Compare commits

...

53 Commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 10:08:53 -07:00
Peter Li adde88078f Textures and samplers on both backends
Texture1D/2D/3D/Cube (and arrays), Texture2DMS, RWTexture*, Buffer and
RWBuffer, SamplerState and SamplerComparisonState. Methods: Sample,
SampleBias, SampleLevel, SampleGrad, SampleCmp, SampleCmpLevelZero,
SampleCmpLevel/Bias/Grad (DXIL 6.7/6.8), Load, operator[] reads and
writes, Gather and GatherCmp (per channel, one offset),
CalculateLevelOfDetail(Unclamped), GetDimensions (textures and buffers)
and, on DXIL, GetSamplePosition. Argument roles come from one shared
decoder (src/ir/texture.zig); out parameters of methods go through
temporaries.

DXIL follows dxc's argument layout (undef padding, zero offsets),
resource metadata and properties, replicated typed stores and the typed
UAV load flag. SPIR-V follows dxc's image types (unknown depth, inferred
formats for typed buffers and RW textures), capabilities and image
operands.

Also: SPIR-V interpolation decorations on pixel inputs and vertex
outputs (as dxc), a crash on array pixel inputs, and a miscompile on both
backends where swizzle components lived in a 16-entry static buffer, so
a function with more than 16 swizzles could silently read the wrong
components. test/spirv/check.sh (part of `zig build oracle`) checks
SPIR-V disassembly like test/dxil/check.sh does for DXIL.

Not yet: status (sparse feedback) arguments, Gather with four offsets,
and texel offsets that need loop unrolling to become constants.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 07:42:59 -07:00
Peter Li 50a86683f2 DXIL vertex and pixel shaders
Signatures follow dxc: semantic interpretation per signature point, a port
of the prefix-stable signature packer (registers and masks match dxc, so
stages link with dxc-compiled ones), canonical system-value names,
SV_Target arrays split per render target, ISG1/OSG1, PSV0 signature
elements and dependency tables, and signature metadata. Inputs and
outputs go through loadInput/storeOutput; shadow and not-in-signature
system values use their intrinsics. Adds discard, clip, derivatives and
fwidth, and signature-driven shader flags.

Also fixes two miscompiles found along the way: static global
initializers were dropped (both backends; they now run on entry in
declaration order, and DXIL keeps static globals in allocas), and DXIL
float constants were written as f64 bit patterns, so every float literal
read back as 0.0.

test/dxil/check.sh (part of `zig build oracle`) compares signatures with
dxc and checks the disassembly, since dxv does not catch wrong values.

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:15:15 -07:00
Peter Li 22df96e507 DXIL backend for compute shaders
src/dxil/emit.zig lowers IR to DXIL: calls are inlined while emitting
(returns merge through phis), values are scalarized, locals become
flattened [N x scalar] allocas, and resources become handles created on
entry (createHandle before SM 6.6, createHandleFromBinding plus
annotateHandle from 6.6). Structured, byte-address and typed buffer
reads and writes use bufferLoad/Store or rawBufferLoad/Store by shader
model; math intrinsics map to dx.op unary / binary / tertiary / dot
operations; compute system values to threadId and friends. The module
carries dx.resources, entry properties (shader flags, numthreads) and a
PSV0 part with resource bindings; dxv accepts the output.

The bitcode writer gains alloca, load, store, getelementptr, unreachable
and aggregate constants. Float-to-int constant folding saturates instead
of panicking on out-of-range values.

zig build oracle-codegen: SPIR-V 281 valid, DXIL 2 valid (compute only so
far), 0 invalid on either backend.

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:59:16 -07:00
Peter Li e8bca47e87 Add semantic analysis (Sema) with dxc-derived oracles
Sema type-checks a parsed translation unit: an interned type table, scopes
and symbols, declarations, statements and expressions, implicit and explicit
conversions, user-function overload resolution, and intrinsic / builtin
method matching driven by dxc's gen_intrin_main.txt (vendored, turned into a
Zig table at build time by tools/gen_intrinsics.zig).

Rules ported from dxc where it matters for exact agreement:
- operator result types (CombineBasicTypes, shift and bool rules)
- literal suffix types and diagnostics, including `1.#INF`
- declaration modifier validity and conflicts (DiagnoseHLSLDecl) and
  row_major / column_major checks, using source-ordered qualifier words
- constant folding of asuint / max / min
- `_Static_assert`, `__decltype` and `std::is_same` builtins
  (`static_assert` is an ordinary identifier in HLSL 2021)

Templates, operator overloading and bitfields report "not supported yet
(planned for milestone 0.2)".

Oracles:
- zig build oracle-sema: no false errors on the 1604 dxc-valid corpus
  files (1537 clean, 67 need milestone 0.2 features)
- zig build oracle-verify: error-line agreement with dxc's SemaHLSL
  -verify tests under HLSL 2021 (53% of expected error lines caught,
  80 false error lines)

Also fixes the provenance commit of gen_intrin_main.txt (55a61aa79).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:17:40 -07:00
138 changed files with 29523 additions and 97 deletions

View File

@ -22,6 +22,18 @@ pub fn build(b: *std.Build) void {
gen_options_run.addFileArg(b.path("vendor/dxc/HLSLOptions.td")); gen_options_run.addFileArg(b.path("vendor/dxc/HLSLOptions.td"));
const options_table = gen_options_run.addOutputFileArg("options_table.zig"); const options_table = gen_options_run.addOutputFileArg("options_table.zig");
// dxc's intrinsic declarations, likewise generated at build time.
const gen_intrinsics = b.addExecutable(.{
.name = "gen_intrinsics",
.root_module = b.createModule(.{
.root_source_file = b.path("tools/gen_intrinsics.zig"),
.target = b.graph.host,
}),
});
const gen_intrinsics_run = b.addRunArtifact(gen_intrinsics);
gen_intrinsics_run.addFileArg(b.path("vendor/dxc/gen_intrin_main.txt"));
const intrinsics_table = gen_intrinsics_run.addOutputFileArg("intrinsics_table.zig");
const mod = b.addModule("zdxc", .{ const mod = b.addModule("zdxc", .{
.root_source_file = b.path("src/root.zig"), .root_source_file = b.path("src/root.zig"),
.target = target, .target = target,
@ -29,6 +41,7 @@ pub fn build(b: *std.Build) void {
.imports = &.{.{ .name = "hlsl_headers", .module = hlsl_headers }}, .imports = &.{.{ .name = "hlsl_headers", .module = hlsl_headers }},
}); });
mod.addAnonymousImport("options_table", .{ .root_source_file = options_table }); mod.addAnonymousImport("options_table", .{ .root_source_file = options_table });
mod.addAnonymousImport("intrinsics_table", .{ .root_source_file = intrinsics_table });
const exe = b.addExecutable(.{ const exe = b.addExecutable(.{
.name = "zdxc", .name = "zdxc",
@ -60,6 +73,16 @@ pub fn build(b: *std.Build) void {
oracle.setCwd(b.path(".")); oracle.setCwd(b.path("."));
oracle.has_side_effects = true; oracle.has_side_effects = true;
oracle_step.dependOn(&oracle.step); oracle_step.dependOn(&oracle.step);
const dxil_checks = b.addSystemCommand(&.{ "sh", "test/dxil/check.sh" });
dxil_checks.addArtifactArg(exe);
dxil_checks.setCwd(b.path("."));
dxil_checks.has_side_effects = true;
oracle_step.dependOn(&dxil_checks.step);
const spirv_checks = b.addSystemCommand(&.{ "sh", "test/spirv/check.sh" });
spirv_checks.addArtifactArg(exe);
spirv_checks.setCwd(b.path("."));
spirv_checks.has_side_effects = true;
oracle_step.dependOn(&spirv_checks.step);
const oracle_parse_step = b.step("oracle-parse", "Parse every dxc-valid corpus file with zdxc"); const oracle_parse_step = b.step("oracle-parse", "Parse every dxc-valid corpus file with zdxc");
const oracle_parse = b.addSystemCommand(&.{ "sh", "test/oracle/parse.sh" }); const oracle_parse = b.addSystemCommand(&.{ "sh", "test/oracle/parse.sh" });
@ -68,6 +91,32 @@ pub fn build(b: *std.Build) void {
oracle_parse.has_side_effects = true; oracle_parse.has_side_effects = true;
oracle_parse_step.dependOn(&oracle_parse.step); oracle_parse_step.dependOn(&oracle_parse.step);
const oracle_sema_step = b.step("oracle-sema", "Check that Sema accepts every dxc-valid corpus file");
const oracle_sema = b.addSystemCommand(&.{ "sh", "test/oracle/sema.sh" });
oracle_sema.addArtifactArg(exe);
oracle_sema.setCwd(b.path("."));
oracle_sema.has_side_effects = true;
oracle_sema.step.dependOn(&oracle_parse.step); // builds the corpus list
oracle_sema_step.dependOn(&oracle_sema.step);
const oracle_codegen_step = b.step("oracle-codegen", "Compile the dxc-valid corpus to SPIR-V and DXIL and validate the output");
for ([_][]const u8{ "spirv", "dxil" }) |backend| {
const run = b.addSystemCommand(&.{ "sh", "test/oracle/codegen.sh" });
run.addArtifactArg(exe);
run.addArg(backend);
run.setCwd(b.path("."));
run.has_side_effects = true;
run.step.dependOn(&oracle_parse.step); // builds the corpus list
oracle_codegen_step.dependOn(&run.step);
}
const oracle_verify_step = b.step("oracle-verify", "Compare Sema errors with dxc's SemaHLSL -verify expectations");
const oracle_verify = b.addSystemCommand(&.{ "sh", "test/oracle/verify.sh" });
oracle_verify.addArtifactArg(exe);
oracle_verify.setCwd(b.path("."));
oracle_verify.has_side_effects = true;
oracle_verify_step.dependOn(&oracle_verify.step);
const oracle_cli_step = b.step("oracle-cli", "Parse every dxc command line in the DXC test corpus"); const oracle_cli_step = b.step("oracle-cli", "Parse every dxc command line in the DXC test corpus");
const oracle_cli = b.addSystemCommand(&.{ "sh", "test/oracle/cli.sh" }); const oracle_cli = b.addSystemCommand(&.{ "sh", "test/oracle/cli.sh" });
oracle_cli.addArtifactArg(exe); oracle_cli.addArtifactArg(exe);

View File

@ -161,6 +161,19 @@ pub const Diagnostics = struct {
_ = d.report(.{ .severity = severity, .loc = loc }, fmt, args); _ = d.report(.{ .severity = severity, .loc = loc }, fmt, args);
} }
/// A point to roll back to (substitution failures are not errors).
pub const Mark = struct { len: usize, errors: u32, warnings: u32 };
pub fn mark(d: *const Diagnostics) Mark {
return .{ .len = d.list.items.len, .errors = d.error_count, .warnings = d.warning_count };
}
pub fn rollback(d: *Diagnostics, m: Mark) void {
d.list.shrinkRetainingCapacity(m.len);
d.error_count = m.errors;
d.warning_count = m.warnings;
}
pub fn hasErrors(d: *const Diagnostics) bool { pub fn hasErrors(d: *const Diagnostics) bool {
return d.error_count != 0; return d.error_count != 0;
} }

4895
src/dxil/emit.zig Normal file

File diff suppressed because it is too large Load Diff

316
src/dxil/libinfo.zig Normal file
View File

@ -0,0 +1,316 @@
//! Per-function shader flags and compatibility (valid stages, minimum
//! shader model) of a DXIL library, computed from the emitted
//! instructions the way dxc's ShaderFlags::CollectShaderFlags and
//! DxilModule::ComputeShaderCompatInfo compute them (validator 1.8+):
//! the validator rebuilds RDAT from these and compares.
const std = @import("std");
const module = @import("module.zig");
const op_compat = @import("op_compat.zig");
/// What a resource global (by module global index) is, for flags that
/// depend on the handles a function uses.
pub const GlobalRes = struct { uav: bool, typed_multi: bool = false };
pub const Options = struct {
/// -enable-16bit-types (native low precision).
native16: bool,
/// DXIL 1.7+: functions using UAVs set ResMayNotAlias.
res_may_not_alias: bool,
globals: []const ?GlobalRes,
};
pub const Info = struct {
/// Shader flags (bit positions of dxc's ShaderFlags raw value).
flags: u64 = 0,
min_minor: u8 = 0,
mask: u32 = op_compat.all_stages,
};
pub const bit = struct {
pub const double = 1 << 2;
pub const raw_structured = 1 << 4;
pub const low_precision = 1 << 5;
pub const double_extensions = 1 << 6;
pub const msad = 1 << 7;
pub const inner_coverage = 1 << 10;
pub const tiled_resources = 1 << 12;
pub const typed_uav_load = 1 << 13;
pub const wave = 1 << 19;
pub const int64 = 1 << 20;
pub const view_id = 1 << 21;
pub const barycentrics = 1 << 22;
pub const native_low_precision = 1 << 23;
pub const raytracing_1_1 = 1 << 25;
pub const sampler_feedback = 1 << 26;
pub const resource_heap = 1 << 30;
pub const sampler_heap = 1 << 31;
pub const res_may_not_alias = 1 << 33;
pub const advanced_texture_ops = 1 << 34;
pub const extended_command_info = 1 << 38;
pub const uses_derivatives = 1 << 39;
pub const requires_group = 1 << 40;
/// Not part of the module's flags.
pub const local = uses_derivatives | requires_group;
};
const stage_group: u32 = (1 << 5) | (1 << 13) | (1 << 14) | (1 << 15) | (1 << 6); // CS, MS, AS, Node, Library
pub fn analyze(m: *const module.Module, f: *const module.Function, o: Options) Info {
var info: Info = .{};
const fty = m.types.items[f.ty].function;
var fl: u64 = 0;
var has16 = false;
var check_access = false;
var lod_clamp = false;
var uses_uav = false;
for (f.insts.items) |inst| {
// Calls to other functions only count through their dx ops.
var op: ?u32 = null;
if (inst.op == .call) {
const callee = m.functions.items[inst.op.call.callee];
if (!std.mem.startsWith(u8, callee.name, "dx.op.")) continue;
if (inst.op.call.args.len > 0) op = constInt(m, inst.op.call.args[0]);
}
// (dxc ignores vector element instructions here.)
if (inst.op == .extractelement or inst.op == .insertelement) continue;
var types_seen: [8]module.TypeId = undefined;
var n: usize = 0;
types_seen[n] = inst.ty;
n += 1;
var operands: [4]?module.Value = .{ null, null, null, null };
const all_args: []const module.Value = switch (inst.op) {
.call => |c| c.args,
.gep => |g| g.indices,
else => &.{},
};
switch (inst.op) {
.binop => |b| operands = .{ b.lhs, b.rhs, null, null },
.cast => |c| operands[0] = c.val,
.cmp => |c| operands = .{ c.lhs, c.rhs, null, null },
.select => |s| operands = .{ s.cond, s.t, s.f, null },
.extractvalue => |x| operands[0] = x.agg,
.load => |x| operands[0] = x.ptr,
.store => |x| operands = .{ x.ptr, x.val, null, null },
.gep => |g| operands[0] = g.ptr,
.atomicrmw => |x| operands = .{ x.ptr, x.val, null, null },
.cmpxchg => |x| operands = .{ x.ptr, x.cmp, x.new, null },
.ret => |r| operands[0] = r,
.br => |b| operands[0] = b.cond,
.@"switch" => |s| operands[0] = s.cond,
.alloca => |a| operands[0] = a.size,
else => {},
}
var is_double = false;
var is_int64 = false;
var is16 = false;
const visit = struct {
fn t(mm: *const module.Module, ty: module.TypeId, d: *bool, i64_: *bool, h: *bool, group: *bool) void {
switch (mm.types.items[ty]) {
.double => d.* = true,
.half => h.* = true,
.int => |w| {
if (w == 64) i64_.* = true;
if (w == 16) h.* = true;
},
.pointer => |p| if (p.addr_space == 3) {
group.* = true;
},
else => {},
}
}
};
var group = false;
visit.t(m, inst.ty, &is_double, &is_int64, &is16, &group);
for (operands) |ov| if (ov) |v| if (valueType(m, f, fty, v)) |vt| visit.t(m, vt, &is_double, &is_int64, &is16, &group);
for (all_args) |v| if (valueType(m, f, fty, v)) |vt| visit.t(m, vt, &is_double, &is_int64, &is16, &group);
if (group) fl |= bit.requires_group;
if (is_double) {
fl |= bit.double;
switch (inst.op) {
// (fdiv is sdiv on floating point types)
.binop => |b| if (b.op == .sdiv and isFloatOp(m, inst.ty)) {
fl |= bit.double_extensions;
},
.cast => |c| switch (c.op) {
.uitofp, .sitofp, .fptoui, .fptosi => fl |= bit.double_extensions,
else => {},
},
else => {},
}
}
if (is_int64) fl |= bit.int64;
if (is16) has16 = true;
const code = op orelse continue;
const c = op_compat.get(code);
info.min_minor = @max(info.min_minor, c.minor);
info.mask &= c.mask;
const args = inst.op.call.args;
if ((code >= 110 and code <= 123) or (code >= 135 and code <= 136) or (code >= 165 and code <= 167) or code == 222 or (code >= 312 and code <= 313)) fl |= bit.wave;
if (code >= 174 and code <= 177) fl |= bit.sampler_feedback;
switch (code) {
71 => check_access = true,
50 => fl |= bit.msad,
91 => fl |= bit.inner_coverage,
138 => fl |= bit.view_id,
137 => fl |= bit.barycentrics,
178, 258, 213 => fl |= bit.raytracing_1_1,
60, 61, 64, 81, 83, 84, 85, 86 => {
fl |= bit.uses_derivatives;
if (code != 81 and code < 83 and clampArg(m, code, args)) lod_clamp = true;
},
62, 63 => if (code == 63 and clampArg(m, code, args)) {
lod_clamp = true;
},
68, 66 => if (handleRes(m, f, o, args[1])) |r| if (r.uav and r.typed_multi) {
fl |= bit.typed_uav_load;
},
218 => {
if (args.len > 2 and constInt(m, args[2]) == 1) fl |= bit.sampler_heap else fl |= bit.resource_heap;
},
57 => if (args.len > 1 and constInt(m, args[1]) == 1) {
uses_uav = true;
},
160 => if (handleRes(m, f, o, args[1])) |r| if (r.uav) {
uses_uav = true;
},
216 => if (args.len > 2 and annotateIsUav(m, args[2])) {
uses_uav = true;
},
256, 257 => fl |= bit.extended_command_info,
80 => if (args.len > 1) if (constInt(m, args[1])) |mode| if (mode != 2) {
fl |= bit.requires_group;
info.mask &= stage_group;
},
else => {},
}
}
if (has16) fl |= bit.low_precision;
if (o.native16) fl |= bit.native_low_precision;
if (check_access or lod_clamp) fl |= bit.tiled_resources;
if (o.res_may_not_alias and uses_uav) fl |= bit.res_may_not_alias;
info.flags = fl;
return info;
}
/// The minimum shader model of an entry (or library function) given its
/// flags (AdjustMinimumShaderModelAndFlags).
pub fn minMinor(info: Info, kind: ?u32) u8 {
var v = info.min_minor;
const fl = info.flags;
if (kind) |k| {
if (fl & bit.uses_derivatives != 0 and (k == 5 or k == 13 or k == 14)) v = @max(v, 6);
if (k == 13 or k == 14) v = @max(v, 5) else if (k >= 7 and k <= 12) v = @max(v, 3) else if (k == 15) v = @max(v, 8);
}
if (fl & bit.extended_command_info != 0) {
v = @max(v, 8);
} else if (fl & bit.advanced_texture_ops != 0) {
v = @max(v, 7);
} else if (fl & (bit.resource_heap | bit.sampler_heap) != 0) {
v = @max(v, 6);
} else if (fl & (bit.raytracing_1_1 | bit.sampler_feedback) != 0) {
v = @max(v, 5);
} else if (fl & bit.low_precision != 0 and fl & bit.native_low_precision != 0) {
v = @max(v, 2);
} else if (fl & (bit.view_id | bit.barycentrics) != 0) {
v = @max(v, 1);
}
return v;
}
/// Feature info bits (SFI0 / RDAT) of shader flags.
pub fn featureInfo(fl: u64) u64 {
const map = [_][2]u64{
.{ bit.double, 0x1 }, .{ 1 << 16, 0x4 }, .{ 1 << 15, 0x8 },
.{ bit.double_extensions, 0x20 }, .{ bit.msad, 0x40 }, .{ 1 << 11, 0x200 },
.{ bit.inner_coverage, 0x400 }, .{ 1 << 9, 0x2000 }, .{ bit.int64, 0x8000 },
.{ bit.view_id, 0x10000 }, .{ 1 << 24, 0x80000 }, .{ bit.wave, 0x4000 },
.{ 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 }, .{ bit.raytracing_1_1, 0x100000 }, .{ bit.sampler_feedback, 0x200000 },
.{ bit.advanced_texture_ops, 0x20000000 }, .{ bit.uses_derivatives, 0x100 << 32 }, .{ bit.requires_group, 0x200 << 32 },
};
var out: u64 = 0;
for (map) |e| if (fl & e[0] != 0) {
out |= e[1];
};
if (fl & bit.low_precision != 0) out |= if (fl & bit.native_low_precision != 0) 0x40000 else 0x10;
return out;
}
fn constInt(m: *const module.Module, v: module.Value) ?u32 {
if (v != .constant) return null;
const c = m.constants.items[v.constant];
return switch (c.kind) {
.int => |x| @truncate(@as(u64, @bitCast(x))),
else => null,
};
}
fn isFloatOp(m: *const module.Module, ty: module.TypeId) bool {
return switch (m.types.items[ty]) {
.half, .float, .double => true,
else => false,
};
}
/// Sample / SampleBias / SampleCmp and SampleGrad: a clamp operand that is
/// not undef.
fn clampArg(m: *const module.Module, code: u32, args: []const module.Value) bool {
const idx: usize = switch (code) {
60 => 10,
61 => 11,
64 => 11,
63 => 16,
else => return false,
};
if (idx >= args.len) return false;
const v = args[idx];
if (v != .constant) return true;
return m.constants.items[v.constant].kind != .undef;
}
fn annotateIsUav(m: *const module.Module, props: module.Value) bool {
if (props != .constant) return false;
const c = m.constants.items[props.constant];
if (c.kind != .aggregate or c.kind.aggregate.len == 0) return false;
const basic = m.constants.items[c.kind.aggregate[0]];
return basic.kind == .int and basic.kind.int & 0x1000 != 0;
}
/// The resource global behind a handle made by createHandleForLib (of a
/// loaded global), possibly annotated.
fn handleRes(m: *const module.Module, f: *const module.Function, o: Options, h: module.Value) ?GlobalRes {
var v = h;
var steps: u32 = 0;
while (steps < 4) : (steps += 1) {
if (v != .inst) return null;
const inst = f.insts.items[v.inst];
switch (inst.op) {
.call => |c| {
const code = if (c.args.len > 0) constInt(m, c.args[0]) else null;
if (code == 216 or code == 160) {
v = c.args[1];
continue;
}
return null;
},
.load => |l| {
if (l.ptr == .global) return o.globals[l.ptr.global];
return null;
},
else => return null,
}
}
return null;
}
fn valueType(m: *const module.Module, f: *const module.Function, fty: @FieldType(module.Type, "function"), v: module.Value) ?module.TypeId {
return switch (v) {
.global => |g| m.globals.items[g].ptr_ty,
.function => null,
.constant => |c| m.constants.items[c].ty,
.arg => |a| fty.params[a],
.inst => |i| f.insts.items[i].ty,
};
}

181
src/dxil/mangle.zig Normal file
View File

@ -0,0 +1,181 @@
//! Microsoft-style C++ name mangling of library functions and resource
//! globals, as dxc spells them (`\x01?name@@YAXXZ`). D3D12 refers to
//! library exports by the unmangled name (recorded in RDAT next to this
//! one), so near enough is good enough for unusual types.
const std = @import("std");
const Allocator = std.mem.Allocator;
const types = @import("../sema/types.zig");
const TypeTable = types.TypeTable;
const TypeId = types.TypeId;
pub const Param = struct { ty: TypeId, by_ref: bool = false };
/// Names already spelled (the function's own first): later uses of a
/// struct or class template name are back-references (`U1@`, `V1@`).
const Names = struct {
list: std.ArrayList([]const u8) = .empty,
fn find(n: *Names, name: []const u8) ?usize {
for (n.list.items, 0..) |x, k| if (std.mem.eql(u8, x, name)) return k;
return null;
}
fn add(n: *Names, a: Allocator, name: []const u8) Allocator.Error!void {
if (n.list.items.len < 10 and n.find(name) == null) try n.list.append(a, name);
}
};
/// `\x01?name@@YA<ret><params>Z`.
pub fn function(a: Allocator, t: *TypeTable, name: []const u8, ret: TypeId, params: []const Param) Allocator.Error![]u8 {
var out: std.ArrayList(u8) = .empty;
var names: Names = .{};
try names.add(a, name);
try out.print(a, "\x01?{s}@@YA", .{name});
// Parameter types spelled with more than one character are numbered;
// repeats are back-references.
var refs: std.ArrayList(Param) = .empty;
const rt = t.get(ret);
if (rt == .@"struct" or rt == .matrix or (rt == .vector and rt.vector.len > 1) or rt == .resource) try out.appendSlice(a, "?A");
try typeCode(a, t, ret, &out, &names);
if (params.len == 0) {
try out.append(a, 'X');
} else {
for (params) |p0| {
// (inout structs are passed as values, as in dxc.)
const p: Param = .{ .ty = p0.ty, .by_ref = p0.by_ref and t.get(p0.ty) != .@"struct" };
const back = for (refs.items, 0..) |r, k| {
if (r.ty == p.ty and r.by_ref == p.by_ref) break k;
} else null;
if (back) |k| if (k < 10) {
try out.append(a, '0' + @as(u8, @intCast(k)));
continue;
};
var code: std.ArrayList(u8) = .empty;
if (p.by_ref) try code.appendSlice(a, "AIA");
try typeCode(a, t, p.ty, &code, &names);
try out.appendSlice(a, code.items);
if (code.items.len > 1 and back == null) try refs.append(a, p);
}
try out.append(a, '@');
}
try out.append(a, 'Z');
return out.items;
}
/// `\x01?name@@3<type>A` (a global variable).
pub fn global(a: Allocator, t: *TypeTable, name: []const u8, ty: TypeId) Allocator.Error![]u8 {
var out: std.ArrayList(u8) = .empty;
var names: Names = .{};
try names.add(a, name);
try out.print(a, "\x01?{s}@@3", .{name});
try typeCode(a, t, ty, &out, &names);
try out.append(a, 'A');
return out.items;
}
fn number(a: Allocator, n: u64, out: *std.ArrayList(u8)) Allocator.Error!void {
if (n >= 1 and n <= 10) return out.append(a, '0' + @as(u8, @intCast(n - 1)));
if (n == 0) return out.appendSlice(a, "A@");
var buf: [16]u8 = undefined;
var k: usize = buf.len;
var v = n;
while (v != 0) : (v >>= 4) {
k -= 1;
buf[k] = 'A' + @as(u8, @intCast(v & 0xf));
}
try out.appendSlice(a, buf[k..]);
try out.append(a, '@');
}
fn scalarCode(s: types.Scalar) []const u8 {
return switch (s) {
.bool => "_N",
.int, .literal_int => "H",
.uint => "I",
.float, .literal_float => "M",
.double => "N",
.half => "$halff@",
.float16 => "$f16@",
.int16 => "F",
.uint16 => "G",
.int64 => "_J",
.uint64 => "_K",
.min16float => "$min16f@",
.min10float => "$min10f@",
.min16int => "$min16i@",
.min12int => "$min12i@",
.min16uint => "$min16ui@",
else => "H",
};
}
fn typeCode(a: Allocator, t: *TypeTable, ty: TypeId, out: *std.ArrayList(u8), names: *Names) Allocator.Error!void {
if (ty == TypeTable.void_type) return out.append(a, 'X');
switch (t.get(ty)) {
.scalar => |s| try out.appendSlice(a, scalarCode(s)),
.@"enum" => |en| try className(a, 'W', try std.fmt.allocPrint(a, "4{s}", .{en.name}), out, names),
.vector => |v| {
var args: std.ArrayList(u8) = .empty;
try args.appendSlice(a, scalarCode(v.elem));
try args.appendSlice(a, "$0");
try number(a, v.len, &args);
try className(a, 'V', try std.fmt.allocPrint(a, "?$vector@{s}@", .{args.items}), out, names);
},
.matrix => |m| {
var args: std.ArrayList(u8) = .empty;
try args.appendSlice(a, scalarCode(m.elem));
try args.appendSlice(a, "$0");
try number(a, m.rows, &args);
try args.appendSlice(a, "$0");
try number(a, m.cols, &args);
try className(a, 'V', try std.fmt.allocPrint(a, "?$matrix@{s}@", .{args.items}), out, names);
},
.array => {
// Y<dims - 1><dim>...<element>
var dims: std.ArrayList(u32) = .empty;
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);
for (dims.items) |d| try number(a, d, out);
try typeCode(a, t, et, out, names);
},
.@"struct" => |st| try className(a, 'U', st.name, out, names),
.resource => |r| {
if (r.elem == TypeTable.void_type or r.kind == .raytracing_acceleration_structure) return className(a, 'U', r.name, out, names);
// Template arguments have names of their own.
var args: std.ArrayList(u8) = .empty;
var inner: Names = .{};
try inner.add(a, r.name);
try typeCode(a, t, r.elem, &args, &inner);
try className(a, 'V', try std.fmt.allocPrint(a, "?${s}@{s}@", .{ r.name, args.items }), out, names);
},
.sampler => |s| try className(a, 'U', if (s.comparison) "SamplerComparisonState" else "SamplerState", out, names),
.patch => |p| {
var args: std.ArrayList(u8) = .empty;
var inner: Names = .{};
const pname = if (p.output) "OutputPatch" else "InputPatch";
try inner.add(a, pname);
try typeCode(a, t, p.elem, &args, &inner);
try args.appendSlice(a, "$0");
try number(a, p.count, &args);
try className(a, 'V', try std.fmt.allocPrint(a, "?${s}@{s}@", .{ pname, args.items }), out, names);
},
else => try out.append(a, 'X'),
}
}
/// `<kind><name>@@`, or `<kind><backref>@` for a name already spelled
/// (template instances `?$name@args@` end in `@` themselves).
fn className(a: Allocator, kind: u8, name: []const u8, out: *std.ArrayList(u8), names: *Names) Allocator.Error!void {
try out.append(a, kind);
if (names.find(name)) |k| {
try out.append(a, '0' + @as(u8, @intCast(k)));
return out.append(a, '@');
}
try out.appendSlice(a, name);
if (name[0] != '?') try out.append(a, '@');
try out.append(a, '@');
try names.add(a, name);
}

View File

@ -47,15 +47,19 @@ pub const Constant = struct {
float_bits: u64, float_bits: u64,
undef, undef,
null, null,
/// Struct / array / vector of earlier constants.
aggregate: []const ConstId,
}, },
}; };
pub const Linkage = enum(u32) { external = 0, internal = 3 }; pub const Linkage = enum(u32) { external = 0, internal = 3 };
/// Attribute group for function declarations (e.g. dx.op functions). /// Attribute group for function declarations (e.g. dx.op functions).
pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly }; pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly, noreturn_nounwind };
pub const Value = union(enum) { pub const Value = union(enum) {
/// Index into Module.globals (a pointer to the variable).
global: u32,
/// Index into Module.functions. /// Index into Module.functions.
function: u32, function: u32,
constant: ConstId, constant: ConstId,
@ -65,6 +69,12 @@ pub const Value = union(enum) {
}; };
pub const BinOp = enum(u32) { add = 0, sub = 1, mul = 2, udiv = 3, sdiv = 4, urem = 5, srem = 6, shl = 7, lshr = 8, ashr = 9, @"and" = 10, @"or" = 11, xor = 12 }; pub const BinOp = enum(u32) { add = 0, sub = 1, mul = 2, udiv = 3, sdiv = 4, urem = 5, srem = 6, shl = 7, lshr = 8, ashr = 9, @"and" = 10, @"or" = 11, xor = 12 };
pub const RmwOp = enum(u32) { xchg = 0, add = 1, sub = 2, @"and" = 3, nand = 4, @"or" = 5, xor = 6, max = 7, min = 8, umax = 9, umin = 10 };
/// A module-level variable (groupshared memory: address space 3),
/// declared without an initializer as dxc does.
pub const GlobalVar = struct { name: []const u8, ty: TypeId, addr_space: u32, ptr_ty: TypeId, constant: bool = false };
pub const CastOp = enum(u32) { trunc = 0, zext = 1, sext = 2, fptoui = 3, fptosi = 4, uitofp = 5, sitofp = 6, fptrunc = 7, fpext = 8, ptrtoint = 9, inttoptr = 10, bitcast = 11 }; pub const CastOp = enum(u32) { trunc = 0, zext = 1, sext = 2, fptoui = 3, fptosi = 4, uitofp = 5, sitofp = 6, fptrunc = 7, fpext = 8, ptrtoint = 9, inttoptr = 10, bitcast = 11 };
pub const Inst = struct { pub const Inst = struct {
@ -73,6 +83,8 @@ pub const Inst = struct {
op: union(enum) { op: union(enum) {
ret: ?Value, ret: ?Value,
br: struct { then: u32, @"else": ?u32 = null, cond: ?Value = null }, br: struct { then: u32, @"else": ?u32 = null, cond: ?Value = null },
/// Case values are constants.
@"switch": struct { cond: Value, default: u32, cases: []const struct { val: Value, block: u32 } },
call: struct { callee: u32, args: []const Value }, call: struct { callee: u32, args: []const Value },
binop: struct { op: BinOp, lhs: Value, rhs: Value, flags: u32 = 0 }, binop: struct { op: BinOp, lhs: Value, rhs: Value, flags: u32 = 0 },
cast: struct { op: CastOp, val: Value }, cast: struct { op: CastOp, val: Value },
@ -80,6 +92,19 @@ pub const Inst = struct {
select: struct { cond: Value, t: Value, f: Value }, select: struct { cond: Value, t: Value, f: Value },
extractvalue: struct { agg: Value, index: u32 }, extractvalue: struct { agg: Value, index: u32 },
phi: struct { incoming: []const struct { val: Value, block: u32 } }, phi: struct { incoming: []const struct { val: Value, block: u32 } },
/// `ty` is the pointer type; `elem` the allocated type.
alloca: struct { elem: TypeId, size: Value },
load: struct { ptr: Value, @"align": u32 },
store: struct { ptr: Value, val: Value, @"align": u32 },
/// `ty` is the result pointer type; `elem` the source element type.
gep: struct { elem: TypeId, ptr: Value, indices: []const Value },
/// Sequentially consistent read-modify-write; yields the old value.
atomicrmw: struct { op: RmwOp, ptr: Value, val: Value },
/// Yields `{ old, success }` (`ty` is that literal struct).
cmpxchg: struct { ptr: Value, cmp: Value, new: Value },
@"unreachable",
extractelement: struct { vec: Value, index: Value },
insertelement: struct { vec: Value, val: Value, index: Value },
}, },
}; };
@ -108,6 +133,7 @@ pub const Module = struct {
types: std.ArrayList(Type) = .empty, types: std.ArrayList(Type) = .empty,
constants: std.ArrayList(Constant) = .empty, constants: std.ArrayList(Constant) = .empty,
functions: std.ArrayList(Function) = .empty, functions: std.ArrayList(Function) = .empty,
globals: std.ArrayList(GlobalVar) = .empty,
metadata: std.ArrayList(Metadata) = .empty, metadata: std.ArrayList(Metadata) = .empty,
named_metadata: std.ArrayList(struct { name: []const u8, nodes: []const MdId }) = .empty, named_metadata: std.ArrayList(struct { name: []const u8, nodes: []const MdId }) = .empty,
@ -162,6 +188,12 @@ pub const Module = struct {
unreachable; unreachable;
} }
pub fn addGlobal(m: *Module, name: []const u8, ty: TypeId, addr_space: u32) !Value {
const ptr_ty = try m.getType(.{ .pointer = .{ .elem = ty, .addr_space = addr_space } });
try m.globals.append(m.allocator(), .{ .name = try m.allocator().dupe(u8, name), .ty = ty, .addr_space = addr_space, .ptr_ty = ptr_ty });
return .{ .global = @intCast(m.globals.items.len - 1) };
}
pub fn constant(m: *Module, c: Constant) !Value { pub fn constant(m: *Module, c: Constant) !Value {
for (m.constants.items, 0..) |existing, i| { for (m.constants.items, 0..) |existing, i| {
if (existing.ty == c.ty and std.meta.eql(existing.kind, c.kind)) return .{ .constant = @intCast(i) }; if (existing.ty == c.ty and std.meta.eql(existing.kind, c.kind)) return .{ .constant = @intCast(i) };
@ -259,15 +291,17 @@ const Encoder = struct {
} }
fn moduleValueCount(e: *Encoder) u32 { fn moduleValueCount(e: *Encoder) u32 {
return @intCast(e.m.functions.items.len + e.m.constants.items.len); return @intCast(e.m.globals.items.len + e.m.functions.items.len + e.m.constants.items.len);
} }
/// Absolute value ID. Module values: functions, then constants. /// Absolute value ID. Module values: globals, functions, constants.
fn valueId(e: *Encoder, f: ?*const Function, v: Value) u32 { fn valueId(e: *Encoder, f: ?*const Function, v: Value) u32 {
const nglobals: u32 = @intCast(e.m.globals.items.len);
const nfuncs: u32 = @intCast(e.m.functions.items.len); const nfuncs: u32 = @intCast(e.m.functions.items.len);
return switch (v) { return switch (v) {
.function => |i| i, .global => |i| i,
.constant => |c| nfuncs + c, .function => |i| nglobals + i,
.constant => |c| nglobals + nfuncs + c,
.arg => |a| e.moduleValueCount() + a, .arg => |a| e.moduleValueCount() + a,
.inst => |i| blk: { .inst => |i| blk: {
const func = f.?; const func = f.?;
@ -283,6 +317,7 @@ const Encoder = struct {
fn typeOf(e: *Encoder, f: ?*const Function, v: Value) TypeId { fn typeOf(e: *Encoder, f: ?*const Function, v: Value) TypeId {
return switch (v) { return switch (v) {
.global => |i| e.m.globals.items[i].ptr_ty,
.function => |i| e.m.ptrTypeConst(e.m.functions.items[i].ty), .function => |i| e.m.ptrTypeConst(e.m.functions.items[i].ty),
.constant => |c| e.m.constants.items[c].ty, .constant => |c| e.m.constants.items[c].ty,
.arg => |a| e.m.types.items[f.?.ty].function.params[a], .arg => |a| e.m.types.items[f.?.ty].function.params[a],
@ -318,6 +353,12 @@ const Encoder = struct {
try e.writeTypes(); try e.writeTypes();
try w.recordString(2, &.{}, e.m.triple); try w.recordString(2, &.{}, e.m.triple);
try w.recordString(3, &.{}, e.m.datalayout); try w.recordString(3, &.{}, e.m.datalayout);
for (e.m.globals.items) |g| {
// GLOBALVAR: [type, addrspace << 2 | explicit type, init (none),
// linkage (external), align 4, section]
try e.ops.appendSlice(e.gpa(), &.{ g.ty, (@as(u64, g.addr_space) << 2) | 2 | @intFromBool(g.constant), 0, 0, 3, 0 });
try e.rec(7);
}
for (e.m.functions.items) |f| { for (e.m.functions.items) |f| {
// FUNCTION: [type, cc, isproto, linkage, paramattr, align, section, // FUNCTION: [type, cc, isproto, linkage, paramattr, align, section,
// visibility, gc, unnamed_addr, prologue, dllstorage, // visibility, gc, unnamed_addr, prologue, dllstorage,
@ -341,11 +382,11 @@ const Encoder = struct {
} }
fn writeAttributes(e: *Encoder) !void { fn writeAttributes(e: *Encoder) !void {
// Groups 1..3 match FnAttrs order; each applies to the function (index 0xFFFFFFFF). // Groups 1..4 match FnAttrs order; each applies to the function (index 0xFFFFFFFF).
// Attribute kinds: nounwind = 18, readnone = 20, readonly = 21. // Attribute kinds: noreturn = 17, nounwind = 18, readnone = 20, readonly = 21.
const w = &e.w; const w = &e.w;
try w.enterBlock(block_paramattr_group, 3); try w.enterBlock(block_paramattr_group, 3);
const groups = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 } }; const groups = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 }, &.{ 17, 18 } };
for (groups, 1..) |kinds, id| { for (groups, 1..) |kinds, id| {
try e.push(id); try e.push(id);
try e.push(0xFFFFFFFF); try e.push(0xFFFFFFFF);
@ -435,6 +476,10 @@ const Encoder = struct {
}, },
.undef => try e.rec(3), .undef => try e.rec(3),
.null => try e.rec(2), .null => try e.rec(2),
.aggregate => |elems| {
for (elems) |el| try e.push(e.valueId(null, .{ .constant = el }));
try e.rec(7); // CST_CODE_AGGREGATE
},
} }
} }
try w.endBlock(); try w.endBlock();
@ -480,7 +525,9 @@ const Encoder = struct {
} }
}.lt); }.lt);
try w.enterBlock(block_value_symtab, 4); try w.enterBlock(block_value_symtab, 4);
for (order) |i| try w.recordString(1, &.{i}, funcs[i].name); // VST_ENTRY const nglobals: u32 = @intCast(e.m.globals.items.len);
for (e.m.globals.items, 0..) |g, i| try w.recordString(1, &.{i}, g.name);
for (order) |i| try w.recordString(1, &.{nglobals + i}, funcs[i].name); // VST_ENTRY
try w.endBlock(); try w.endBlock();
} }
@ -498,6 +545,17 @@ const Encoder = struct {
if (v) |val| try e.pushValueAndType(f, inst_id, val); if (v) |val| try e.pushValueAndType(f, inst_id, val);
try e.rec(10); try e.rec(10);
}, },
.@"switch" => |sw| {
// SWITCH: [opty, cond, default, (case value id, block)...]
try e.push(e.typeOf(f, sw.cond));
try e.pushValue(f, inst_id, sw.cond);
try e.push(sw.default);
for (sw.cases) |c| {
try e.push(e.valueId(f, c.val));
try e.push(c.block);
}
try e.rec(12);
},
.br => |b| { .br => |b| {
try e.push(b.then); try e.push(b.then);
if (b.@"else") |el| { if (b.@"else") |el| {
@ -545,6 +603,62 @@ const Encoder = struct {
try e.push(x.index); try e.push(x.index);
try e.rec(26); try e.rec(26);
}, },
.alloca => |a| {
try e.push(a.elem);
try e.push(e.typeOf(f, a.size));
try e.push(e.valueId(f, a.size)); // absolute
try e.push(@as(u64, std.math.log2_int(u32, 4)) + 1 | (1 << 6)); // align 4, explicit type
try e.rec(19);
},
.load => |l| {
try e.pushValueAndType(f, inst_id, l.ptr);
try e.push(inst.ty);
try e.push(@as(u64, std.math.log2_int(u32, l.@"align")) + 1);
try e.push(0);
try e.rec(20);
},
.store => |s| {
try e.pushValueAndType(f, inst_id, s.ptr);
try e.pushValueAndType(f, inst_id, s.val);
try e.push(@as(u64, std.math.log2_int(u32, s.@"align")) + 1);
try e.push(0);
try e.rec(44);
},
.gep => |g| {
try e.push(1); // inbounds
try e.push(g.elem);
try e.pushValueAndType(f, inst_id, g.ptr);
for (g.indices) |x| try e.pushValueAndType(f, inst_id, x);
try e.rec(43);
},
.@"unreachable" => try e.rec(15),
.extractelement => |x| {
try e.pushValueAndType(f, inst_id, x.vec);
try e.pushValueAndType(f, inst_id, x.index);
try e.rec(6); // INST_EXTRACTELT
},
.insertelement => |x| {
try e.pushValueAndType(f, inst_id, x.vec);
try e.pushValue(f, inst_id, x.val);
try e.pushValueAndType(f, inst_id, x.index);
try e.rec(7); // INST_INSERTELT
},
.atomicrmw => |a| {
// ATOMICRMW: [ptr, val, op, volatile, ordering, scope]
try e.pushValueAndType(f, inst_id, a.ptr);
try e.pushValue(f, inst_id, a.val);
try e.ops.appendSlice(e.gpa(), &.{ @backingInt(a.op), 0, 6, 1 }); // seq_cst, cross-thread
try e.rec(38);
},
.cmpxchg => |c| {
// CMPXCHG: [ptr, cmp, new, volatile, success ordering,
// scope, failure ordering, weak]
try e.pushValueAndType(f, inst_id, c.ptr);
try e.pushValueAndType(f, inst_id, c.cmp);
try e.pushValue(f, inst_id, c.new);
try e.ops.appendSlice(e.gpa(), &.{ 0, 6, 1, 6, 0 });
try e.rec(46);
},
.phi => |p| { .phi => |p| {
try e.push(inst.ty); try e.push(inst.ty);
for (p.incoming) |in| { for (p.incoming) |in| {

219
src/dxil/op_compat.zig Normal file
View File

@ -0,0 +1,219 @@
//! Minimum shader model and valid shader stages of each DXIL operation, as
//! used for library compatibility info (RDAT). Generated from the
//! OPCODE-SMMASK block of dxc's lib/DXIL/DxilOperations.cpp
//! (OP::GetMinShaderModelAndMask, with translation, as for libraries) at
//! commit f9fc72ad3.
/// Shader stage bits (1 << DXIL::ShaderKind).
pub const all_stages: u32 = 0xffff;
pub const Compat = struct { minor: u8, mask: u32 };
/// Entries for operations other than shader model 6.0 in every stage.
const table = [_]struct { u16, u8, u32 }{
.{ 60, 0, 0xe061 },
.{ 61, 0, 0xe061 },
.{ 64, 0, 0xe061 },
.{ 76, 0, 0x1 },
.{ 77, 0, 0x1 },
.{ 81, 0, 0xe061 },
.{ 82, 0, 0x1 },
.{ 83, 0, 0xe061 },
.{ 84, 0, 0xe061 },
.{ 85, 0, 0xe061 },
.{ 86, 0, 0xe061 },
.{ 87, 0, 0x1 },
.{ 88, 0, 0x1 },
.{ 89, 0, 0x1 },
.{ 90, 0, 0x1 },
.{ 91, 0, 0x1 },
.{ 92, 0, 0x1 },
.{ 93, 0, 0xe020 },
.{ 94, 0, 0xe020 },
.{ 95, 0, 0xe020 },
.{ 96, 0, 0xe020 },
.{ 97, 0, 0x4 },
.{ 98, 0, 0x4 },
.{ 99, 0, 0x4 },
.{ 100, 0, 0x4 },
.{ 103, 0, 0x18 },
.{ 104, 0, 0x18 },
.{ 105, 0, 0x10 },
.{ 106, 0, 0x8 },
.{ 107, 0, 0x8 },
.{ 108, 0, 0x1c },
.{ 122, 0, 0xe061 },
.{ 123, 0, 0xe061 },
.{ 137, 1, 0x1 },
.{ 138, 1, 0x201f },
.{ 141, 3, 0x740 },
.{ 142, 3, 0x740 },
.{ 143, 3, 0x740 },
.{ 144, 3, 0xf40 },
.{ 145, 3, 0x1fc0 },
.{ 146, 3, 0x1fc0 },
.{ 147, 3, 0xf40 },
.{ 148, 3, 0xf40 },
.{ 149, 3, 0x740 },
.{ 150, 3, 0x740 },
.{ 151, 3, 0x740 },
.{ 152, 3, 0x740 },
.{ 153, 3, 0xf40 },
.{ 154, 3, 0xf40 },
.{ 155, 3, 0x200 },
.{ 156, 3, 0x200 },
.{ 157, 3, 0xcc0 },
.{ 158, 3, 0x140 },
.{ 159, 3, 0x1cc0 },
.{ 161, 3, 0x740 },
.{ 162, 4, 0xffff },
.{ 163, 4, 0xffff },
.{ 164, 4, 0xffff },
.{ 165, 5, 0xffff },
.{ 166, 5, 0xffff },
.{ 167, 5, 0xffff },
.{ 168, 5, 0x2000 },
.{ 169, 5, 0x2000 },
.{ 170, 5, 0x2000 },
.{ 171, 5, 0x2000 },
.{ 172, 5, 0x2000 },
.{ 173, 5, 0x4000 },
.{ 174, 5, 0x41 },
.{ 175, 5, 0x41 },
.{ 176, 5, 0xffff },
.{ 177, 5, 0xffff },
.{ 178, 5, 0xffff },
.{ 179, 5, 0xffff },
.{ 180, 5, 0xffff },
.{ 181, 5, 0xffff },
.{ 182, 5, 0xffff },
.{ 183, 5, 0xffff },
.{ 184, 5, 0xffff },
.{ 185, 5, 0xffff },
.{ 186, 5, 0xffff },
.{ 187, 5, 0xffff },
.{ 188, 5, 0xffff },
.{ 189, 5, 0xffff },
.{ 190, 5, 0xffff },
.{ 191, 5, 0xffff },
.{ 192, 5, 0xffff },
.{ 193, 5, 0xffff },
.{ 194, 5, 0xffff },
.{ 195, 5, 0xffff },
.{ 196, 5, 0xffff },
.{ 197, 5, 0xffff },
.{ 198, 5, 0xffff },
.{ 199, 5, 0xffff },
.{ 200, 5, 0xffff },
.{ 201, 5, 0xffff },
.{ 202, 5, 0xffff },
.{ 203, 5, 0xffff },
.{ 204, 5, 0xffff },
.{ 205, 5, 0xffff },
.{ 206, 5, 0xffff },
.{ 207, 5, 0xffff },
.{ 208, 5, 0xffff },
.{ 209, 5, 0xffff },
.{ 210, 5, 0xffff },
.{ 211, 5, 0xffff },
.{ 212, 5, 0xffff },
.{ 213, 5, 0x740 },
.{ 214, 5, 0xffff },
.{ 215, 5, 0xffff },
.{ 218, 6, 0xffff },
.{ 219, 6, 0xffff },
.{ 220, 6, 0xffff },
.{ 221, 6, 0xffff },
.{ 222, 0, 0xe061 },
.{ 223, 7, 0xffff },
.{ 224, 7, 0xffff },
.{ 225, 7, 0xffff },
.{ 238, 8, 0x8000 },
.{ 239, 8, 0x8000 },
.{ 240, 8, 0x8000 },
.{ 241, 8, 0x8000 },
.{ 242, 8, 0x8000 },
.{ 243, 8, 0x8000 },
.{ 245, 8, 0xffff },
.{ 246, 8, 0x8000 },
.{ 247, 8, 0x8000 },
.{ 248, 8, 0x8000 },
.{ 249, 8, 0x8000 },
.{ 250, 8, 0x8000 },
.{ 251, 8, 0x8000 },
.{ 252, 8, 0x8000 },
.{ 253, 8, 0x8000 },
.{ 254, 8, 0xffff },
.{ 255, 8, 0xe061 },
.{ 256, 8, 0x2 },
.{ 257, 8, 0x2 },
.{ 258, 9, 0xffff },
.{ 262, 9, 0xcc0 },
.{ 263, 9, 0xcc0 },
.{ 264, 9, 0xcc0 },
.{ 265, 9, 0xcc0 },
.{ 266, 9, 0xcc0 },
.{ 267, 9, 0xcc0 },
.{ 268, 9, 0xc0 },
.{ 269, 9, 0xcc0 },
.{ 270, 9, 0xcc0 },
.{ 271, 9, 0xcc0 },
.{ 272, 9, 0xcc0 },
.{ 273, 9, 0xcc0 },
.{ 274, 9, 0xcc0 },
.{ 275, 9, 0xcc0 },
.{ 276, 9, 0xcc0 },
.{ 277, 9, 0xcc0 },
.{ 278, 9, 0xcc0 },
.{ 279, 9, 0xcc0 },
.{ 280, 9, 0xcc0 },
.{ 281, 9, 0xcc0 },
.{ 282, 9, 0xcc0 },
.{ 283, 9, 0xcc0 },
.{ 284, 9, 0xcc0 },
.{ 285, 9, 0xcc0 },
.{ 286, 9, 0xcc0 },
.{ 287, 9, 0xcc0 },
.{ 288, 9, 0xcc0 },
.{ 289, 9, 0xcc0 },
.{ 303, 9, 0xffff },
.{ 304, 9, 0xffff },
.{ 312, 10, 0x6020 },
.{ 313, 10, 0x6020 },
.{ 314, 10, 0x640 },
.{ 315, 10, 0xffff },
.{ 316, 10, 0xffff },
.{ 317, 10, 0xcc0 },
.{ 318, 10, 0x640 },
.{ 319, 10, 0xffff },
.{ 320, 10, 0xffff },
.{ 321, 10, 0xcc0 },
.{ 322, 10, 0x20 },
.{ 323, 10, 0x20 },
.{ 324, 10, 0x20 },
.{ 325, 10, 0xffff },
.{ 326, 10, 0x20 },
.{ 327, 10, 0x20 },
.{ 328, 10, 0x20 },
.{ 329, 10, 0x20 },
.{ 330, 10, 0x20 },
.{ 331, 10, 0x20 },
.{ 332, 10, 0x20 },
.{ 333, 10, 0xffff },
.{ 334, 10, 0x20 },
.{ 335, 10, 0x20 },
.{ 336, 10, 0xffff },
.{ 337, 10, 0xffff },
.{ 338, 10, 0xffff },
.{ 339, 10, 0x20 },
.{ 340, 10, 0xffff },
.{ 341, 10, 0xffff },
.{ 342, 10, 0xffff },
.{ 343, 10, 0xffff },
.{ 344, 10, 0xffff },
};
pub fn get(op: u32) Compat {
for (table) |t| if (t[0] == op) return .{ .minor = t[1], .mask = t[2] };
return .{ .minor = 0, .mask = all_stages };
}

191
src/dxil/rdat.zig Normal file
View File

@ -0,0 +1,191 @@
//! The runtime data part (RDAT) of DXIL libraries, built the way dxc's
//! DxilRDATWriter / DxilRDATBuilder build it: the validator regenerates
//! the part from the module and requires the same bytes.
//!
//! 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 (only the first four are produced here).
const std = @import("std");
const Allocator = std.mem.Allocator;
pub const null_ref: u32 = 0xffff_ffff;
pub const Resource = struct {
class: u32,
kind: u32,
id: u32,
space: u32,
lower: u32,
upper: u32,
name: u32,
flags: u32 = 0,
};
/// RuntimeDataFunctionInfo3 (validator 1.10+).
pub const Function = struct {
name: u32,
unmangled_name: u32,
resources: u32 = null_ref,
function_dependencies: u32 = null_ref,
shader_kind: u32,
payload_size: u32 = 0,
attribute_size: u32 = 0,
feature_info1: u32 = 0,
feature_info2: u32 = 0,
shader_stage_flag: u32,
min_shader_target: u32,
min_wave_lanes: u8 = 0,
max_wave_lanes: u8 = 0,
shader_flags: u16 = 0,
raw_shader_ref: u32 = null_ref,
extended_properties: u32 = null_ref,
};
pub const Builder = struct {
gpa: Allocator,
strings: std.ArrayList(u8) = .empty,
string_map: std.StringHashMapUnmanaged(u32) = .empty,
indices: std.ArrayList(u32) = .empty,
resources: std.ArrayList([8]u32) = .empty,
functions: std.ArrayList([14]u32) = .empty,
raw: std.ArrayList(u8) = .empty,
subobjects: std.ArrayList([6]u32) = .empty,
pub fn init(gpa: Allocator) Allocator.Error!Builder {
var b: Builder = .{ .gpa = gpa };
_ = try b.string("");
return b;
}
/// Offset of `s` in the string buffer (each string once).
pub fn string(b: *Builder, s: []const u8) Allocator.Error!u32 {
if (b.string_map.get(s)) |off| return off;
const off: u32 = @intCast(b.strings.items.len);
try b.strings.appendSlice(b.gpa, s);
try b.strings.append(b.gpa, 0);
try b.string_map.put(b.gpa, s, off);
return off;
}
/// Offset of the index array (count, then the values); identical
/// arrays are shared.
pub fn array(b: *Builder, vals: []const u32) Allocator.Error!u32 {
var at: usize = 0;
while (at < b.indices.items.len) {
const n = b.indices.items[at];
if (n == vals.len and std.mem.eql(u32, b.indices.items[at + 1 ..][0..n], vals)) return @intCast(at);
at += n + 1;
}
const off: u32 = @intCast(b.indices.items.len);
try b.indices.append(b.gpa, @intCast(vals.len));
try b.indices.appendSlice(b.gpa, vals);
return off;
}
pub fn addResource(b: *Builder, r: Resource) Allocator.Error!void {
try b.resources.append(b.gpa, .{ r.class, r.kind, r.id, r.space, r.lower, r.upper, r.name, r.flags });
}
pub fn addFunction(b: *Builder, f: Function) Allocator.Error!void {
const packed_wave: u32 = @as(u32, f.min_wave_lanes) | (@as(u32, f.max_wave_lanes) << 8) | (@as(u32, f.shader_flags) << 16);
try b.functions.append(b.gpa, .{
f.name, f.unmangled_name, f.resources, f.function_dependencies,
f.shader_kind, f.payload_size, f.attribute_size, f.feature_info1,
f.feature_info2, f.shader_stage_flag, f.min_shader_target, packed_wave,
f.raw_shader_ref, f.extended_properties,
});
}
/// RuntimeDataSubobjectInfo: kind, name, then four kind-specific
/// words.
pub fn addSubobject(b: *Builder, rec: [6]u32) Allocator.Error!void {
try b.subobjects.append(b.gpa, rec);
}
/// Offset of `bytes` in the raw bytes part.
pub fn bytes(b: *Builder, data: []const u8) Allocator.Error!u32 {
const off: u32 = @intCast(b.raw.items.len);
try b.raw.appendSlice(b.gpa, data);
return off;
}
/// The finished part.
pub fn finish(b: *Builder) Allocator.Error![]u8 {
const Part = struct { ty: u32, data: []const u8 };
var parts: std.ArrayList(Part) = .empty;
defer parts.deinit(b.gpa);
var tables: std.ArrayList([]u8) = .empty;
defer {
for (tables.items) |t| b.gpa.free(t);
tables.deinit(b.gpa);
}
if (b.strings.items.len > 0) try parts.append(b.gpa, .{ .ty = 1, .data = b.strings.items });
if (b.resources.items.len > 0) {
const t = try table(b.gpa, 8, std.mem.sliceAsBytes(b.resources.items), b.resources.items.len);
try tables.append(b.gpa, t);
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);
try tables.append(b.gpa, t);
try parts.append(b.gpa, .{ .ty = 4, .data = t });
}
if (b.indices.items.len > 0) try parts.append(b.gpa, .{ .ty = 2, .data = std.mem.sliceAsBytes(b.indices.items) });
if (b.raw.items.len > 0) try parts.append(b.gpa, .{ .ty = 5, .data = b.raw.items });
if (b.subobjects.items.len > 0) {
const t = try table(b.gpa, 6, std.mem.sliceAsBytes(b.subobjects.items), b.subobjects.items.len);
try tables.append(b.gpa, t);
try parts.append(b.gpa, .{ .ty = 6, .data = t });
}
var size: usize = 8 + 4 * parts.items.len;
for (parts.items) |p| size += 8 + std.mem.alignForward(usize, p.data.len, 4);
const out = try b.gpa.alloc(u8, size);
@memset(out, 0);
std.mem.writeInt(u32, out[0..4], 0x10, .little); // RDAT_Version_10
std.mem.writeInt(u32, out[4..8], @intCast(parts.items.len), .little);
var at: usize = 8 + 4 * parts.items.len;
for (parts.items, 0..) |p, k| {
std.mem.writeInt(u32, out[8 + 4 * k ..][0..4], @intCast(at), .little);
const padded = std.mem.alignForward(usize, p.data.len, 4);
std.mem.writeInt(u32, out[at..][0..4], p.ty, .little);
std.mem.writeInt(u32, out[at + 4 ..][0..4], @intCast(padded), .little);
@memcpy(out[at + 8 ..][0..p.data.len], p.data);
at += 8 + padded;
}
return out;
}
fn table(gpa: Allocator, words: usize, rows: []const u8, count: usize) Allocator.Error![]u8 {
const t = try gpa.alloc(u8, 8 + rows.len);
std.mem.writeInt(u32, t[0..4], @intCast(count), .little);
std.mem.writeInt(u32, t[4..8], @intCast(words * 4), .little);
@memcpy(t[8..], rows);
return t;
}
pub fn deinit(b: *Builder) void {
b.strings.deinit(b.gpa);
b.string_map.deinit(b.gpa);
b.indices.deinit(b.gpa);
b.resources.deinit(b.gpa);
b.functions.deinit(b.gpa);
b.raw.deinit(b.gpa);
b.subobjects.deinit(b.gpa);
}
};
test "rdat of one resource and function" {
var b = try Builder.init(std.testing.allocator);
defer b.deinit();
const n = try b.string("buf");
try b.addResource(.{ .class = 1, .kind = 12, .id = 0, .space = 0, .lower = 0, .upper = 0, .name = n });
const res = try b.array(&.{0});
try std.testing.expectEqual(res, try b.array(&.{0}));
try b.addFunction(.{ .name = try b.string("cs"), .unmangled_name = try b.string("cs"), .resources = res, .shader_kind = 5, .shader_stage_flag = 32, .min_shader_target = 0x50060 });
const out = try b.finish();
defer std.testing.allocator.free(out);
try std.testing.expectEqual(@as(u32, 4), std.mem.readInt(u32, out[4..8], .little));
}

1655
src/dxil/rootsig.zig Normal file

File diff suppressed because it is too large Load Diff

View File

@ -5,6 +5,7 @@ const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const Module = @import("module.zig").Module; const Module = @import("module.zig").Module;
const container = @import("container.zig"); const container = @import("container.zig");
const signature = @import("signature.zig");
pub const ShaderKind = enum(u8) { pub const ShaderKind = enum(u8) {
pixel = 0, pixel = 0,
@ -102,22 +103,22 @@ pub fn buildEmptyCompute(gpa: Allocator, info: ComputeInfo) ![]u8 {
const dxil_part = try programPart(gpa, info.profile, bitcode); const dxil_part = try programPart(gpa, info.profile, bitcode);
defer gpa.free(dxil_part); defer gpa.free(dxil_part);
const psv = try psvCompute(gpa, info.entry, info.num_threads); const psv_part = try psvCompute(gpa, info.entry, info.num_threads, &.{});
defer gpa.free(psv); defer gpa.free(psv_part);
const empty_sig = [_]u8{ 0, 0, 0, 0, 8, 0, 0, 0 }; // ParamCount 0, ParamOffset 8 const empty_sig = [_]u8{ 0, 0, 0, 0, 8, 0, 0, 0 }; // ParamCount 0, ParamOffset 8
const parts = [_]container.Part{ const parts = [_]container.Part{
.{ .fourcc = container.fourcc("SFI0"), .data = &@as([8]u8, @splat(0)) }, .{ .fourcc = container.fourcc("SFI0"), .data = &@as([8]u8, @splat(0)) },
.{ .fourcc = container.fourcc("ISG1"), .data = &empty_sig }, .{ .fourcc = container.fourcc("ISG1"), .data = &empty_sig },
.{ .fourcc = container.fourcc("OSG1"), .data = &empty_sig }, .{ .fourcc = container.fourcc("OSG1"), .data = &empty_sig },
.{ .fourcc = container.fourcc("PSV0"), .data = psv }, .{ .fourcc = container.fourcc("PSV0"), .data = psv_part },
.{ .fourcc = container.fourcc("DXIL"), .data = dxil_part }, .{ .fourcc = container.fourcc("DXIL"), .data = dxil_part },
}; };
return container.assemble(gpa, &parts); return container.assemble(gpa, &parts);
} }
/// DxilProgramHeader + DxilBitcodeHeader + bitcode. /// DxilProgramHeader + DxilBitcodeHeader + bitcode.
fn programPart(gpa: Allocator, profile: Profile, bitcode: []const u8) ![]u8 { pub fn programPart(gpa: Allocator, profile: Profile, bitcode: []const u8) ![]u8 {
const padded = std.mem.alignForward(usize, bitcode.len, 4); const padded = std.mem.alignForward(usize, bitcode.len, 4);
const out = try gpa.alloc(u8, 24 + padded); const out = try gpa.alloc(u8, 24 + padded);
@memset(out, 0); @memset(out, 0);
@ -132,48 +133,145 @@ fn programPart(gpa: Allocator, profile: Profile, bitcode: []const u8) ![]u8 {
return out; return out;
} }
/// One PSVResourceBindInfo1 record.
pub const ResourceBind = struct { res_type: u32, space: u32, lower: u32, upper: u32, kind: u32, flags: u32 = 0 };
pub const PsvInfo = struct {
kind: ShaderKind,
entry: []const u8,
/// The stage-specific PSVRuntimeInfo0 union.
stage_info: [16]u8 = @splat(0),
num_threads: [3]u32 = .{ 0, 0, 0 },
resources: []const ResourceBind = &.{},
inputs: []const signature.Element = &.{},
outputs: []const signature.Element = &.{},
patch_constants: []const signature.Element = &.{},
groupshared_bytes: u32 = 0,
max_vertex_count: u16 = 0,
mesh_topology: u8 = 0,
uses_view_id: bool = false,
};
pub fn psvCompute(gpa: Allocator, entry: []const u8, num_threads: [3]u32, resources: []const ResourceBind) ![]u8 {
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), as produced for validator 1.11.
fn psvCompute(gpa: Allocator, entry: []const u8, num_threads: [3]u32) ![]u8 { pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
var buf: std.ArrayList(u8) = .empty; var buf: std.ArrayList(u8) = .empty;
errdefer buf.deinit(gpa); errdefer buf.deinit(gpa);
const w = struct { const w = signature.put32;
fn u32_(b: *std.ArrayList(u8), a: Allocator, v: u32) !void { const in_vectors = signature.vectorsUsed(info.inputs, 0);
var tmp: [4]u8 = undefined; var out_vectors: [4]u32 = undefined;
std.mem.writeInt(u32, &tmp, v, .little); for (&out_vectors, 0..) |*v, s| v.* = signature.vectorsUsed(info.outputs, @intCast(s));
try b.appendSlice(a, &tmp); const pc_vectors = signature.vectorsUsed(info.patch_constants, 0);
}
}.u32_;
try w(&buf, gpa, 60); // sizeof(PSVRuntimeInfo4) try w(&buf, gpa, 60); // sizeof(PSVRuntimeInfo4)
// PSVRuntimeInfo0 // PSVRuntimeInfo0
try buf.appendNTimes(gpa, 0, 16); // stage-specific union try buf.appendSlice(gpa, &info.stage_info);
try w(&buf, gpa, 0); // MinimumExpectedWaveLaneCount try w(&buf, gpa, 0); // MinimumExpectedWaveLaneCount
try w(&buf, gpa, 0xFFFFFFFF); // MaximumExpectedWaveLaneCount try w(&buf, gpa, 0xFFFFFFFF); // MaximumExpectedWaveLaneCount
// PSVRuntimeInfo1 // PSVRuntimeInfo1: stage, UsesViewID, MaxVertexCount, element counts,
try buf.appendSlice(gpa, &.{ @backingInt(ShaderKind.compute), 0, 0, 0 }); // stage, UsesViewID, union // vector counts.
try buf.appendNTimes(gpa, 0, 4); // sig element counts, SigInputVectors // (The MaxVertexCount union holds SigPatchConstOrPrimVectors for hull
try buf.appendNTimes(gpa, 0, 4); // SigOutputVectors[4] // and domain shaders.)
// (Mesh shaders: SigPrimVectors and MeshOutputTopology.)
const union16: u16 = switch (info.kind) {
.hull, .domain => @intCast(pc_vectors),
.mesh => @as(u16, @intCast(pc_vectors)) | (@as(u16, info.mesh_topology) << 8),
else => info.max_vertex_count,
};
try buf.appendSlice(gpa, &.{ @backingInt(info.kind), @intFromBool(info.uses_view_id), @truncate(union16), @truncate(union16 >> 8) });
try buf.appendSlice(gpa, &.{ @intCast(info.inputs.len), @intCast(info.outputs.len), @intCast(info.patch_constants.len), @intCast(in_vectors) });
for (out_vectors) |v| try buf.append(gpa, @intCast(v));
// PSVRuntimeInfo2 // PSVRuntimeInfo2
for (num_threads) |t| try w(&buf, gpa, t); for (info.num_threads) |t| try w(&buf, gpa, t);
// PSVRuntimeInfo3: EntryFunctionName offset into string table (after leading NUL)
try w(&buf, gpa, 1); // String table: "\0", arbitrary semantic names, the entry name.
var strings: std.ArrayList(u8) = .empty;
defer strings.deinit(gpa);
try strings.append(gpa, 0);
// Semantic index table, with runs shared between elements.
var indices: std.ArrayList(u32) = .empty;
defer indices.deinit(gpa);
var records: std.ArrayList(u8) = .empty;
defer records.deinit(gpa);
for ([_][]const signature.Element{ info.inputs, info.outputs, info.patch_constants }) |els| for (els) |e| {
var name_off: u32 = 0;
if (e.kind == .arbitrary and e.name.len > 0) {
name_off = @intCast(strings.items.len);
try strings.appendSlice(gpa, e.name);
try strings.append(gpa, 0);
}
const idx_off: u32 = blk: {
var off: usize = 0;
while (off + e.indices.len <= indices.items.len) : (off += 1) {
if (std.mem.eql(u32, indices.items[off..][0..e.indices.len], e.indices)) break :blk @intCast(off);
}
try indices.appendSlice(gpa, e.indices);
break :blk @intCast(indices.items.len - e.indices.len);
};
try w(&records, gpa, name_off);
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 });
};
const entry_off: u32 = @intCast(strings.items.len);
try strings.appendSlice(gpa, info.entry);
try strings.append(gpa, 0);
while (strings.items.len % 4 != 0) try strings.append(gpa, 0);
// PSVRuntimeInfo3: EntryFunctionName
try w(&buf, gpa, entry_off);
// PSVRuntimeInfo4 // PSVRuntimeInfo4
try w(&buf, gpa, 0); // NumBytesGroupSharedMemory try w(&buf, gpa, info.groupshared_bytes); // NumBytesGroupSharedMemory
try w(&buf, gpa, 0); // Flags try w(&buf, gpa, 0); // Flags
try w(&buf, gpa, 0); // resource count try w(&buf, gpa, @intCast(info.resources.len));
if (info.resources.len > 0) {
try w(&buf, gpa, 24); // sizeof(PSVResourceBindInfo1)
for (info.resources) |r| {
for ([_]u32{ r.res_type, r.space, r.lower, r.upper, r.kind, r.flags }) |v| try w(&buf, gpa, v);
}
}
// String table: "\0" ++ entry ++ "\0", padded to 4 bytes. try w(&buf, gpa, @intCast(strings.items.len));
const strtab_len = std.mem.alignForward(usize, entry.len + 2, 4); try buf.appendSlice(gpa, strings.items);
try w(&buf, gpa, @intCast(strtab_len)); try w(&buf, gpa, @intCast(indices.items.len));
try buf.append(gpa, 0); for (indices.items) |v| try w(&buf, gpa, v);
try buf.appendSlice(gpa, entry); if (info.inputs.len + info.outputs.len + info.patch_constants.len > 0) {
try buf.appendNTimes(gpa, 0, strtab_len - entry.len - 1); try w(&buf, gpa, 16); // sizeof(PSVSignatureElement0)
try buf.appendSlice(gpa, records.items);
try w(&buf, gpa, 0); // semantic index table count }
// Outputs depending on the ViewID (left empty, like the dependency
// tables below).
if (info.uses_view_id) {
for (out_vectors, 0..) |ov, stream| {
if (stream > 0 and info.kind != .geometry) break;
if (ov > 0) try buf.appendNTimes(gpa, 0, ((ov + 7) >> 3) * 4);
}
if ((info.kind == .hull or info.kind == .mesh) and pc_vectors > 0) try buf.appendNTimes(gpa, 0, ((pc_vectors + 7) >> 3) * 4);
}
// Input-to-output dependency table (no ViewID). Left empty: the
// validator only checks it against dx.viewIdState, which zdxc omits.
// (One per output stream for geometry shaders.)
for (out_vectors, 0..) |ov, stream| {
if (stream > 0 and info.kind != .geometry) break;
if (info.kind != .mesh and in_vectors > 0 and ov > 0) try buf.appendNTimes(gpa, 0, tableDwords(in_vectors, ov) * 4);
}
// Inputs to patch constants (hull), patch constants to outputs
// (domain).
if (info.kind == .hull and pc_vectors > 0 and in_vectors > 0) try buf.appendNTimes(gpa, 0, tableDwords(in_vectors, pc_vectors) * 4);
if (info.kind == .domain and out_vectors[0] > 0 and pc_vectors > 0) try buf.appendNTimes(gpa, 0, tableDwords(pc_vectors, out_vectors[0]) * 4);
return buf.toOwnedSlice(gpa); return buf.toOwnedSlice(gpa);
} }
/// PSVComputeInputOutputTableDwords.
fn tableDwords(in_vectors: u32, out_vectors: u32) u32 {
return ((out_vectors + 7) >> 3) * in_vectors * 4;
}
test "profile parsing" { test "profile parsing" {
const p = Profile.parse("cs_6_6").?; const p = Profile.parse("cs_6_6").?;
try std.testing.expectEqual(ShaderKind.compute, p.kind); try std.testing.expectEqual(ShaderKind.compute, p.kind);

639
src/dxil/signature.zig Normal file
View File

@ -0,0 +1,639 @@
//! DXIL entry-point signatures: how each semantic is interpreted at a
//! signature point, element packing (a port of dxc's prefix-stable
//! DxilSignatureAllocator, so registers match dxc and shaders from both
//! compilers link), and the ISG1/OSG1 container parts.
const std = @import("std");
const Allocator = std.mem.Allocator;
pub const SemanticKind = enum(u8) {
arbitrary,
vertex_id,
instance_id,
position,
render_target_array_index,
viewport_array_index,
clip_distance,
cull_distance,
output_control_point_id,
domain_location,
primitive_id,
gs_instance_id,
sample_index,
is_front_face,
coverage,
inner_coverage,
target,
depth,
depth_less_equal,
depth_greater_equal,
stencil_ref,
dispatch_thread_id,
group_id,
group_index,
group_thread_id,
tess_factor,
inside_tess_factor,
view_id,
barycentrics,
shading_rate,
cull_primitive,
start_vertex_location,
start_instance_location,
invalid,
};
const sv_names = [_][]const u8{
"", "SV_VertexID", "SV_InstanceID", "SV_Position",
"SV_RenderTargetArrayIndex", "SV_ViewportArrayIndex", "SV_ClipDistance", "SV_CullDistance",
"SV_OutputControlPointID", "SV_DomainLocation", "SV_PrimitiveID", "SV_GSInstanceID",
"SV_SampleIndex", "SV_IsFrontFace", "SV_Coverage", "SV_InnerCoverage",
"SV_Target", "SV_Depth", "SV_DepthLessEqual", "SV_DepthGreaterEqual",
"SV_StencilRef", "SV_DispatchThreadID", "SV_GroupID", "SV_GroupIndex",
"SV_GroupThreadID", "SV_TessFactor", "SV_InsideTessFactor", "SV_ViewID",
"SV_Barycentrics", "SV_ShadingRate", "SV_CullPrimitive", "SV_StartVertexLocation",
"SV_StartInstanceLocation",
};
/// The semantic a name (without its index) denotes: arbitrary unless it has
/// the `SV_` prefix.
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);
}
return .invalid;
}
/// The canonical spelling of a system-value semantic.
pub fn canonicalName(kind: SemanticKind) []const u8 {
return sv_names[@intFromEnum(kind)];
}
pub const Interpretation = enum(u8) { na, sv, sgv, arb, not_in_sig, not_packed, target, tess_factor, shadow, clip_cull };
pub const SigPoint = enum {
vs_in,
vs_out,
pc_in,
hs_in,
hs_cp_in,
hs_cp_out,
pc_out,
ds_in,
ds_cp_in,
ds_out,
gs_v_in,
gs_in,
gs_out,
ps_in,
ps_out,
cs_in,
ms_in,
ms_out,
ms_p_out,
as_in,
fn packing(sp: SigPoint) enum { none, input_assembler, vertex, target } {
return switch (sp) {
.vs_in => .input_assembler,
.vs_out, .hs_cp_in, .hs_cp_out, .pc_out, .ds_in, .ds_cp_in, .ds_out, .gs_v_in, .gs_out, .ps_in, .ms_out, .ms_p_out => .vertex,
.ps_out => .target,
.pc_in, .hs_in, .gs_in, .cs_in, .ms_in, .as_in => .none,
};
}
pub fn isInput(sp: SigPoint) bool {
return switch (sp) {
.vs_in, .pc_in, .hs_in, .hs_cp_in, .ds_in, .ds_cp_in, .gs_v_in, .gs_in, .ps_in, .cs_in, .ms_in, .as_in => true,
else => false,
};
}
};
/// How `kind` is treated at `sp` in shader model 6.`minor` (dxc's
/// DxilSigPoint interpretation table).
pub fn interpretation(kind: SemanticKind, sp: SigPoint, minor: u8) Interpretation {
const I = Interpretation;
// Columns: VSIn, VSOut, PCIn, HSIn, HSCPIn, HSCPOut, PCOut, DSIn,
// DSCPIn, DSOut, GSVIn, GSIn, GSOut, PSIn, PSOut, CSIn, MSIn, MSOut,
// MSPOut, ASIn.
const Row = [20]I;
const na: I = .na;
const arb: I = .arb;
const sv: I = .sv;
const nis: I = .not_in_sig;
const cc: I = .clip_cull;
const row: Row = switch (kind) {
.arbitrary => .{ arb, arb, na, na, arb, arb, arb, arb, arb, arb, arb, na, arb, arb, na, na, na, arb, arb, na },
.vertex_id => .{ sv, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na },
.instance_id => .{ sv, arb, na, na, arb, arb, na, na, arb, arb, arb, na, arb, arb, na, na, na, na, na, na },
.position => .{ arb, sv, na, na, sv, sv, arb, arb, sv, sv, sv, na, sv, sv, na, na, na, sv, na, na },
.render_target_array_index, .viewport_array_index => .{ arb, sv, na, na, sv, sv, arb, arb, sv, sv, sv, na, sv, sv, na, na, na, na, sv, na },
.clip_distance, .cull_distance => .{ arb, cc, na, na, cc, cc, arb, arb, cc, cc, cc, na, cc, cc, na, na, na, cc, na, na },
.output_control_point_id => .{ na, na, na, nis, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na },
.domain_location => .{ na, na, na, na, na, na, na, nis, na, na, na, na, na, na, na, na, na, na, na, na },
.primitive_id => .{ na, na, nis, nis, na, na, na, nis, na, na, na, .shadow, .sgv, .sgv, na, na, na, na, sv, na },
.gs_instance_id => .{ na, na, na, na, na, na, na, na, na, na, na, nis, na, na, na, na, na, na, na, na },
.sample_index => .{ na, na, na, na, na, na, na, na, na, na, na, na, na, .shadow, na, na, na, na, na, na },
.is_front_face => .{ na, na, na, na, na, na, na, na, na, na, na, na, .sgv, .sgv, na, na, na, na, na, na },
.coverage => .{ na, na, na, na, na, na, na, na, na, na, na, na, na, nis, .not_packed, na, na, na, na, na },
.inner_coverage => .{ na, na, na, na, na, na, na, na, na, na, na, na, na, nis, na, na, na, na, na, na },
.target => .{ na, na, na, na, na, na, na, na, na, na, na, na, na, na, .target, na, na, na, na, na },
.depth, .depth_less_equal, .depth_greater_equal, .stencil_ref => .{ na, na, na, na, na, na, na, na, na, na, na, na, na, na, .not_packed, na, na, na, na, na },
.dispatch_thread_id, .group_id, .group_index, .group_thread_id => .{ na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, nis, nis, na, na, nis },
.tess_factor, .inside_tess_factor => .{ na, na, na, na, na, na, .tess_factor, .tess_factor, na, na, na, na, na, na, na, na, na, na, na, na },
.view_id => if (minor >= 1) .{ nis, na, nis, nis, na, na, na, nis, na, na, na, nis, na, nis, na, na, nis, na, na, na } else @splat(na),
.barycentrics => if (minor >= 1) .{ na, na, na, na, na, na, na, na, na, na, na, na, na, .not_packed, na, na, na, na, na, na } else @splat(na),
.shading_rate => if (minor >= 4) .{ na, sv, na, na, sv, sv, na, na, sv, sv, sv, na, sv, sv, na, na, na, na, sv, na } else @splat(na),
.cull_primitive => .{ na, na, na, na, na, na, na, na, na, na, na, na, na, nis, na, na, na, na, .not_packed, na },
.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)];
}
pub fn shouldBeAllocated(i: Interpretation) bool {
return switch (i) {
.na, .not_in_sig, .not_packed, .shadow => false,
else => true,
};
}
pub const InterpMode = enum(u8) {
undefined,
constant,
linear,
linear_centroid,
linear_noperspective,
linear_noperspective_centroid,
linear_sample,
linear_noperspective_sample,
pub fn isAnySample(m: InterpMode) bool {
return m == .linear_sample or m == .linear_noperspective_sample;
}
};
/// DXIL component types (DXIL::ComponentType).
pub const CompType = enum(u8) {
invalid,
i1,
i16,
u16,
i32,
u32,
i64,
u64,
f16,
f32,
f64,
pub fn isFloat(c: CompType) bool {
return c == .f16 or c == .f32 or c == .f64;
}
/// DxilProgramSigCompType.
pub fn sigCompType(c: CompType) u32 {
return switch (c) {
.i1, .u32 => 1,
.i32 => 2,
.f32 => 3,
.u16 => 4,
.i16 => 5,
.f16 => 6,
.u64 => 7,
.i64 => 8,
.f64 => 9,
.invalid => 0,
};
}
/// DxilProgramSigMinPrecision (min-precision mode).
fn minPrecision(c: CompType) u32 {
return switch (c) {
.f16 => 1,
.i16 => 4,
.u16 => 5,
else => 0,
};
}
};
pub const Element = struct {
id: u32,
/// Semantic name without its index, as written.
name: []const u8,
kind: SemanticKind,
interpretation: Interpretation,
comp: CompType,
interp: InterpMode,
rows: u32,
cols: u32,
indices: []const u32,
start_row: ?u32 = null,
start_col: u32 = 0,
/// Components read (inputs) or written (outputs).
usage: u8 = 0,
stream: u32 = 0,
pub fn colsMask(e: Element) u8 {
const m: u8 = @intCast((@as(u32, 1) << @intCast(e.cols)) - 1);
return m << @intCast(if (e.start_row != null) e.start_col else 0);
}
};
// ----------------------------------------------------------------------
// Packing (DxilSignatureAllocator)
const ef_occupied: u8 = 1 << 0;
const ef_arbitrary: u8 = 1 << 1;
const ef_sgv: u8 = 1 << 2;
const ef_sv: u8 = 1 << 3;
const ef_tess_factor: u8 = 1 << 4;
const ef_clip_cull: u8 = 1 << 5;
const ef_conflicts_with_indexed: u8 = ef_sgv | ef_sv;
const indexed_up: u8 = 1 << 0;
const indexed_down: u8 = 1 << 1;
fn indexFlags(row: u32, rows: u32) u8 {
return (if (row > 0) indexed_up else 0) | (if (row < rows - 1) indexed_down else 0);
}
/// What the allocator needs to know about an element.
const PackElement = struct {
kind: SemanticKind = .arbitrary,
interp: InterpMode = .undefined,
interpretation: Interpretation = .arb,
rows: u32 = 1,
cols: u32 = 1,
row: ?u32 = null,
col: u32 = 0,
fn flags(e: PackElement) u8 {
return switch (e.interpretation) {
.arb => ef_arbitrary,
.sv => ef_sv,
.sgv => ef_sgv,
.tess_factor => ef_tess_factor,
.clip_cull => ef_clip_cull,
else => 0,
};
}
};
/// Element flags that may not be placed to the left of an element.
fn conflictFlagsLeft(f: u8) u8 {
var c: u8 = 0;
if (f & ef_arbitrary != 0) c |= ef_sgv | ef_sv | ef_tess_factor | ef_clip_cull;
if (f & (ef_sv | ef_tess_factor | ef_clip_cull) != 0) c |= ef_sgv;
return c;
}
/// Element flags that may not be placed to the right of an element.
fn conflictFlagsRight(f: u8) u8 {
var c: u8 = 0;
if (f & ef_sgv != 0) c |= ef_arbitrary | ef_sv | ef_tess_factor | ef_clip_cull;
if (f & (ef_sv | ef_tess_factor | ef_clip_cull) != 0) c |= ef_arbitrary;
return c;
}
const Register = struct {
flags: [4]u8 = @splat(0),
interp: InterpMode = .undefined,
index_flags: u8 = 0,
indexing_fixed: bool = false,
fn rowConflict(r: Register, flags: u8, index: u8, interp: InterpMode, width: u32) bool {
if (r.index_flags != 0 and flags & ef_conflicts_with_indexed != 0) return true;
if (r.indexing_fixed and (index | r.index_flags) != r.index_flags) return true;
if (flags & ef_tess_factor != 0 and (index | r.index_flags) != index) return true;
if (r.interp != .undefined and r.interp != interp) return true;
// (All packed data is 32 bits wide in min-precision mode.)
var free: u32 = 0;
for (r.flags) |f| {
if (f & ef_occupied != 0 or f & flags != 0) free = 0 else free += 1;
if (width <= free) return false;
}
return true;
}
fn colConflict(r: Register, flags: u8, col: u32, width: u32) bool {
if (col + width > 4) return true;
for (r.flags[col..][0..width]) |f| if (f & (flags | ef_occupied) != 0) return true;
return false;
}
fn place(r: *Register, flags: u8, index: u8, interp: InterpMode, col: u32, width: u32) void {
r.interp = interp;
r.index_flags |= index;
if (flags & (ef_conflicts_with_indexed | ef_tess_factor) != 0) r.indexing_fixed = true;
const left = conflictFlagsLeft(flags);
const right = conflictFlagsRight(flags);
for (&r.flags, 0..) |*f, i| {
if (f.* & ef_occupied != 0) continue;
if (i < col) f.* |= left else if (i < col + width) f.* = ef_occupied | flags else f.* |= right;
}
}
};
const Allocator32 = struct {
regs: []Register,
fn rowConflict(a: *const Allocator32, e: *const PackElement, row: u32) bool {
if (e.rows + row > a.regs.len) return true;
for (0..e.rows) |i| {
if (a.regs[row + i].rowConflict(e.flags(), indexFlags(@intCast(i), e.rows), e.interp, e.cols)) return true;
}
return false;
}
fn colConflict(a: *const Allocator32, e: *const PackElement, row: u32, col: u32) bool {
for (0..e.rows) |i| if (a.regs[row + i].colConflict(e.flags(), col, e.cols)) return true;
return false;
}
fn place(a: *Allocator32, e: *const PackElement, row: u32, col: u32) void {
for (0..e.rows) |i| a.regs[row + i].place(e.flags(), indexFlags(@intCast(i), e.rows), e.interp, col, e.cols);
}
/// First free location at or after `start_row`; returns the row after
/// the element, or 0 if it does not fit.
fn findNext(a: *const Allocator32, row_out: *u32, col_out: *u32, e: *const PackElement, start_row: u32, num_rows: u32, start_col: u32) u32 {
if (e.rows > num_rows) return 0;
var row = start_row;
while (row <= start_row + num_rows - e.rows) : (row += 1) {
if (a.rowConflict(e, row)) continue;
var col = start_col;
while (col + e.cols <= 4) : (col += 1) {
if (a.colConflict(e, row, col)) continue;
row_out.* = row;
col_out.* = col;
return row + e.rows;
}
}
return 0;
}
fn packNext(a: *Allocator32, e: *PackElement, start_row: u32, num_rows: u32, start_col: u32) u32 {
var row: u32 = 0;
var col: u32 = 0;
const used = a.findNext(&row, &col, e, start_row, num_rows, start_col);
if (used != 0) {
a.place(e, row, col);
e.row = row;
e.col = col;
}
return used;
}
/// PackPrefixStable: elements are placed in order; appending elements
/// never moves earlier ones.
fn packPrefixStable(a: *Allocator32, elements: []*PackElement, start_row: u32, num_rows: u32) u32 {
var rows_used: u32 = 0;
// Clip/cull elements share at most two registers and are kept apart
// from other elements.
var cc_regs_buf: [2]Register = .{ .{}, .{} };
var cc: Allocator32 = .{ .regs = &cc_regs_buf };
var cc_used: u32 = 0;
var cc_indexed = false;
var cc_temp: [2]PackElement = .{ .{}, .{} };
for (elements) |e| {
e.row = null;
switch (e.interpretation) {
.clip_cull => {
var row: u32 = 0;
var col: u32 = 0;
const used = cc.findNext(&row, &col, e, 0, 2, 0);
if (used == 0) continue;
if (e.rows > 1 and !cc_indexed) {
if (cc_used == 2 and cc_temp[0].row.? + 1 != cc_temp[1].row.?) continue;
cc_indexed = true;
}
if (used > cc_used) {
const de = &cc_temp[cc_used];
de.* = .{ .kind = e.kind, .interp = e.interp, .interpretation = e.interpretation, .rows = 1, .cols = 4 };
if (cc_indexed) {
if (cc_used < 1) {
de.rows = 2;
rows_used = @max(rows_used, a.packNext(de, start_row, num_rows, 0));
if (de.row == null) continue;
cc_temp[1] = de.*;
cc_temp[1].row = de.row.? + 1;
cc_temp[1].rows = 1;
} else {
rows_used = @max(rows_used, a.packNext(de, cc_temp[0].row.? + 1, cc_temp[0].row.? + 2, 0));
if (de.row == null) continue;
}
cc_used = 2;
} else {
rows_used = @max(rows_used, a.packNext(de, start_row, num_rows, 0));
if (de.row == null) continue;
cc_used = used;
}
}
cc.place(e, row, col);
e.row = cc_temp[row].row;
e.col = col;
continue;
},
.tess_factor => if (e.rows > 1) {
rows_used = @max(rows_used, a.packNext(e, start_row, num_rows, 3));
continue;
},
else => {},
}
rows_used = @max(rows_used, a.packNext(e, start_row, num_rows, 0));
}
return rows_used;
}
};
pub const PackError = error{SignatureFull} || Allocator.Error;
/// Assigns registers to the allocatable elements of a signature, as dxc's
/// PackDxilSignature does with the default (prefix-stable) strategy.
pub fn pack(gpa: Allocator, elements: []Element, sp: SigPoint) PackError!void {
switch (sp.packing()) {
.none => {},
.input_assembler => {
var row: u32 = 0;
for (elements) |*e| if (shouldBeAllocated(e.interpretation)) {
e.start_row = row;
e.start_col = 0;
row += e.rows;
};
if (row > 32) return error.SignatureFull;
},
.target => for (elements) |*e| if (e.kind == .target) {
e.start_row = e.indices[0];
e.start_col = 0;
},
.vertex => {
// One allocator per output stream.
for (0..4) |stream| {
var pes: std.ArrayList(PackElement) = .empty;
defer pes.deinit(gpa);
var owners: std.ArrayList(*Element) = .empty;
defer owners.deinit(gpa);
for (elements) |*e| if (shouldBeAllocated(e.interpretation) and e.stream == stream) {
try pes.append(gpa, .{ .kind = e.kind, .interp = e.interp, .interpretation = e.interpretation, .rows = e.rows, .cols = e.cols });
try owners.append(gpa, e);
};
if (pes.items.len == 0) continue;
const ptrs = try gpa.alloc(*PackElement, pes.items.len);
defer gpa.free(ptrs);
for (ptrs, pes.items) |*p, *pe| p.* = pe;
var regs: [32]Register = @splat(.{});
var alloc: Allocator32 = .{ .regs = &regs };
_ = alloc.packPrefixStable(ptrs, 0, 32);
for (pes.items, owners.items) |pe, e| {
e.start_row = pe.row orelse return error.SignatureFull;
e.start_col = pe.col;
}
}
},
}
}
/// Rows used by the allocated elements of `stream`.
pub fn vectorsUsed(elements: []const Element, stream: u32) u32 {
var n: u32 = 0;
for (elements) |e| if (e.start_row) |r| if (e.stream == stream) {
n = @max(n, r + e.rows);
};
return n;
}
// ----------------------------------------------------------------------
// ISG1 / OSG1
/// D3D system-value code of a semantic (DxilProgramSigSemantic).
pub const Domain = enum(u8) { undefined = 0, isoline = 1, tri = 2, quad = 3 };
fn systemValue(kind: SemanticKind, domain: Domain) u32 {
return switch (kind) {
.tess_factor => switch (domain) {
.isoline => 16, // FinalLineDensityTessfactor (then Detail)
.tri => 13,
.quad => 11,
.undefined => 0,
},
.inside_tess_factor => switch (domain) {
.tri => 14,
.quad => 12,
else => 0,
},
.arbitrary, .invalid => 0,
.position => 1,
.clip_distance => 2,
.cull_distance => 3,
.render_target_array_index => 4,
.viewport_array_index => 5,
.vertex_id => 6,
.primitive_id => 7,
.instance_id => 8,
.is_front_face => 9,
.sample_index => 10,
.barycentrics => 23,
.shading_rate => 24,
.cull_primitive => 25,
.target => 64,
.depth => 65,
.coverage => 66,
.depth_greater_equal => 67,
.depth_less_equal => 68,
.stencil_ref => 69,
.inner_coverage => 70,
else => 0,
};
}
/// 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 {
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);
var names: std.ArrayList([]const u8) = .empty;
defer names.deinit(gpa);
var name_offsets: std.ArrayList(u32) = .empty;
defer name_offsets.deinit(gpa);
var count: u32 = 0;
for (elements) |e| count += @intCast(e.indices.len);
var str_off: u32 = 8 + 32 * count;
for (elements) |e| {
const name_off = for (names.items, name_offsets.items) |n, o| {
if (std.mem.eql(u8, n, e.name)) break o;
} else blk: {
try names.append(gpa, e.name);
try name_offsets.append(gpa, str_off);
str_off += @intCast(e.name.len + 1);
break :blk str_off - @as(u32, @intCast(e.name.len + 1));
};
var usage = e.usage;
if (e.start_row != null) usage <<= @intCast(e.start_col);
const rw: u8 = if (is_input) usage else (usage ^ 0xF) & 0xF;
var reg: u32 = e.start_row orelse 0xFFFFFFFF;
var sv = systemValue(e.kind, domain);
for (e.indices) |idx| {
try recs.append(gpa, .{ .stream = e.stream, .name = name_off, .index = idx, .sv = sv, .comp = e.comp.sigCompType(), .reg = reg, .mask = e.colsMask(), .rw = rw, .min_prec = e.comp.minPrecision() });
if (e.start_row != null) reg += 1;
if (sv == 16) sv = 15; // isoline: density, then detail
}
}
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;
return a.name < b.name;
}
}.lt);
var out: std.ArrayList(u8) = .empty;
errdefer out.deinit(gpa);
try put32(&out, gpa, count);
try put32(&out, gpa, 8);
for (recs.items) |r| {
for ([_]u32{ r.stream, r.name, r.index, r.sv, r.comp, r.reg }) |v| try put32(&out, gpa, v);
try out.appendSlice(gpa, &.{ r.mask, r.rw, 0, 0 });
try put32(&out, gpa, r.min_prec);
}
for (names.items) |n| {
try out.appendSlice(gpa, n);
try out.append(gpa, 0);
}
while (out.items.len % 4 != 0) try out.append(gpa, 0);
return out.toOwnedSlice(gpa);
}
pub fn put32(out: *std.ArrayList(u8), gpa: Allocator, v: u32) Allocator.Error!void {
var tmp: [4]u8 = undefined;
std.mem.writeInt(u32, &tmp, v, .little);
try out.appendSlice(gpa, &tmp);
}
test "prefix-stable packing matches dxc" {
const gpa = std.testing.allocator;
// dxc: PS input { SV_Position; float2 TEXCOORD0; nointerpolation uint
// TEXCOORD1; float3 NORMAL; bool SV_IsFrontFace } packs to rows 0, 1,
// 2, 3 and 2.y.
const idx0 = [_]u32{0};
const idx1 = [_]u32{1};
var els = [_]Element{
.{ .id = 0, .name = "SV_Position", .kind = .position, .interpretation = .sv, .comp = .f32, .interp = .linear_noperspective, .rows = 1, .cols = 4, .indices = &idx0 },
.{ .id = 1, .name = "TEXCOORD", .kind = .arbitrary, .interpretation = .arb, .comp = .f32, .interp = .linear, .rows = 1, .cols = 2, .indices = &idx0 },
.{ .id = 2, .name = "TEXCOORD", .kind = .arbitrary, .interpretation = .arb, .comp = .u32, .interp = .constant, .rows = 1, .cols = 1, .indices = &idx1 },
.{ .id = 3, .name = "NORMAL", .kind = .arbitrary, .interpretation = .arb, .comp = .f32, .interp = .linear, .rows = 1, .cols = 3, .indices = &idx0 },
.{ .id = 4, .name = "SV_IsFrontFace", .kind = .is_front_face, .interpretation = .sgv, .comp = .u32, .interp = .constant, .rows = 1, .cols = 1, .indices = &idx0 },
};
try pack(gpa, &els, .ps_in);
const want = [_][2]u32{ .{ 0, 0 }, .{ 1, 0 }, .{ 2, 0 }, .{ 3, 0 }, .{ 2, 1 } };
for (els, want) |e, w| {
try std.testing.expectEqual(w[0], e.start_row.?);
try std.testing.expectEqual(w[1], e.start_col);
}
try std.testing.expectEqual(@as(u32, 4), vectorsUsed(&els, 0));
}

View File

@ -41,6 +41,13 @@ pub const TypeRef = struct {
attrs: []const Attribute = &.{}, attrs: []const Attribute = &.{},
/// `unorm` / `snorm` inside resource element types. /// `unorm` / `snorm` inside resource element types.
norm: enum { none, unorm, snorm } = .none, norm: enum { none, unorm, snorm } = .none,
/// `__decltype(expr)`: the type of `expr` (`name` is `__decltype`).
decltype: ?*Expr = null,
/// Spelled with `unsigned` (only integer types may be).
unsigned_spec: bool = false,
/// Type attributes written on this reference, in order: `row_major`,
/// `column_major`, `unorm`, `snorm` (template arguments, typedefs).
attr_words: []const QualWord = &.{},
}; };
/// Storage classes, type qualifiers and parameter / interpolation /// Storage classes, type qualifiers and parameter / interpolation
@ -78,9 +85,14 @@ pub const Qualifiers = packed struct(u64) {
indices: bool = false, indices: bool = false,
primitives: bool = false, primitives: bool = false,
payload: bool = false, payload: bool = false,
_: u34 = 0, center: bool = false,
_: u33 = 0,
}; };
/// A qualifier keyword as written: some diagnostics depend on the order
/// and position of qualifiers, which `Qualifiers` does not keep.
pub const QualWord = struct { loc: Loc, word: []const u8 };
/// `[name(args)]` or `[[ns::name(args)]]`. /// `[name(args)]` or `[[ns::name(args)]]`.
pub const Attribute = struct { pub const Attribute = struct {
loc: Loc, loc: Loc,
@ -130,6 +142,10 @@ pub const AssignOp = enum { assign, mul, div, rem, add, sub, shl, shr, bit_and,
pub const Expr = struct { pub const Expr = struct {
loc: Loc, loc: Loc,
kind: Kind, kind: Kind,
/// Filled in by Sema: the expression's type (a sema TypeId; 0 is the
/// error type) and an index into Sema's per-expression information.
ty: u32 = 0,
info: u32 = 0,
pub const Kind = union(enum) { pub const Kind = union(enum) {
int_lit: []const u8, int_lit: []const u8,
@ -154,6 +170,8 @@ pub const Expr = struct {
init_list: []const *Expr, init_list: []const *Expr,
sizeof_type: *TypeRef, sizeof_type: *TypeRef,
sizeof_expr: *Expr, sizeof_expr: *Expr,
/// `std::is_same<A, B>::value` (a dxc builtin).
is_same: struct { a: *TypeRef, b: *TypeRef },
}; };
}; };
@ -190,6 +208,8 @@ pub const VarDecl = struct {
/// Qualified out-of-line definitions (`int S::x = 1;`) keep the full /// Qualified out-of-line definitions (`int S::x = 1;`) keep the full
/// spelled name, e.g. `S::x`. /// spelled name, e.g. `S::x`.
quals: Qualifiers, quals: Qualifiers,
/// The qualifiers in source order.
qual_words: []const QualWord = &.{},
type: *TypeRef, type: *TypeRef,
name: []const u8, name: []const u8,
name_loc: Loc, name_loc: Loc,
@ -197,6 +217,8 @@ pub const VarDecl = struct {
semantics: []const Semantic, semantics: []const Semantic,
bitfield: ?*Expr = null, bitfield: ?*Expr = null,
init: ?*Expr = null, init: ?*Expr = null,
/// Arguments of a variable template specialization: `v<T, T>`.
specialization_args: []const TemplateArg = &.{},
}; };
pub const TemplateParam = struct { pub const TemplateParam = struct {
@ -210,7 +232,11 @@ pub const TemplateParam = struct {
pub const FuncDecl = struct { pub const FuncDecl = struct {
attrs: []const Attribute, attrs: []const Attribute,
quals: Qualifiers, quals: Qualifiers,
qual_words: []const QualWord = &.{},
template_params: []const TemplateParam, template_params: []const TemplateParam,
/// `template <class T> template <class U> R S<T>::f()`: the class
/// template's parameters (`template_params` are the member's own).
outer_template_params: []const TemplateParam = &.{},
ret: *TypeRef, ret: *TypeRef,
/// Function name; for operators `operator+`, `operator[]`, `operator()`. /// Function name; for operators `operator+`, `operator[]`, `operator()`.
name: Name, name: Name,
@ -236,6 +262,7 @@ pub const StructDecl = struct {
}; };
pub const CBufferDecl = struct { pub const CBufferDecl = struct {
attrs: []const Attribute = &.{},
tbuffer: bool, tbuffer: bool,
name: []const u8, name: []const u8,
semantics: []const Semantic, semantics: []const Semantic,
@ -258,7 +285,7 @@ pub const Decl = struct {
func: FuncDecl, func: FuncDecl,
@"struct": StructDecl, @"struct": StructDecl,
cbuffer: CBufferDecl, cbuffer: CBufferDecl,
typedef: struct { name: []const u8, type: *TypeRef, array_dims: []const ?*Expr, template_params: []const TemplateParam = &.{} }, typedef: struct { name: []const u8, type: *TypeRef, array_dims: []const ?*Expr, template_params: []const TemplateParam = &.{}, qual_words: []const QualWord = &.{}, attrs: []const Attribute = &.{} },
@"enum": EnumDecl, @"enum": EnumDecl,
namespace: struct { name: []const u8, decls: []const *Decl }, namespace: struct { name: []const u8, decls: []const *Decl },
/// `using namespace N;` /// `using namespace N;`

61
src/front/ast_clone.zig Normal file
View File

@ -0,0 +1,61 @@
//! Deep copies of AST subtrees. Template instantiation checks a fresh copy
//! of the template's declaration per argument list, since Sema records
//! types and resolutions in the nodes themselves.
const std = @import("std");
const Allocator = std.mem.Allocator;
const ast = @import("ast.zig");
/// A copy of `v` sharing only strings (and other byte slices); expression
/// nodes come back unchecked.
pub fn clone(a: Allocator, comptime T: type, v: T) Allocator.Error!T {
switch (@typeInfo(T)) {
.pointer => |p| switch (p.size) {
.one => {
const out = try a.create(p.child);
out.* = try clone(a, p.child, v.*);
return out;
},
.slice => {
if (p.child == u8) return v;
const out = try a.alloc(p.child, v.len);
for (v, out) |x, *o| o.* = try clone(a, p.child, x);
return out;
},
else => return v,
},
.optional => |o| return if (v) |x| try clone(a, o.child, x) else null,
.@"struct" => |st| {
var out: T = undefined;
inline for (st.field_names, st.field_types) |fname, ftype| @field(out, fname) = try clone(a, ftype, @field(v, fname));
if (T == ast.Expr) {
out.ty = 0;
out.info = 0;
}
return out;
},
.@"union" => |u| {
if (u.tag_type == null) return v;
switch (v) {
inline else => |payload, tag| return @unionInit(T, @tagName(tag), try clone(a, @TypeOf(payload), payload)),
}
},
else => return v,
}
}
test "clone shares strings and resets expression info" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const lit = try a.create(ast.Expr);
lit.* = .{ .loc = .none, .kind = .{ .int_lit = "42" }, .ty = 7, .info = 3 };
const neg = try a.create(ast.Expr);
neg.* = .{ .loc = .none, .kind = .{ .unary = .{ .op = .minus, .operand = lit } }, .ty = 7 };
const c = try clone(a, *ast.Expr, neg);
try std.testing.expect(c != neg);
try std.testing.expect(c.kind.unary.operand != lit);
try std.testing.expectEqual(@as(u32, 0), c.ty);
try std.testing.expectEqual(@as(u32, 0), c.kind.unary.operand.info);
try std.testing.expectEqual(lit.kind.int_lit.ptr, c.kind.unary.operand.kind.int_lit.ptr);
}

View File

@ -37,6 +37,11 @@ fn templateArgs(w: *W, args: []const ast.TemplateArg) W.Error!void {
pub fn typeRef(w: *W, t: *const ast.TypeRef) W.Error!void { pub fn typeRef(w: *W, t: *const ast.TypeRef) W.Error!void {
if (t.norm != .none) try w.print("{s} ", .{@tagName(t.norm)}); if (t.norm != .none) try w.print("{s} ", .{@tagName(t.norm)});
if (t.decltype) |e| {
try w.writeAll("__decltype(");
try expr(w, e);
return w.writeByte(')');
}
try name(w, t.name); try name(w, t.name);
if (t.args.len > 0) try templateArgs(w, t.args); if (t.args.len > 0) try templateArgs(w, t.args);
try dims(w, t.array_dims); try dims(w, t.array_dims);
@ -216,7 +221,7 @@ pub fn decl(w: *W, d: *const ast.Decl, depth: usize) W.Error!void {
}, },
.pragma => |p| try w.print("(pragma {s})", .{p}), .pragma => |p| try w.print("(pragma {s})", .{p}),
.static_assert => |s| { .static_assert => |s| {
try w.writeAll("(static_assert "); try w.writeAll("(_Static_assert ");
try expr(w, s.cond); try expr(w, s.cond);
try w.writeByte(')'); try w.writeByte(')');
}, },
@ -405,6 +410,13 @@ pub fn expr(w: *W, e: *const ast.Expr) W.Error!void {
try typeRef(w, t); try typeRef(w, t);
try w.writeByte(')'); try w.writeByte(')');
}, },
.is_same => |x| {
try w.writeAll("(is_same ");
try typeRef(w, x.a);
try w.writeAll(", ");
try typeRef(w, x.b);
try w.writeByte(')');
},
.sizeof_expr => |x| { .sizeof_expr => |x| {
try w.writeAll("(sizeof "); try w.writeAll("(sizeof ");
try expr(w, x); try expr(w, x);

View File

@ -305,7 +305,8 @@ pub const Lexer = struct {
} }
break; break;
} }
if (isIdentChar(c) or c == '.') { // dxc also takes '#' (for `1.#INF`).
if (isIdentChar(c) or c == '.' or c == '#') {
l.pos += 1; l.pos += 1;
continue; continue;
} }
@ -342,6 +343,7 @@ test "punctuators and literals" {
try expectKinds("a+=b<<=c>>1.5e-3f", &.{ .identifier, .plus_equal, .identifier, .less_less_equal, .identifier, .greater_greater, .number }); try expectKinds("a+=b<<=c>>1.5e-3f", &.{ .identifier, .plus_equal, .identifier, .less_less_equal, .identifier, .greater_greater, .number });
try expectKinds("x::y->z...", &.{ .identifier, .colon_colon, .identifier, .arrow, .identifier, .ellipsis }); try expectKinds("x::y->z...", &.{ .identifier, .colon_colon, .identifier, .arrow, .identifier, .ellipsis });
try expectKinds("\"a\\\"b\" 'c' .5h 0x1Fu", &.{ .string, .char, .number, .number }); try expectKinds("\"a\\\"b\" 'c' .5h 0x1Fu", &.{ .string, .char, .number, .number });
try expectKinds("1.#INF.xxx -1.#INF", &.{ .number, .minus, .number });
try expectKinds("# ## #x", &.{ .hash, .hash_hash, .hash, .identifier }); try expectKinds("# ## #x", &.{ .hash, .hash_hash, .hash, .identifier });
} }

View File

@ -35,9 +35,16 @@ pub const Parser = struct {
/// Name of the struct most recently parsed by parseStructDeclInto /// Name of the struct most recently parsed by parseStructDeclInto
/// (synthesized for anonymous structs), for `typedef struct ...`. /// (synthesized for anonymous structs), for `typedef struct ...`.
last_struct_name: []const u8 = "", last_struct_name: []const u8 = "",
/// The qualifier words read by the last parseQualifiers call.
last_quals: []const ast.QualWord = &.{},
/// Qualifier words for the next parseDeclaratorsInto call.
decl_quals: []const ast.QualWord = &.{},
/// Set while parsing template arguments: a top-level `>` ends the /// Set while parsing template arguments: a top-level `>` ends the
/// argument instead of being a comparison. /// argument instead of being a comparison.
no_greater: bool = false, no_greater: bool = false,
/// The last parseName ended in `::template X`: X takes template
/// arguments whatever it names.
forced_template: bool = false,
/// Collect every token from `pp` and set up a parser over them. /// Collect every token from `pp` and set up a parser over them.
pub fn fromPreprocessor(arena: Allocator, diags: *Diagnostics, pp: *Preprocessor) !Parser { pub fn fromPreprocessor(arena: Allocator, diags: *Diagnostics, pp: *Preprocessor) !Parser {
@ -288,13 +295,16 @@ pub const Parser = struct {
/// allocation), or null if no type starts there. /// allocation), or null if no type starts there.
fn scanType(p: *const Parser, start: usize) ?usize { fn scanType(p: *const Parser, start: usize) ?usize {
var i = start; var i = start;
if (p.toks[i].isIdent("unorm") or p.toks[i].isIdent("snorm")) i += 1; while (isTypeAttrWord(p.toks[i])) i += 1;
if (p.toks[i].isIdent("typename")) return p.scanDependentType(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")) { if (p.toks[i].isIdent("unsigned") or p.toks[i].isIdent("signed")) {
i += 1; i += 1;
if (p.toks[i].kind == .identifier and isBuiltinType(p.toks[i].text)) i += 1; if (p.toks[i].kind == .identifier and isBuiltinType(p.toks[i].text)) i += 1;
return i; return i;
} }
if (p.toks[i].isIdent("__decltype") and p.toks[i + 1].kind == .l_paren) {
return p.skipTypeAttrs(p.skipParens(i + 1) orelse return null);
}
if (p.toks[i].kind == .colon_colon) i += 1; if (p.toks[i].kind == .colon_colon) i += 1;
while (true) { while (true) {
const t = p.toks[i]; const t = p.toks[i];
@ -347,6 +357,23 @@ pub const Parser = struct {
} }
} }
/// Index just past the `)` matching the `(` at `start`, or null.
fn skipParens(p: *const Parser, start: usize) ?usize {
var i = start;
var depth: u32 = 0;
while (true) : (i += 1) {
switch (p.toks[i].kind) {
.l_paren => depth += 1,
.r_paren => {
depth -= 1;
if (depth == 0) return i + 1;
},
.semi, .l_brace, .r_brace, .eof => return null,
else => {},
}
}
}
/// Index just past the `>` matching the `<` at `i`, or null. /// Index just past the `>` matching the `<` at `i`, or null.
fn skipAngles(p: *const Parser, start: usize) ?usize { fn skipAngles(p: *const Parser, start: usize) ?usize {
var i = start; var i = start;
@ -425,14 +452,23 @@ pub const Parser = struct {
/// `line`, ...) count only when a type or another qualifier follows. /// `line`, ...) count only when a type or another qualifier follows.
fn parseQualifiers(p: *Parser) ast.Qualifiers { fn parseQualifiers(p: *Parser) ast.Qualifiers {
var q: ast.Qualifiers = .{}; var q: ast.Qualifiers = .{};
var words: std.ArrayList(ast.QualWord) = .empty;
defer p.last_quals = words.items;
while (p.at(.identifier)) { while (p.at(.identifier)) {
const word = p.tok().text; const word = p.tok().text;
if (inList(&reserved_declspecs, 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();
continue;
}
const field = qualifierField(word) orelse break; const field = qualifierField(word) orelse break;
if (isContextualQualifier(word)) { if (isContextualQualifier(word)) {
const n = p.peek(1); const n = p.peek(1);
const next_is_qual = n.kind == .identifier and qualifierField(n.text) != null; const next_is_qual = n.kind == .identifier and qualifierField(n.text) != null;
if (!next_is_qual and !p.isTypeStartAt(p.pos + 1)) break; if (!next_is_qual and !p.isTypeStartAt(p.pos + 1)) break;
} }
words.append(p.arena, .{ .loc = p.tok().loc, .word = word }) catch {};
_ = p.advance(); _ = p.advance();
if (std.mem.eql(u8, word, "inout")) { if (std.mem.eql(u8, word, "inout")) {
q.in = true; q.in = true;
@ -449,11 +485,16 @@ pub const Parser = struct {
fn parseType(p: *Parser) Error!*ast.TypeRef { fn parseType(p: *Parser) Error!*ast.TypeRef {
var norm: @FieldType(ast.TypeRef, "norm") = .none; var norm: @FieldType(ast.TypeRef, "norm") = .none;
if (p.eatIdent("unorm")) { var words: std.ArrayList(ast.QualWord) = .empty;
norm = .unorm; while (isTypeAttrWord(p.tok())) {
} else if (p.eatIdent("snorm")) norm = .snorm; const w = p.advance();
try words.append(p.arena, .{ .loc = w.loc, .word = w.text });
if (w.isIdent("unorm")) norm = .unorm;
if (w.isIdent("snorm")) norm = .snorm;
}
const t = try p.parseTypeInner(); const t = try p.parseTypeInner();
if (norm != .none) t.norm = norm; if (norm != .none) t.norm = norm;
if (words.items.len > 0) t.attr_words = words.items;
if (p.at(.l_square) and p.peek(1).kind == .l_square) t.attrs = try p.parseAttributes(); if (p.at(.l_square) and p.peek(1).kind == .l_square) t.attrs = try p.parseAttributes();
return t; return t;
} }
@ -465,12 +506,22 @@ pub const Parser = struct {
const n = try p.parseNameWithFinalArgs(); const n = try p.parseNameWithFinalArgs();
return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = n.name, .args = n.args }); return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = n.name, .args = n.args });
} }
if (p.atIdent("__decltype")) {
_ = p.advance();
_ = try p.expect(.l_paren, "'('");
const saved = p.no_greater;
p.no_greater = false;
const e = try p.parseExpr();
p.no_greater = saved;
_ = try p.expect(.r_paren, "')'");
return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = try p.simpleName(start.loc, "__decltype"), .decltype = e });
}
if (p.atIdent("unsigned") or p.atIdent("signed")) { if (p.atIdent("unsigned") or p.atIdent("signed")) {
const signed = p.advance().isIdent("signed"); const signed = p.advance().isIdent("signed");
var base: []const u8 = "int"; var base: []const u8 = "int";
if (p.at(.identifier) and isBuiltinType(p.tok().text)) base = p.advance().text; if (p.at(.identifier) and isBuiltinType(p.tok().text)) base = p.advance().text;
const name = if (signed) base else try unsignedName(p.arena, base); const name = if (signed) base else try unsignedName(p.arena, base);
return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = try p.simpleName(start.loc, name) }); return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = try p.simpleName(start.loc, name), .unsigned_spec = !signed });
} }
const name = try p.parseName(); const name = try p.parseName();
if (!p.isTypeName(name.last())) { if (!p.isTypeName(name.last())) {
@ -479,7 +530,7 @@ pub const Parser = struct {
return error.Syntax; return error.Syntax;
} }
var args: []const ast.TemplateArg = &.{}; var args: []const ast.TemplateArg = &.{};
if (p.at(.less) and p.isTemplateName(name.last())) args = try p.parseTemplateArgs(); 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 });
} }
@ -487,7 +538,7 @@ pub const Parser = struct {
fn parseNameWithFinalArgs(p: *Parser) Error!struct { name: ast.Name, args: []const ast.TemplateArg } { fn parseNameWithFinalArgs(p: *Parser) Error!struct { name: ast.Name, args: []const ast.TemplateArg } {
const name = try p.parseName(); const name = try p.parseName();
var args: []const ast.TemplateArg = &.{}; var args: []const ast.TemplateArg = &.{};
if (p.at(.less) and p.isTemplateName(name.last())) args = try p.parseTemplateArgs(); if (p.at(.less) and (p.forced_template or p.isTemplateName(name.last()))) args = try p.parseTemplateArgs();
return .{ .name = name, .args = args }; return .{ .name = name, .args = args };
} }
@ -502,6 +553,7 @@ pub const Parser = struct {
var parts: std.ArrayList([]const u8) = .empty; var parts: std.ArrayList([]const u8) = .empty;
var args: std.ArrayList([]const ast.TemplateArg) = .empty; var args: std.ArrayList([]const ast.TemplateArg) = .empty;
var any_args = false; var any_args = false;
p.forced_template = false;
if (p.eat(.colon_colon)) { if (p.eat(.colon_colon)) {
try parts.append(p.arena, ""); try parts.append(p.arena, "");
try args.append(p.arena, &.{}); try args.append(p.arena, &.{});
@ -522,6 +574,11 @@ pub const Parser = struct {
try args.append(p.arena, part_args); try args.append(p.arena, part_args);
if (!(p.at(.colon_colon) and p.peek(1).kind == .identifier and !p.peek(1).isIdent("operator"))) break; if (!(p.at(.colon_colon) and p.peek(1).kind == .identifier and !p.peek(1).isIdent("operator"))) break;
_ = p.advance(); _ = p.advance();
// `X<T>::template Y<U>`: the disambiguator.
if (p.atIdent("template") and p.peek(1).kind == .identifier) {
_ = p.advance();
p.forced_template = true;
}
} }
return .{ .loc = loc, .parts = parts.items, .args = if (any_args) args.items else &.{} }; return .{ .loc = loc, .parts = parts.items, .args = if (any_args) args.items else &.{} };
} }
@ -537,14 +594,11 @@ pub const Parser = struct {
return args.items; return args.items;
} }
while (true) { while (true) {
var norm: @FieldType(ast.TypeRef, "norm") = .none;
if (p.atIdent("unorm")) norm = .unorm;
if (p.atIdent("snorm")) norm = .snorm;
if (norm != .none) _ = p.advance();
_ = p.parseQualifiers(); // e.g. `row_major float4x4` _ = p.parseQualifiers(); // e.g. `row_major float4x4`
const pre = p.last_quals;
if (p.isTypeStartAt(p.pos)) { if (p.isTypeStartAt(p.pos)) {
const t = try p.parseType(); const t = try p.parseType();
t.norm = norm; if (pre.len > 0) t.attr_words = try std.mem.concat(p.arena, ast.QualWord, &.{ pre, t.attr_words });
t.array_dims = try p.parseArrayDims(); t.array_dims = try p.parseArrayDims();
try args.append(p.arena, .{ .type = t }); try args.append(p.arena, .{ .type = t });
} else { } else {
@ -639,14 +693,25 @@ pub const Parser = struct {
var attrs = try p.parseAttributes(); var attrs = try p.parseAttributes();
var template_params: []const ast.TemplateParam = &.{}; var template_params: []const ast.TemplateParam = &.{};
var outer_params: []const ast.TemplateParam = &.{};
var in_template = false; var in_template = false;
var in_inner = false;
if (p.atIdent("template")) { if (p.atIdent("template")) {
_ = p.advance(); _ = p.advance();
try p.pushScope(); try p.pushScope();
in_template = true; in_template = true;
template_params = try p.parseTemplateParams(); template_params = try p.parseTemplateParams();
// An out-of-line member template of a class template.
if (p.atIdent("template")) {
_ = p.advance();
try p.pushScope();
in_inner = true;
outer_params = template_params;
template_params = try p.parseTemplateParams();
}
} }
defer if (in_template) p.popScope(); defer if (in_template) p.popScope();
defer if (in_inner) p.popScope();
const more_attrs = try p.parseAttributes(); const more_attrs = try p.parseAttributes();
if (more_attrs.len > 0) attrs = try std.mem.concat(p.arena, ast.Attribute, &.{ attrs, more_attrs }); if (more_attrs.len > 0) attrs = try std.mem.concat(p.arena, ast.Attribute, &.{ attrs, more_attrs });
@ -654,24 +719,46 @@ pub const Parser = struct {
const save = p.pos; const save = p.pos;
const lead_quals = p.parseQualifiers(); const lead_quals = p.parseQualifiers();
const t = p.tok(); const t = p.tok();
// Legacy effect syntax, skipped with dxc's deprecation warnings.
if (isTechniqueWord(t)) {
_ = p.reportAt(p.pos, .warning, "effect technique ignored - effect syntax is deprecated and will be removed in HLSL 2026", .{});
while (!p.at(.l_brace) and !p.at(.eof)) _ = p.advance();
if (p.at(.l_brace)) try p.skipBalanced(.l_brace, .r_brace);
return;
}
if (isEffectObjectWord(t) and p.peek(1).kind == .identifier) {
_ = p.reportAt(p.pos, .warning, "effect object ignored - effect syntax is deprecated and will be removed in HLSL 2026", .{});
p.skipDeclaration();
return;
}
if (t.isIdent("struct") or t.isIdent("class") or t.isIdent("interface")) { if (t.isIdent("struct") or t.isIdent("class") or t.isIdent("interface")) {
return p.parseStructDeclInto(out, attrs, lead_quals, template_params, ctx); return p.parseStructDeclInto(out, attrs, lead_quals, template_params, ctx);
} }
p.pos = save; p.pos = save;
if (t.isIdent("cbuffer") or t.isIdent("tbuffer")) return out.append(p.arena, try p.parseCBuffer()); if (t.isIdent("cbuffer") or t.isIdent("tbuffer")) {
const d = try p.parseCBuffer();
d.kind.cbuffer.attrs = attrs;
return out.append(p.arena, d);
}
if (t.isIdent("typedef")) return p.parseTypedefInto(out); if (t.isIdent("typedef")) return p.parseTypedefInto(out);
if (t.isIdent("using")) return out.append(p.arena, try p.parseUsing(template_params)); if (t.isIdent("using")) return out.append(p.arena, try p.parseUsing(template_params));
if (t.isIdent("namespace")) return out.append(p.arena, try p.parseNamespace()); if (t.isIdent("namespace")) return out.append(p.arena, try p.parseNamespace());
if (t.isIdent("enum")) return p.parseEnumInto(out); if (t.isIdent("enum")) return p.parseEnumInto(out, ctx);
if (t.isIdent("static_assert")) { if (t.isIdent("_Static_assert")) {
const d = try p.parseStaticAssert(); const d = try p.parseStaticAssert();
_ = try p.expect(.semi, "';'"); _ = try p.expect(.semi, "';'");
return out.append(p.arena, d); return out.append(p.arena, d);
} }
const quals = p.parseQualifiers(); const quals = p.parseQualifiers();
const words = p.last_quals;
const ty = try p.parseType(); const ty = try p.parseType();
p.decl_quals = words;
const first = out.items.len;
try p.parseDeclaratorsInto(out, attrs, quals, template_params, ty, ctx); try p.parseDeclaratorsInto(out, attrs, quals, template_params, ty, ctx);
if (outer_params.len > 0) for (out.items[first..]) |d| if (d.kind == .func) {
d.kind.func.outer_template_params = outer_params;
};
} }
fn parseTemplateParams(p: *Parser) Error![]const ast.TemplateParam { fn parseTemplateParams(p: *Parser) Error![]const ast.TemplateParam {
@ -793,9 +880,9 @@ pub const Parser = struct {
_ = try p.missingSemi("';' after struct"); _ = try p.missingSemi("';' after struct");
return; return;
} }
// `struct S { ... } a, b;` // `struct S { ... } a, b;` (leading attributes apply to them too).
const ty = try p.mk(ast.TypeRef, .{ .loc = name_loc, .name = try p.simpleName(name_loc, name.?) }); const ty = try p.mk(ast.TypeRef, .{ .loc = name_loc, .name = try p.simpleName(name_loc, name.?) });
try p.parseDeclaratorsInto(out, &.{}, quals, &.{}, ty, ctx); try p.parseDeclaratorsInto(out, lead_attrs, quals, &.{}, ty, ctx);
} }
/// After a struct body without `;`: does the next line look like a new /// After a struct body without `;`: does the next line look like a new
@ -848,6 +935,7 @@ pub const Parser = struct {
fn parseTypedefInto(p: *Parser, out: *std.ArrayList(*ast.Decl)) Error!void { fn parseTypedefInto(p: *Parser, out: *std.ArrayList(*ast.Decl)) Error!void {
const kw = p.advance(); const kw = p.advance();
_ = p.parseQualifiers(); _ = p.parseQualifiers();
const words = p.last_quals;
var ty: *ast.TypeRef = undefined; var ty: *ast.TypeRef = undefined;
if (p.atIdent("struct") or p.atIdent("class")) { if (p.atIdent("struct") or p.atIdent("class")) {
// `typedef struct { ... } Name;` // `typedef struct { ... } Name;`
@ -858,7 +946,7 @@ pub const Parser = struct {
const name = try p.expectIdent("typedef name"); const name = try p.expectIdent("typedef name");
const dims = try p.parseArrayDims(); const dims = try p.parseArrayDims();
try p.declareName(name.text, .type); try p.declareName(name.text, .type);
try out.append(p.arena, try p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .typedef = .{ .name = name.text, .type = ty, .array_dims = dims } } })); try out.append(p.arena, try p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .typedef = .{ .name = name.text, .type = ty, .array_dims = dims, .qual_words = words } } }));
if (!p.eat(.comma)) break; if (!p.eat(.comma)) break;
} }
_ = try p.expect(.semi, "';'"); _ = try p.expect(.semi, "';'");
@ -877,14 +965,14 @@ pub const Parser = struct {
return p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .using_decl = n } }); return p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .using_decl = n } });
} }
const name = try p.expectIdent("alias name"); const name = try p.expectIdent("alias name");
_ = try p.parseAttributes(); // e.g. [[vk::ext_capability(...)]] const attrs = try p.parseAttributes(); // e.g. [[vk::ext_capability(...)]]
_ = try p.expect(.equal, "'='"); _ = try p.expect(.equal, "'='");
_ = p.parseQualifiers(); _ = p.parseQualifiers();
const ty = try p.parseType(); const ty = try p.parseType();
const dims = try p.parseArrayDims(); const dims = try p.parseArrayDims();
_ = try p.expect(.semi, "';'"); _ = try p.expect(.semi, "';'");
try p.declareNameOuter(name.text, if (template_params.len > 0) .template_type else .type, template_params.len > 0); try p.declareNameOuter(name.text, if (template_params.len > 0) .template_type else .type, template_params.len > 0);
return p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .typedef = .{ .name = name.text, .type = ty, .array_dims = dims, .template_params = template_params } } }); return p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .typedef = .{ .name = name.text, .type = ty, .array_dims = dims, .template_params = template_params, .attrs = attrs } } });
} }
fn parseNamespace(p: *Parser) Error!*ast.Decl { fn parseNamespace(p: *Parser) Error!*ast.Decl {
@ -903,14 +991,21 @@ pub const Parser = struct {
return p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .namespace = .{ .name = name.text, .decls = decls.items } } }); return p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .namespace = .{ .name = name.text, .decls = decls.items } } });
} }
fn parseEnumInto(p: *Parser, out: *std.ArrayList(*ast.Decl)) Error!void { fn parseEnumInto(p: *Parser, out: *std.ArrayList(*ast.Decl), ctx: DeclContext) Error!void {
const kw = p.advance(); const kw = p.advance();
const scoped = p.eatIdent("class") or p.eatIdent("struct"); const scoped = p.eatIdent("class") or p.eatIdent("struct");
var name: ?[]const u8 = null; var name: ?[]const u8 = null;
var name_loc = kw.loc;
if (p.at(.identifier) and !isReserved(p.tok().text)) { if (p.at(.identifier) and !isReserved(p.tok().text)) {
name_loc = p.tok().loc;
name = p.advance().text; name = p.advance().text;
try p.declareName(name.?, .type);
} }
// `enum E x;` / `enum E : 1;` (a bitfield): the enum used as a type.
if (name != null and !scoped and !p.at(.l_brace) and !(p.at(.colon) and p.isTypeStartAt(p.pos + 1))) {
const ty = try p.mk(ast.TypeRef, .{ .loc = name_loc, .name = try p.simpleName(name_loc, name.?) });
return p.parseDeclaratorsInto(out, &.{}, .{}, &.{}, ty, ctx);
}
if (name) |n| try p.declareName(n, .type);
var underlying: ?*ast.TypeRef = null; var underlying: ?*ast.TypeRef = null;
if (p.eat(.colon)) underlying = try p.parseType(); if (p.eat(.colon)) underlying = try p.parseType();
_ = try p.expect(.l_brace, "'{'"); _ = try p.expect(.l_brace, "'{'");
@ -935,14 +1030,17 @@ pub const Parser = struct {
try p.parseDeclaratorsInto(out, &.{}, .{}, &.{}, ty, .global); try p.parseDeclaratorsInto(out, &.{}, .{}, &.{}, ty, .global);
} }
/// `_Static_assert(cond, "message")`: C11's spelling, accepted by dxc in
/// every language version (`static_assert` is an identifier in 2021).
fn parseStaticAssert(p: *Parser) Error!*ast.Decl { fn parseStaticAssert(p: *Parser) Error!*ast.Decl {
// Parsed for recovery, but not part of HLSL 2021 (dxc rejects it).
_ = p.reportAt(p.pos, .@"error", "'static_assert' requires HLSL 202x; zdxc implements HLSL 2021", .{});
const kw = p.advance(); const kw = p.advance();
_ = try p.expect(.l_paren, "'('"); _ = try p.expect(.l_paren, "'('");
const cond = try p.parseAssign(); const cond = try p.parseAssign();
var message: ?[]const u8 = null; var message: ?[]const u8 = null;
if (p.eat(.comma)) message = (try p.expect(.string, "string literal")).text; if (p.eat(.comma)) {
if (!p.at(.string)) return p.fail("expected string literal", .{});
message = (try p.parsePrimary()).kind.string_lit; // adjacent literals concatenate
}
_ = try p.expect(.r_paren, "')'"); _ = try p.expect(.r_paren, "')'");
return p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .static_assert = .{ .cond = cond, .message = message } } }); return p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .static_assert = .{ .cond = cond, .message = message } } });
} }
@ -957,11 +1055,14 @@ pub const Parser = struct {
ty: *ast.TypeRef, ty: *ast.TypeRef,
ctx: DeclContext, ctx: DeclContext,
) Error!void { ) Error!void {
const words = p.decl_quals;
p.decl_quals = &.{};
// Function names may be qualified (`S::method`) or operators; // Function names may be qualified (`S::method`) or operators;
// variables may be qualified for out-of-line static members. // variables may be qualified for out-of-line static members.
const name_loc = p.tok().loc; const name_loc = p.tok().loc;
var fname: ?ast.Name = null; var fname: ?ast.Name = null;
var qualified_var: ?[]const u8 = null; var qualified_var: ?[]const u8 = null;
var var_spec: []const ast.TemplateArg = &.{};
if (p.atIdent("operator")) { if (p.atIdent("operator")) {
fname = try p.parseOperatorName(); fname = try p.parseOperatorName();
} else if (p.at(.identifier) and (p.peek(1).kind == .colon_colon or p.peek(1).kind == .l_paren or p.peek(1).kind == .less)) { } else if (p.at(.identifier) and (p.peek(1).kind == .colon_colon or p.peek(1).kind == .l_paren or p.peek(1).kind == .less)) {
@ -978,7 +1079,7 @@ pub const Parser = struct {
} else { } else {
// Explicit specialization `f<T>(...)` is not supported yet; // Explicit specialization `f<T>(...)` is not supported yet;
// accept the syntax. // accept the syntax.
if (p.at(.less)) _ = try p.parseTemplateArgs(); if (p.at(.less)) var_spec = try p.parseTemplateArgs();
if (p.at(.l_paren)) { if (p.at(.l_paren)) {
fname = n; fname = n;
} else if (n.parts.len > 1 or p.toks[p.pos - 1].kind == .greater) { } else if (n.parts.len > 1 or p.toks[p.pos - 1].kind == .greater) {
@ -988,14 +1089,22 @@ pub const Parser = struct {
} else p.pos = save; } else p.pos = save;
} }
} }
if (fname) |n| return out.append(p.arena, try p.parseFunctionRest(attrs, quals, template_params, ty, n, name_loc, ctx)); if (fname) |n| {
const d = try p.parseFunctionRest(attrs, quals, template_params, ty, n, name_loc, ctx);
if (d.kind == .func) d.kind.func.qual_words = words;
return out.append(p.arena, d);
}
var first = true; var first = true;
while (true) { while (true) {
var name: Token = undefined; var name: Token = undefined;
if (first and qualified_var != null) { if (first and qualified_var != null) {
name = .{ .kind = .identifier, .text = qualified_var.?, .loc = name_loc }; name = .{ .kind = .identifier, .text = qualified_var.?, .loc = name_loc };
} else if (ctx == .member and p.at(.colon)) {
// Anonymous bitfield (`uint : 4;`).
name = .{ .kind = .identifier, .text = "", .loc = p.tok().loc };
} else name = try p.expectIdent("declarator name"); } else name = try p.expectIdent("declarator name");
const first_spec = first;
first = false; first = false;
const dims = try p.parseArrayDims(); const dims = try p.parseArrayDims();
var bitfield: ?*ast.Expr = null; var bitfield: ?*ast.Expr = null;
@ -1003,13 +1112,21 @@ pub const Parser = struct {
// Legacy effect syntax: `<annotations>` and `{ state block }`. // Legacy effect syntax: `<annotations>` and `{ state block }`.
if (ctx != .local and p.at(.less)) try p.skipBalanced(.less, .greater); if (ctx != .local and p.at(.less)) try p.skipBalanced(.less, .greater);
var init_expr: ?*ast.Expr = null; var init_expr: ?*ast.Expr = null;
if (ctx != .local and p.at(.l_brace)) { if (p.at(.l_brace)) {
_ = p.reportAt(p.pos, .warning, "effect state block ignored - effect syntax is deprecated and will be removed in HLSL 2026", .{});
try p.skipBalanced(.l_brace, .r_brace); try p.skipBalanced(.l_brace, .r_brace);
} else if (p.eat(.equal)) init_expr = try p.parseInitializer(); } else if (p.eat(.equal)) {
if (p.atIdent("sampler_state")) {
_ = p.reportAt(p.pos, .warning, "effect sampler_state assignment ignored - effect syntax is deprecated and will be removed in HLSL 2026", .{});
_ = p.advance();
if (p.at(.l_brace)) try p.skipBalanced(.l_brace, .r_brace);
} else init_expr = try p.parseInitializer();
}
try out.append(p.arena, try p.mk(ast.Decl, .{ .loc = name.loc, .kind = .{ .@"var" = .{ try out.append(p.arena, try p.mk(ast.Decl, .{ .loc = name.loc, .kind = .{ .@"var" = .{
.attrs = attrs, .attrs = attrs,
.template_params = template_params, .template_params = template_params,
.quals = quals, .quals = quals,
.qual_words = words,
.type = ty, .type = ty,
.name = name.text, .name = name.text,
.name_loc = name.loc, .name_loc = name.loc,
@ -1017,6 +1134,7 @@ pub const Parser = struct {
.semantics = sems, .semantics = sems,
.bitfield = bitfield, .bitfield = bitfield,
.init = init_expr, .init = init_expr,
.specialization_args = if (first_spec) var_spec else &.{},
} } })); } } }));
if (ctx == .local) try p.declareName(name.text, .value); if (ctx == .local) try p.declareName(name.text, .value);
// Variable templates are referenced as `v<Args>`. // Variable templates are referenced as `v<Args>`.
@ -1028,6 +1146,20 @@ pub const Parser = struct {
/// Skip a balanced `open ... close` group (legacy annotations and state /// Skip a balanced `open ... close` group (legacy annotations and state
/// blocks, which zdxc ignores like dxc does). /// blocks, which zdxc ignores like dxc does).
/// Skips to just past the `;` ending a declaration (outside braces).
fn skipDeclaration(p: *Parser) void {
var depth: u32 = 0;
while (!p.at(.eof)) {
const t = p.advance();
switch (t.kind) {
.l_brace => depth += 1,
.r_brace => depth -|= 1,
.semi => if (depth == 0) return,
else => {},
}
}
}
fn skipBalanced(p: *Parser, open: Kind, close: Kind) Error!void { fn skipBalanced(p: *Parser, open: Kind, close: Kind) Error!void {
_ = try p.expect(open, "group"); _ = try p.expect(open, "group");
var depth: u32 = 1; var depth: u32 = 1;
@ -1080,6 +1212,7 @@ pub const Parser = struct {
while (!p.at(.r_paren)) { while (!p.at(.r_paren)) {
const pattrs = try p.parseAttributes(); const pattrs = try p.parseAttributes();
const pquals = p.parseQualifiers(); const pquals = p.parseQualifiers();
const pwords = p.last_quals;
const pty = try p.parseType(); const pty = try p.parseType();
var pname: []const u8 = ""; var pname: []const u8 = "";
var pname_loc = p.tok().loc; var pname_loc = p.tok().loc;
@ -1097,6 +1230,7 @@ pub const Parser = struct {
try params.append(p.arena, .{ try params.append(p.arena, .{
.attrs = pattrs, .attrs = pattrs,
.quals = pquals, .quals = pquals,
.qual_words = pwords,
.type = pty, .type = pty,
.name = pname, .name = pname,
.name_loc = pname_loc, .name_loc = pname_loc,
@ -1342,8 +1476,10 @@ pub const Parser = struct {
if (t.kind == .identifier) { if (t.kind == .identifier) {
const w = t.text; const w = t.text;
if (std.mem.eql(u8, w, "struct") or std.mem.eql(u8, w, "class") or std.mem.eql(u8, w, "typedef") or 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")) std.mem.eql(u8, w, "using") or std.mem.eql(u8, w, "enum") or std.mem.eql(u8, w, "_Static_assert"))
return true; return true;
if (inList(&reserved_declspecs, w)) return true;
if (isEffectObjectWord(t) and p.peek(1).kind == .identifier) return true;
if (qualifierField(w) != null) { if (qualifierField(w) != null) {
if (!isContextualQualifier(w)) return true; if (!isContextualQualifier(w)) return true;
const n = p.peek(1); const n = p.peek(1);
@ -1579,6 +1715,12 @@ pub const Parser = struct {
switch (t.kind) { switch (t.kind) {
.number => { .number => {
_ = p.advance(); _ = p.advance();
// HLSL allows swizzles on literals (`0x04.xxx`, `1.0.xxxx`);
// the lexer reads them as one pp-number.
if (splitLiteralSwizzle(t.text)) |split| {
const lit = try p.mkExpr(t.loc, if (isFloatLiteral(split.literal)) .{ .float_lit = split.literal } else .{ .int_lit = split.literal });
return p.mkExpr(t.loc, .{ .member = .{ .base = lit, .name = split.swizzle, .name_loc = t.loc.advance(@intCast(split.literal.len + 1)) } });
}
return p.mkExpr(t.loc, if (isFloatLiteral(t.text)) .{ .float_lit = t.text } else .{ .int_lit = t.text }); return p.mkExpr(t.loc, if (isFloatLiteral(t.text)) .{ .float_lit = t.text } else .{ .int_lit = t.text });
}, },
.string => { .string => {
@ -1616,6 +1758,16 @@ pub const Parser = struct {
_ = p.advance(); _ = p.advance();
return p.mkExpr(t.loc, .this); return p.mkExpr(t.loc, .this);
} }
if (t.isIdent("std") and p.peek(1).kind == .colon_colon and p.peek(2).isIdent("is_same") and p.peek(3).kind == .less) {
p.pos += 3;
const args = try p.parseTemplateArgs();
_ = try p.expect(.colon_colon, "'::'");
const v = try p.expect(.identifier, "'value'");
if (args.len != 2 or args[0] != .type or args[1] != .type or !v.isIdent("value")) {
return p.fail("expected 'std::is_same<type, type>::value'", .{});
}
return p.mkExpr(t.loc, .{ .is_same = .{ .a = args[0].type, .b = args[1].type } });
}
if (t.kind == .identifier and isReserved(t.text)) { if (t.kind == .identifier and isReserved(t.text)) {
return p.fail("expected expression, found '{s}'", .{t.text}); return p.fail("expected expression, found '{s}'", .{t.text});
} }
@ -1629,7 +1781,9 @@ pub const Parser = struct {
} }
const name = try p.parseName(); const name = try p.parseName();
// Explicit template arguments: `f<float>(x)`. // Explicit template arguments: `f<float>(x)`.
if (p.at(.less) and p.isTemplateName(name.last())) { // (Members of a class are unknown here: `S::f<1>(x)` is a call
// when it reads as one.)
if (p.at(.less) and (p.forced_template or p.isTemplateName(name.last()) or (name.parts.len > 1 and p.looksLikeTemplateCall()))) {
const targs = try p.parseTemplateArgs(); const targs = try p.parseTemplateArgs();
if (!p.at(.l_paren)) { if (!p.at(.l_paren)) {
// Variable template use: `is_same_v<int, bool>`. // Variable template use: `is_same_v<int, bool>`.
@ -1652,6 +1806,22 @@ fn describe(t: Token) []const u8 {
return if (t.kind == .eof) "end of file" else t.text; return if (t.kind == .eof) "end of file" else t.text;
} }
/// `0x04.xxx` -> literal `0x04`, swizzle `xxx`; `1.0.xy` -> `1.0`, `xy`.
fn splitLiteralSwizzle(text: []const u8) ?struct { literal: []const u8, swizzle: []const u8 } {
const dot = std.mem.lastIndexOfScalar(u8, text, '.') orelse return null;
const sw = text[dot + 1 ..];
if (sw.len == 0 or sw.len > 4) return null;
for (sw) |c| if (std.mem.indexOfScalar(u8, "xyzwrgba", c) == null) return null;
const lit = text[0..dot];
if (lit.len == 0) return null;
// `1.xx`: the literal must not end in an exponent marker.
if (std.ascii.isAlphabetic(lit[lit.len - 1]) and !(lit.len > 1 and lit[0] == '0' and (lit[1] == 'x' or lit[1] == 'X'))) {
const last = lit[lit.len - 1];
if (last != 'f' and last != 'F' and last != 'h' and last != 'H' and last != 'u' and last != 'U' and last != 'l' and last != 'L') return null;
}
return .{ .literal = lit, .swizzle = sw };
}
fn isFloatLiteral(text: []const u8) bool { fn isFloatLiteral(text: []const u8) bool {
if (text.len > 1 and text[0] == '0' and (text[1] == 'x' or text[1] == 'X')) return false; if (text.len > 1 and text[0] == '0' and (text[1] == 'x' or text[1] == 'X')) return false;
if (std.mem.indexOfAny(u8, text, ".eE") != null) return true; if (std.mem.indexOfAny(u8, text, ".eE") != null) return true;
@ -1660,14 +1830,7 @@ fn isFloatLiteral(text: []const u8) bool {
} }
/// Words that can never be identifiers. /// Words that can never be identifiers.
const reserved_words = [_][]const u8{ const reserved_words = [_][]const u8{ "if", "else", "for", "while", "do", "switch", "case", "default", "break", "continue", "return", "discard", "struct", "class", "interface", "cbuffer", "tbuffer", "typedef", "namespace", "enum", "template", "typename", "true", "false", "this", "sizeof", "static", "const", "uniform", "extern", "volatile", "groupshared", "inline", "using", "operator", "_Static_assert", "inout", "in", "out", "__decltype" };
"if", "else", "for", "while", "do", "switch", "case",
"default", "break", "continue", "return", "discard", "struct", "class",
"interface", "cbuffer", "tbuffer", "typedef", "namespace", "enum", "template",
"typename", "true", "false", "this", "sizeof", "static", "const",
"uniform", "extern", "volatile", "groupshared", "inline", "using", "operator",
"static_assert", "inout", "in", "out",
};
/// Qualifier keywords and their ast.Qualifiers field names. /// Qualifier keywords and their ast.Qualifiers field names.
const qualifier_words = [_][2][]const u8{ const qualifier_words = [_][2][]const u8{
@ -1681,7 +1844,37 @@ const qualifier_words = [_][2][]const u8{
.{ "export", "export" }, .{ "point", "point" }, .{ "line", "line" }, .{ "export", "export" }, .{ "point", "point" }, .{ "line", "line" },
.{ "triangle", "triangle" }, .{ "lineadj", "lineadj" }, .{ "triangleadj", "triangleadj" }, .{ "triangle", "triangle" }, .{ "lineadj", "lineadj" }, .{ "triangleadj", "triangleadj" },
.{ "vertices", "vertices" }, .{ "indices", "indices" }, .{ "primitives", "primitives" }, .{ "vertices", "vertices" }, .{ "indices", "indices" }, .{ "primitives", "primitives" },
.{ "payload", "payload" }, .{ "payload", "payload" }, .{ "center", "center" },
};
fn isTechniqueWord(t: Token) bool {
return t.isIdent("technique") or t.isIdent("Technique") or t.isIdent("technique10") or t.isIdent("technique11");
}
/// dxc's g_DeprecatedEffectObjectNames.
fn isEffectObjectWord(t: Token) bool {
const names = [_][]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);
}
/// Type attributes that may precede a type: `unorm float`,
/// `row_major float4x4`.
fn isTypeAttrWord(t: Token) bool {
return t.isIdent("unorm") or t.isIdent("snorm") or t.isIdent("row_major") or t.isIdent("column_major");
}
/// C / C++ declaration specifiers dxc's parser rejects as "reserved
/// keyword in HLSL".
const reserved_declspecs = [_][]const u8{
"volatile", "signed", "long", "short", "char", "wchar_t", "char16_t",
"char32_t", "register", "mutable", "constexpr", "friend", "virtual", "union",
"__declspec", "__forceinline", "_Alignas", "_Atomic", "_Complex", "_Imaginary", "_Noreturn",
"_Thread_local", "thread_local", "__int64", "__int128", "typeof", "__thread", "concept",
}; };
/// Qualifiers that are ordinary identifiers unless a type follows. /// Qualifiers that are ordinary identifiers unless a type follows.
@ -1689,6 +1882,7 @@ const contextual_words = [_][]const u8{
"precise", "shared", "row_major", "column_major", "nointerpolation", "linear", "centroid", "precise", "shared", "row_major", "column_major", "nointerpolation", "linear", "centroid",
"sample", "noperspective", "globallycoherent", "reordercoherent", "export", "point", "line", "sample", "noperspective", "globallycoherent", "reordercoherent", "export", "point", "line",
"triangle", "lineadj", "triangleadj", "vertices", "indices", "primitives", "payload", "triangle", "lineadj", "triangleadj", "vertices", "indices", "primitives", "payload",
"center",
}; };
fn isReserved(w: []const u8) bool { fn isReserved(w: []const u8) bool {

View File

@ -27,6 +27,8 @@ pub const Options = struct {
major: u32 = 6, major: u32 = 6,
minor: u32 = 0, minor: u32 = 0,
spirv: bool = false, spirv: bool = false,
/// SPIR-V 1.x of the target environment.
spirv_minor: u32 = 0,
enable_16bit: bool = false, enable_16bit: bool = false,
}; };
@ -241,7 +243,7 @@ pub const Preprocessor = struct {
); );
try w.print("#define __SHADER_TARGET_STAGE {d}\n#define __SHADER_TARGET_MAJOR {d}\n#define __SHADER_TARGET_MINOR {d}\n", .{ o.stage, o.major, o.minor }); try w.print("#define __SHADER_TARGET_STAGE {d}\n#define __SHADER_TARGET_MAJOR {d}\n#define __SHADER_TARGET_MINOR {d}\n", .{ o.stage, o.major, o.minor });
if (o.enable_16bit) try w.writeAll("#define __HLSL_ENABLE_16_BIT 1\n"); if (o.enable_16bit) try w.writeAll("#define __HLSL_ENABLE_16_BIT 1\n");
if (o.spirv) try w.writeAll("#define __spirv__ 1\n#define __SPIRV_MAJOR_VERSION__ 1\n#define __SPIRV_MINOR_VERSION__ 0\n"); if (o.spirv) try w.print("#define __spirv__ 1\n#define __SPIRV_MAJOR_VERSION__ 1\n#define __SPIRV_MINOR_VERSION__ {d}\n", .{o.spirv_minor});
for (o.defines) |d| try w.print("#define {s} {s}\n", .{ d.name, d.value orelse "1" }); for (o.defines) |d| try w.print("#define {s} {s}\n", .{ d.name, d.value orelse "1" });
const id = try pp.sm.addFile("<built-in>", text.written()); const id = try pp.sm.addFile("<built-in>", text.written());

696
src/ir/ir.zig Normal file
View File

@ -0,0 +1,696 @@
//! zdxc IR: typed values in a control-flow graph that keeps its structure
//! (selection and loop headers name their merge and continue blocks), shared
//! by the DXIL and SPIR-V backends.
//!
//! Lowering produces memory form: locals and parameters live in `local_var`
//! storage accessed by `load` / `store`, as dxc's SPIR-V backend emits them.
//! Functions and calls are kept (SPIR-V wants real functions); the DXIL
//! backend inlines, promotes memory to SSA values and scalarizes.
//!
//! Value types are Sema's TypeTable ids (scalars, vectors, matrices,
//! arrays, structs, resources). A value whose `ptr` space is not `.none` is
//! a pointer to storage of that type.
const std = @import("std");
const Allocator = std.mem.Allocator;
const types = @import("../sema/types.zig");
pub const TypeId = types.TypeId;
pub const TypeTable = types.TypeTable;
/// An instruction result within a function.
pub const Ref = enum(u32) {
none = std.math.maxInt(u32),
_,
pub fn index(r: Ref) u32 {
return @backingInt(r);
}
};
pub const BlockId = enum(u32) {
none = std.math.maxInt(u32),
_,
pub fn index(b: BlockId) u32 {
return @backingInt(b);
}
};
/// Where a pointer points.
pub const Space = enum { none, function, private, groupshared, resource, input, output, cbuffer, mesh, ray };
/// Ray tracing shader storage an entry receives: the incoming payload,
/// the hit attributes and the incoming callable data.
pub const RayIncoming = enum { payload, attributes, callable };
pub const BinaryOp = enum {
add,
sub,
mul,
div,
rem,
shl,
shr,
bit_and,
bit_or,
bit_xor,
log_and,
log_or,
};
pub const CmpOp = enum { eq, ne, lt, le, gt, ge };
pub const UnaryOp = enum { neg, not, bit_not };
pub const Constant = union(enum) {
/// Integer or bool bits, sign-extended for signed types.
int: i64,
float: f64,
};
pub const Op = union(enum) {
/// A scalar constant (or a vector of one constant, splatted).
constant: Constant,
/// The function's `n`th parameter (a pointer for out / inout).
param: u32,
/// Pointer to a module global (resource, groupshared, static).
global: u32,
/// Function-local storage of the result type (result is a pointer).
local_var,
load: Ref,
store: struct { ptr: Ref, value: Ref },
/// Pointer to a member / element of the storage `base` points at.
access: struct { base: Ref, indices: []const Ref },
binary: struct { op: BinaryOp, lhs: Ref, rhs: Ref },
unary: struct { op: UnaryOp, operand: Ref },
cmp: struct { op: CmpOp, lhs: Ref, rhs: Ref },
/// Component-wise numeric conversion to the result type (same shape).
convert: Ref,
/// Bit reinterpretation (asuint, asfloat, ...).
bitcast: Ref,
/// Scalar replicated to the result vector / matrix.
splat: Ref,
/// Constant component / member / element.
extract: struct { agg: Ref, index: u32 },
insert: struct { agg: Ref, value: Ref, index: u32 },
/// Vector / matrix / struct / array from its components.
construct: []const Ref,
/// Vector components picked by index (swizzles, truncation).
shuffle: struct { vec: Ref, components: []const u8 },
select: struct { cond: Ref, t: Ref, f: Ref },
call: struct { func: u32, args: []const Ref },
/// A math / bit / derivative intrinsic by HLSL name (`sqrt`, `mad`, ...).
intrinsic: struct { name: []const u8, args: []const Ref },
/// `resource[index]` read and write (structured / typed / raw buffers,
/// textures).
res_load: struct { res: Ref, index: Ref },
res_store: struct { res: Ref, index: Ref, value: Ref },
/// A builtin method call on a resource (`Load`, `Sample`, ...).
method: struct { name: []const u8, res: Ref, args: []const Ref },
/// An entry-point input / output element (index into the entry's
/// signature).
input: u32,
/// A per-vertex input (geometry shaders): element, vertex index.
input_vertex: struct { element: u32, vertex: u32 },
output: struct { element: u32, value: Ref },
/// Hull / domain shaders: a patch constant read (domain) or written
/// (hull patch constant function), and a hull output control point
/// read back by the patch constant function.
patch_input: u32,
/// Mesh shaders: an output array (a pointer in the `mesh` space; stores
/// through it write vertices, primitives or indices), and the payload
/// from the amplification shader.
mesh_output: MeshOutput,
mesh_payload,
/// `ResourceDescriptorHeap[index]` / `SamplerDescriptorHeap[index]`
/// as a resource of the instruction's type.
heap_resource: struct { index: Ref, sampler: bool },
/// Ray tracing entries: pointer (`ray` space) to the storage of an
/// incoming value of the instruction's type.
ray_incoming: RayIncoming,
/// SPIR-V specialization constant (index into Module.spec_constants).
spec_constant: u32,
/// Inline SPIR-V (`[[vk::ext_instruction]]` functions): an instruction
/// of `set` (null: core), with the capabilities and extensions it needs.
spirv_inst: *const SpirvInst,
patch_output: struct { element: u32, value: Ref },
output_vertex: struct { element: u32, vertex: u32 },
/// Geometry shaders: emit the vertex written to the outputs of a stream,
/// or end its strip.
emit: u32,
cut: u32,
phi: []const struct { value: Ref, block: BlockId },
};
pub const Inst = struct {
op: Op,
ty: TypeId,
/// Non-`none` when the result is a pointer to `ty` storage.
ptr: Space = .none,
};
pub const Terminator = union(enum) {
/// Not yet terminated (lowering in progress).
none,
ret: Ref,
br: BlockId,
cond_br: struct { cond: Ref, then: BlockId, @"else": BlockId },
@"switch": struct { value: Ref, default: BlockId, cases: []const struct { value: i64, block: BlockId } },
/// After `discard`, or where control cannot reach.
@"unreachable",
discard,
};
/// Structured control flow: a header block names where its construct
/// merges and (for loops) where iterations continue.
pub const Merge = union(enum) {
none,
selection: BlockId,
loop: struct { merge: BlockId, @"continue": BlockId, unroll: Unroll = .auto },
};
/// `[unroll]` / `[loop]` on a loop.
pub const Unroll = enum { auto, unroll, dont };
pub const Block = struct {
insts: std.ArrayList(Ref) = .empty,
term: Terminator = .none,
merge: Merge = .none,
};
pub const Param = struct {
name: []const u8,
ty: TypeId,
/// out / inout: passed as a pointer to caller storage.
by_ref: bool,
/// in, out, inout (library function annotations).
dir: enum { in, out, inout } = .in,
/// The HLSL type (before patches become arrays), for mangled names.
sema_ty: TypeId = 0,
semantic: ?[]const u8 = null,
};
pub const Function = struct {
name: []const u8,
params: []const Param,
ret: TypeId,
/// The entry (index into `Module.entries`) the function was lowered
/// for first.
entry: u32 = 0,
ret_semantic: ?[]const u8 = null,
/// Declaration order of the HLSL function (libraries define functions
/// in this order).
decl_order: u32 = std.math.maxInt(u32),
insts: std.ArrayList(Inst) = .empty,
blocks: std.ArrayList(Block) = .empty,
pub fn inst(f: *const Function, r: Ref) Inst {
return f.insts.items[r.index()];
}
pub fn block(f: *Function, b: BlockId) *Block {
return &f.blocks.items[b.index()];
}
};
pub const Binding = struct {
/// Register class: 'b', 't', 'u', 's' (0: none given).
class: u8 = 0,
index: u32 = 0,
space: u32 = 0,
explicit: bool = false,
/// `spaceN` was written.
space_given: bool = false,
};
/// Vulkan binding options (-fvk-*-shift, -fvk-bind-globals,
/// -auto-binding-space).
pub const VkOptions = struct {
/// Per register class (b, t, s, u): shifts by set; `all` applies to
/// every set without one of its own.
shifts: [4]std.ArrayList(struct { shift: u32, set: ?u32 }) = .{ .empty, .empty, .empty, .empty },
bind_globals: ?[2]u32 = null,
auto_binding_space: u32 = 0,
/// -fvk-auto-shift-bindings: implicit bindings start at their class's
/// shift too.
auto_shift: bool = false,
/// -fvk-stage-io-order=alpha: locations by semantic, not declaration.
alpha_io_order: bool = false,
/// -fvk-use-gl-layout, -fvk-use-dx-layout, -fvk-use-scalar-layout.
layout: enum { default, gl, dx, scalar } = .default,
/// -fspv-entrypoint-name=, -fspv-enable-maximal-reconvergence,
/// -fvk-support-nonzero-base-instance / -vertex,
/// -fspv-use-unknown-image-format.
entry_name: ?[]const u8 = null,
/// -fspv-reflect: SPV_GOOGLE semantic / user type / counter
/// decorations.
reflect: bool = false,
/// -fspv-extension=: the only extensions allowed (empty: any).
extensions: std.ArrayList([]const u8) = .empty,
maximal_reconvergence: bool = false,
nonzero_base_instance: bool = false,
nonzero_base_vertex: bool = false,
unknown_image_format: bool = false,
/// -fvk-invert-y, -fvk-use-dx-position-w.
invert_y: bool = false,
dx_position_w: bool = false,
/// -fspv-flatten-resource-arrays: one variable (and binding) per
/// element of an array of resources.
flatten_arrays: bool = false,
/// -fspv-use-legacy-buffer-matrix-order: byte-address buffer matrices
/// are row major (dxc's old, incorrect assumption).
legacy_matrix_order: bool = false,
/// -fspv-use-vulkan-memory-model.
vulkan_memory_model: bool = false,
/// -fvk-bind-register: every resource's (set, binding) by register.
bind_register: std.ArrayList(struct { class: u8, index: u32, space: u32, binding: u32, set: u32 }) = .empty,
pub fn shift(o: VkOptions, class: u8, set: u32) u32 {
const k: usize = switch (class) {
'b' => 0,
't' => 1,
's' => 2,
'u' => 3,
else => return 0,
};
var all: u32 = 0;
for (o.shifts[k].items) |x| {
if (x.set) |s0| {
if (s0 == set) return x.shift;
} else all = x.shift;
}
return all;
}
};
/// A descriptor declaration, in declaration order: SPIR-V numbers implicit
/// bindings over all of them, used or not (as dxc).
pub const BindingDecl = struct {
/// The IR global (null: unused; it still takes a binding number).
global: ?u32,
reg: Binding = .{},
/// `register(spaceN)` without a register.
space_only: bool = false,
/// [[vk::binding(binding, set)]], [[vk::counter_binding(binding)]].
vk_binding: ?u32 = null,
vk_set: ?u32 = null,
vk_counter: ?u32 = null,
/// Append / Consume buffers: their counter is numbered right after.
acs: bool = false,
/// `$Globals`.
globals_buffer: bool = false,
/// [[vk::combinedImageSampler]]: `s` registers shift like `t` ones.
combined: bool = false,
/// Resources in the declaration (array elements).
count: u32 = 1,
};
pub const Global = struct {
name: []const u8,
ty: TypeId,
space: Space,
binding: Binding = .{},
/// A `tbuffer` block (space `cbuffer`): a texture buffer with the
/// constant buffer layout.
tbuffer: bool = false,
/// `[[vk::shader_record_ext]]` / `[[vk::shader_record_nv]]` buffers
/// (SPIR-V ShaderRecordBufferKHR storage).
shader_record: bool = false,
/// `[[vk::push_constant]]` buffers (SPIR-V PushConstant storage).
push_constant: bool = false,
/// [[vk::input_attachment_index(n)]] (SubpassInput).
input_attachment: ?u32 = null,
/// [[vk::image_format("...")]]: the SPIR-V ImageFormat.
image_format: ?u32 = null,
/// `globallycoherent` resources.
globally_coherent: bool = false,
ext: SpirvExt = .{},
};
pub const Stage = enum {
vertex,
pixel,
geometry,
hull,
domain,
compute,
mesh,
amplification,
library,
raygeneration,
intersection,
anyhit,
closesthit,
miss,
callable,
pub fn isRayTracing(s: Stage) bool {
return @backingInt(s) >= @backingInt(Stage.raygeneration);
}
};
/// One entry-point input or output (a semantic on a parameter, field or
/// the return value).
pub const SigElement = struct {
semantic: []const u8,
semantic_index: u32,
ty: TypeId,
system_value: bool,
interp: types.Interp = .{},
/// Matrices in the element are row_major (signature layout only).
row_major: bool = false,
/// Geometry shader output stream.
stream: u32 = 0,
/// One value per vertex of the input primitive (geometry shaders).
per_vertex: bool = false,
/// The semantic as written (`TEXCOORD`, `TEXCOORD3`).
spelling: ?[]const u8 = null,
/// [[vk::location(n)]], [[vk::index(n)]], [[vk::builtin("...")]].
vk_location: ?u32 = null,
vk_index: ?u32 = null,
vk_builtin: ?[]const u8 = null,
ext_decorations: []const ExtDecoration = &.{},
};
pub const Primitive = enum(u8) { point = 1, line = 2, triangle = 3, line_adj = 6, triangle_adj = 7 };
pub const GeometryInfo = struct {
input: Primitive = .triangle,
/// Vertices per input primitive.
input_vertices: u32 = 3,
max_vertex_count: u32 = 1,
instance_count: u32 = 1,
/// Output topology per stream (null: stream unused).
streams: [4]?enum { point, line, triangle } = .{ null, null, null, null },
};
pub const Domain = enum(u8) { isoline = 1, tri = 2, quad = 3 };
pub const Partitioning = enum(u8) { integer = 1, pow2 = 2, fractional_odd = 3, fractional_even = 4 };
pub const OutputTopology = enum(u8) { point = 1, line = 2, triangle_cw = 3, triangle_ccw = 4 };
pub const MeshOutput = enum { vertices, primitives, indices };
pub const MeshInfo = struct {
max_vertices: u32 = 0,
max_primitives: u32 = 0,
/// DXIL::MeshOutputTopology.
topology: enum(u8) { line = 1, triangle = 2 } = .triangle,
/// The payload struct (read by a mesh shader, sent by an amplification
/// shader's DispatchMesh).
payload: ?TypeId = null,
};
pub const TessInfo = struct {
domain: Domain = .tri,
partitioning: Partitioning = .integer,
output_topology: OutputTopology = .triangle_cw,
/// Control points per input patch (hull: InputPatch; domain:
/// OutputPatch).
input_control_points: u32 = 0,
output_control_points: u32 = 0,
max_tess_factor: f32 = 64,
};
pub const Entry = struct {
/// The function the entry wraps (the HLSL entry, in memory form).
func: u32,
name: []const u8,
stage: Stage,
num_threads: [3]u32 = .{ 1, 1, 1 },
geometry: GeometryInfo = .{},
tess: TessInfo = .{},
mesh: MeshInfo = .{},
inputs: std.ArrayList(SigElement) = .empty,
outputs: std.ArrayList(SigElement) = .empty,
/// Patch constants: written by the hull shader's patch constant
/// function, read by the domain shader.
patch_constants: std.ArrayList(SigElement) = .empty,
/// Hull shaders: the wrapper of the patch constant function (no
/// parameters; reads inputs and output control points, writes patch
/// constants).
patch_wrapper: ?u32 = null,
/// The HLSL patch constant function.
patch_func: ?u32 = null,
/// `[RootSignature("...")]`: the root signature text.
root_signature: ?[]const u8 = null,
/// Inline SPIR-V capabilities / extensions of the entry function.
ext: SpirvExt = .{},
/// The wrapper with no parameters that reads `inputs`, calls `func`
/// and writes `outputs`.
wrapper: u32 = 0,
};
/// `[[vk::ext_decorate(...)]]`, `ext_decorate_id`, `ext_decorate_string`.
pub const ExtDecoration = struct {
decoration: u32,
kind: enum { literal, id, string },
/// Literal words, or the constants for `id`.
ints: []const u32 = &.{},
strings: []const []const u8 = &.{},
};
/// Inline SPIR-V attributes of a declaration.
pub const SpirvExt = struct {
decorations: []const ExtDecoration = &.{},
capabilities: []const u32 = &.{},
extensions: []const []const u8 = &.{},
/// `[[vk::ext_builtin_input(n)]]` / `ext_builtin_output(n)`.
builtin: ?u32 = null,
builtin_output: bool = false,
/// `[[vk::ext_storage_class(n)]]`.
storage_class: ?u32 = null,
};
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 },
capabilities: []const u32 = &.{},
extensions: []const []const u8 = &.{},
};
/// A ray tracing state object subobject (DXIL::SubobjectKind values).
pub const Subobject = struct {
name: []const u8,
kind: Kind,
/// Flags, sizes, depths and hit group type, by kind.
ints: [2]u32 = .{ 0, 0 },
/// Hit group shaders (any hit, closest hit, intersection); the
/// associated subobject; root signature text.
strings: [3][]const u8 = .{ "", "", "" },
/// Associations: the exports.
exports: []const []const u8 = &.{},
pub const Kind = enum(u32) {
state_object_config = 0,
global_root_signature = 1,
local_root_signature = 2,
subobject_to_exports_association = 8,
raytracing_shader_config = 9,
raytracing_pipeline_config = 10,
hit_group = 11,
raytracing_pipeline_config1 = 12,
};
};
pub const Module = struct {
arena: Allocator,
types: *TypeTable,
globals: std.ArrayList(Global) = .empty,
/// By pointer: lowering appends callees while building a caller.
functions: std.ArrayList(*Function) = .empty,
/// Entry points (one, or a library's shaders in declaration order).
entries: std.ArrayList(Entry) = .empty,
/// Libraries: functions exported by name (`export`).
exports: std.ArrayList(u32) = .empty,
/// Libraries: state object subobjects, in declaration order.
subobjects: std.ArrayList(Subobject) = .empty,
/// [[vk::constant_id(n)]] constants (SPIR-V).
spec_constants: std.ArrayList(struct { name: []const u8, ty: TypeId, id: u32, value: Constant }) = .empty,
/// Descriptor declarations in declaration order.
binding_decls: std.ArrayList(BindingDecl) = .empty,
vk: VkOptions = .{},
/// -enable-16bit-types: half and 16-bit integers are native types.
native_16bit: bool = false,
/// Root signatures: version 1.0 or 1.1 (-force-rootsig-ver), and
/// -Qstrip_rootsignature.
rootsig_version: enum { v1_0, v1_1 } = .v1_1,
strip_rootsig: bool = false,
pub fn addFunction(m: *Module, f: Function) !u32 {
const p = try m.arena.create(Function);
p.* = f;
try m.functions.append(m.arena, p);
return @intCast(m.functions.items.len - 1);
}
};
/// Appends instructions to a function at a current block.
pub const Builder = struct {
m: *Module,
f: *Function,
cur: BlockId = .none,
pub fn newBlock(b: *Builder) !BlockId {
try b.f.blocks.append(b.m.arena, .{});
return @fromBackingInt(@intCast(b.f.blocks.items.len - 1));
}
pub fn setBlock(b: *Builder, blk: BlockId) void {
b.cur = blk;
}
/// The current block is still open (no terminator yet).
pub fn open(b: *Builder) bool {
return b.cur != .none and b.f.block(b.cur).term == .none;
}
pub fn add(b: *Builder, inst: Inst) !Ref {
try b.f.insts.append(b.m.arena, inst);
const r: Ref = @fromBackingInt(@intCast(b.f.insts.items.len - 1));
// Instructions after a terminator (dead code) go to a fresh block.
if (!b.open()) b.cur = try b.newBlock();
try b.f.block(b.cur).insts.append(b.m.arena, r);
return r;
}
pub fn terminate(b: *Builder, t: Terminator) void {
if (!b.open()) return;
b.f.block(b.cur).term = t;
}
pub fn constInt(b: *Builder, ty: TypeId, v: i64) !Ref {
return b.add(.{ .op = .{ .constant = .{ .int = v } }, .ty = ty });
}
pub fn constFloat(b: *Builder, ty: TypeId, v: f64) !Ref {
return b.add(.{ .op = .{ .constant = .{ .float = v } }, .ty = ty });
}
pub fn load(b: *Builder, ptr: Ref) !Ref {
const p = b.f.inst(ptr);
return b.add(.{ .op = .{ .load = ptr }, .ty = p.ty });
}
pub fn store(b: *Builder, ptr: Ref, value: Ref) !void {
_ = try b.add(.{ .op = .{ .store = .{ .ptr = ptr, .value = value } }, .ty = TypeTable.void_type });
}
};
/// Prints a module in a readable text form (for `-zdxc-ir` and tests).
pub fn dump(m: *const Module, w: *std.Io.Writer) !void {
for (m.globals.items, 0..) |g, i| {
try w.print("global @{d} {s}: {s} {s}", .{ i, g.name, @tagName(g.space), try m.types.format(m.arena, g.ty) });
if (g.binding.class != 0) try w.print(" : register({c}{d}, space{d})", .{ g.binding.class, g.binding.index, g.binding.space });
try w.writeByte('\n');
}
for (m.functions.items, 0..) |f, fi| {
try w.print("fn @{d} {s}(", .{ fi, f.name });
for (f.params, 0..) |p, i| {
if (i > 0) try w.writeAll(", ");
try w.print("{s}{s}: {s}", .{ if (p.by_ref) "ref " else "", p.name, try m.types.format(m.arena, p.ty) });
}
try w.print(") -> {s} {{\n", .{try m.types.format(m.arena, f.ret)});
for (f.blocks.items, 0..) |blk, bi| {
try w.print("b{d}:", .{bi});
switch (blk.merge) {
.none => {},
.selection => |mb| try w.print(" ; selection merge b{d}", .{mb.index()}),
.loop => |l| try w.print(" ; loop merge b{d} continue b{d}", .{ l.merge.index(), l.@"continue".index() }),
}
try w.writeByte('\n');
for (blk.insts.items) |r| try dumpInst(m, f, r, w);
try w.writeAll(" ");
switch (blk.term) {
.none => try w.writeAll("<open>"),
.ret => |v| if (v == .none) try w.writeAll("ret") else try w.print("ret %{d}", .{v.index()}),
.br => |t| try w.print("br b{d}", .{t.index()}),
.cond_br => |c| try w.print("br %{d}, b{d}, b{d}", .{ c.cond.index(), c.then.index(), c.@"else".index() }),
.@"switch" => |sw| {
try w.print("switch %{d} default b{d}", .{ sw.value.index(), sw.default.index() });
for (sw.cases) |c| try w.print(", {d}: b{d}", .{ c.value, c.block.index() });
},
.@"unreachable" => try w.writeAll("unreachable"),
.discard => try w.writeAll("discard"),
}
try w.writeByte('\n');
}
try w.writeAll("}\n");
}
}
fn dumpInst(m: *const Module, f: *const Function, r: Ref, w: *std.Io.Writer) !void {
const inst = f.inst(r);
try w.writeAll(" ");
if (inst.ty != TypeTable.void_type) {
try w.print("%{d}: {s}{s} = ", .{ r.index(), if (inst.ptr != .none) "*" else "", try m.types.format(m.arena, inst.ty) });
}
switch (inst.op) {
.constant => |c| switch (c) {
.int => |v| try w.print("const {d}", .{v}),
.float => |v| try w.print("const {d}", .{v}),
},
.param => |p| try w.print("param {d}", .{p}),
.global => |g| try w.print("global @{d}", .{g}),
.local_var => try w.writeAll("local_var"),
.load => |p| try w.print("load %{d}", .{p.index()}),
.store => |s| try w.print("store %{d}, %{d}", .{ s.ptr.index(), s.value.index() }),
.access => |a| {
try w.print("access %{d}", .{a.base.index()});
for (a.indices) |i| try w.print(", %{d}", .{i.index()});
},
.binary => |b| try w.print("{s} %{d}, %{d}", .{ @tagName(b.op), b.lhs.index(), b.rhs.index() }),
.unary => |u| try w.print("{s} %{d}", .{ @tagName(u.op), u.operand.index() }),
.cmp => |c| try w.print("cmp.{s} %{d}, %{d}", .{ @tagName(c.op), c.lhs.index(), c.rhs.index() }),
.convert => |x| try w.print("convert %{d}", .{x.index()}),
.bitcast => |x| try w.print("bitcast %{d}", .{x.index()}),
.splat => |x| try w.print("splat %{d}", .{x.index()}),
.extract => |x| try w.print("extract %{d}, {d}", .{ x.agg.index(), x.index }),
.insert => |x| try w.print("insert %{d}, %{d}, {d}", .{ x.agg.index(), x.value.index(), x.index }),
.construct => |xs| {
try w.writeAll("construct");
for (xs, 0..) |x, i| try w.print("{s} %{d}", .{ if (i > 0) "," else "", x.index() });
},
.shuffle => |s| {
try w.print("shuffle %{d}", .{s.vec.index()});
for (s.components) |c| try w.print(", {d}", .{c});
},
.select => |s| try w.print("select %{d}, %{d}, %{d}", .{ s.cond.index(), s.t.index(), s.f.index() }),
.call => |c| {
try w.print("call @{d}", .{c.func});
for (c.args) |a| try w.print(", %{d}", .{a.index()});
},
.intrinsic => |c| {
try w.print("{s}", .{c.name});
for (c.args, 0..) |a, i| try w.print("{s} %{d}", .{ if (i > 0) "," else "", a.index() });
},
.input_vertex => |x| try w.print("input {d} vertex {d}", .{ x.element, x.vertex }),
.emit => |k| try w.print("emit stream {d}", .{k}),
.patch_input => |k| try w.print("patch input {d}", .{k}),
.mesh_output => |k| try w.print("mesh output {s}", .{@tagName(k)}),
.mesh_payload => try w.print("mesh payload", .{}),
.ray_incoming => |k| try w.print("ray incoming {s}", .{@tagName(k)}),
.spec_constant => |k| try w.print("spec constant {d}", .{k}),
.spirv_inst => |x| try w.print("spirv op {d}", .{x.opcode}),
.heap_resource => |h| try w.print("{s}[%{d}]", .{ if (h.sampler) "SamplerDescriptorHeap" else "ResourceDescriptorHeap", h.index.index() }),
.patch_output => |x| try w.print("patch output {d} = %{d}", .{ x.element, x.value.index() }),
.output_vertex => |x| try w.print("output {d} vertex {d}", .{ x.element, x.vertex }),
.cut => |k| try w.print("cut stream {d}", .{k}),
.res_load => |x| try w.print("res_load %{d}[%{d}]", .{ x.res.index(), x.index.index() }),
.res_store => |x| try w.print("res_store %{d}[%{d}], %{d}", .{ x.res.index(), x.index.index(), x.value.index() }),
.method => |x| {
try w.print("%{d}.{s}(", .{ x.res.index(), x.name });
for (x.args, 0..) |a, i| try w.print("{s}%{d}", .{ if (i > 0) ", " else "", a.index() });
try w.writeByte(')');
},
.input => |i| try w.print("input {d}", .{i}),
.output => |o| try w.print("output {d}, %{d}", .{ o.element, o.value.index() }),
.phi => |ins| {
try w.writeAll("phi");
for (ins, 0..) |in, i| try w.print("{s} [%{d}, b{d}]", .{ if (i > 0) "," else "", in.value.index(), in.block.index() });
},
}
try w.writeByte('\n');
}

293
src/ir/layout.zig Normal file
View File

@ -0,0 +1,293 @@
//! Memory layouts of buffer contents.
//!
//! - `dx_legacy`: D3D cbuffer packing (DXIL cbuffers). 16-byte registers;
//! vectors may not straddle a register; arrays, structs and matrices
//! start on a register; every array element but the last fills whole
//! registers.
//! - `vk_relaxed`: dxc's default SPIR-V cbuffer layout. std140 with relaxed
//! vector placement (component aligned, no 16-byte straddle); arrays and
//! structs 16-byte aligned and padded; array strides multiples of 16.
//! - `std430`: dxc's default SPIR-V structured-buffer layout. Relaxed vector
//! placement as above; arrays and structs aligned to their members' std430
//! alignment (vec3 counts as 16).
//! - `dx_packed`: DXIL structured buffers, tightly packed at scalar
//! alignment.
//!
//! Matrices are column-major unless their field is `row_major`: a
//! column-major RxC matrix is C vectors of R components.
const std = @import("std");
const types = @import("../sema/types.zig");
const TypeId = types.TypeId;
const TypeTable = types.TypeTable;
const Allocator = std.mem.Allocator;
/// `vk_relaxed` / `std430`: relaxed GLSL std140 / std430 (dxc's Vulkan
/// defaults); `gl_std140` / `gl_std430`: strict ones (-fvk-use-gl-layout);
/// `scalar`: scalar block layout (-fvk-use-scalar-layout).
pub const Rules = enum { dx_legacy, vk_relaxed, std430, dx_packed, gl_std140, gl_std430, scalar };
pub const Error = error{Unsupported} || Allocator.Error;
fn scalarSize(t: *const TypeTable, ty: TypeId) u32 {
return switch (t.component(ty).?) {
.double, .int64, .uint64 => 8,
.int16, .uint16, .float16 => 2,
else => 4,
};
}
fn roundUp(v: u32, a: u32) u32 {
return (v + a - 1) / a * a;
}
/// A matrix as stored: `count` vectors of `len` components.
const MatrixVectors = struct { count: u32, len: u32 };
fn matrixVectors(m: anytype, row_major: bool) MatrixVectors {
return if (row_major) .{ .count = m.rows, .len = m.cols } else .{ .count = m.cols, .len = m.rows };
}
/// std430 base alignment of an `n`-vector of `s`-byte components.
fn vectorAlign(n: u32, s: u32) u32 {
return if (n == 1) s else if (n == 2) 2 * s else 4 * s;
}
/// Byte distance between the vectors of a stored matrix.
pub fn matrixStride(t: *const TypeTable, ty: TypeId, row_major: bool, rules: Rules) u32 {
const m = t.get(ty).matrix;
const mv = matrixVectors(m, row_major);
const s = scalarSize(t, ty);
return switch (rules) {
.dx_legacy, .vk_relaxed => 16,
.gl_std140 => roundUp(vectorAlign(mv.len, s), 16),
.std430, .gl_std430 => vectorAlign(mv.len, s),
.dx_packed, .scalar => mv.len * s,
};
}
pub fn alignOf(t: *const TypeTable, ty: TypeId, row_major: bool, rules: Rules) Error!u32 {
switch (t.get(ty)) {
.scalar, .@"enum" => return scalarSize(t, ty),
// (The base alignment; relaxed placement packs 32-bit vectors
// tighter, see `place`.)
.vector => |v| return switch (rules) {
.std430, .vk_relaxed, .gl_std140, .gl_std430 => vectorAlign(v.len, scalarSize(t, ty)),
else => scalarSize(t, ty),
},
.matrix => return switch (rules) {
.dx_legacy, .vk_relaxed => 16,
.std430, .gl_std140, .gl_std430 => matrixStride(t, ty, row_major, rules),
.dx_packed, .scalar => scalarSize(t, ty),
},
.array => |a| return switch (rules) {
.dx_legacy => 16,
.vk_relaxed, .gl_std140 => @max(16, try alignOf(t, a.elem, row_major, rules)),
else => alignOf(t, a.elem, row_major, rules),
},
.@"struct" => |st| return structAlign(t, st, rules),
else => return error.Unsupported,
}
}
/// Size in bytes (dx_legacy does not pad the last element / member).
pub fn sizeOf(t: *const TypeTable, ty: TypeId, row_major: bool, rules: Rules) Error!u32 {
switch (t.get(ty)) {
.scalar, .@"enum" => return scalarSize(t, ty),
.vector => |v| return v.len * scalarSize(t, ty),
.matrix => |m| {
const mv = matrixVectors(m, row_major);
const vec = mv.len * scalarSize(t, ty);
return switch (rules) {
.dx_legacy => (mv.count - 1) * 16 + vec,
else => mv.count * matrixStride(t, ty, row_major, rules),
};
},
.array => |a| {
const stride = try arrayStride(t, a.elem, row_major, rules);
return switch (rules) {
.dx_legacy => (a.len - 1) * stride + try sizeOf(t, a.elem, row_major, rules),
else => a.len * stride,
};
},
.@"struct" => |s| return structSize(t, s, rules),
else => return error.Unsupported,
}
}
/// Byte distance between array elements.
pub fn arrayStride(t: *const TypeTable, elem: TypeId, row_major: bool, rules: Rules) Error!u32 {
const size = try sizeOf(t, elem, row_major, rules);
return switch (rules) {
.dx_legacy, .vk_relaxed => roundUp(size, 16),
.gl_std140 => roundUp(size, @max(16, try alignOf(t, elem, row_major, rules))),
.std430, .gl_std430 => roundUp(size, try alignOf(t, elem, row_major, rules)),
.dx_packed => size,
.scalar => roundUp(size, try alignOf(t, elem, row_major, rules)),
};
}
/// Offset where a member of type `ty` goes when the previous one ended at
/// `off`.
pub fn place(t: *const TypeTable, off: u32, ty: TypeId, row_major: bool, rules: Rules) Error!u32 {
switch (t.get(ty)) {
.scalar, .@"enum", .vector => {
const size = try sizeOf(t, ty, row_major, rules);
switch (rules) {
// Strict GLSL: vectors at their full alignment.
.gl_std140, .gl_std430 => return roundUp(off, try alignOf(t, ty, row_major, rules)),
.scalar => return roundUp(off, scalarSize(t, ty)),
else => {},
}
// Relaxed placement: vectors of 32-bit (or narrower)
// components align like their components; 64-bit ones keep
// their full alignment (as dxc).
const s = scalarSize(t, ty);
const al = if (t.get(ty) == .vector and s > 4 and (rules == .vk_relaxed or rules == .std430)) vectorAlign(t.get(ty).vector.len, s) else s;
var o = roundUp(off, al);
// No straddling a 16-byte boundary (except tightly packed).
if (rules != .dx_packed and o / 16 != (o + size - 1) / 16) o = roundUp(o, 16);
return o;
},
.matrix, .array, .@"struct" => return roundUp(off, try alignOf(t, ty, row_major, rules)),
else => return error.Unsupported,
}
}
fn structAlign(t: *const TypeTable, info: *const types.StructInfo, rules: Rules) Error!u32 {
switch (rules) {
.dx_legacy => return 16,
else => {
var al: u32 = if (rules == .vk_relaxed or rules == .gl_std140) 16 else 1;
for (info.fields.items) |f| al = @max(al, try alignOf(t, f.type, f.row_major, rules));
return al;
},
}
}
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]);
return switch (rules) {
.dx_legacy => off,
// (Packed structs still round up to their widest component: a
// double and a float3 take 24 bytes.)
.dx_packed, .vk_relaxed, .std430, .gl_std140, .gl_std430, .scalar => roundUp(off, try structAlign(t, info, 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 {
var off: u32 = 0;
var first: usize = 0;
if (info.bases.items.len > 0 and rules != .dx_legacy and rules != .dx_packed) {
// dxc's SPIR-V keeps a base class as a nested struct (padded to
// 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]);
off = try structSize(t, base, rules);
}
// Explicit offsets (packoffset / register(cN)): the other members
// follow the last explicitly placed one.
var packed_end: ?u32 = null;
for (info.fields.items[first..]) |f| if (f.pack_offset) |po| {
packed_end = @max(packed_end orelse 0, po + try sizeOf(t, f.type, f.row_major, rules));
};
if (packed_end) |pe| off = @max(off, pe);
var end: u32 = off;
for (info.fields.items[first..], out[first..]) |f, *o| {
if (f.pack_offset) |po| {
o.* = po;
continue;
}
// [[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);
end = @max(end, off);
}
return @max(end, packed_end orelse 0);
}
/// Offsets of a struct's fields.
pub fn fieldOffsets(a: Allocator, t: *const TypeTable, info: *const types.StructInfo, rules: Rules) Error![]u32 {
const out = try a.alloc(u32, info.fields.items.len);
_ = try layoutFields(t, info, rules, out);
return out;
}
/// Byte offset of flattened component `k` of a value of type `ty` (row-major
/// component order for matrices, as the IR flattens them).
pub fn componentOffset(a: Allocator, t: *const TypeTable, ty: TypeId, row_major: bool, k: u32, rules: Rules) Error!u32 {
switch (t.get(ty)) {
.scalar, .@"enum" => return 0,
.vector => return k * scalarSize(t, ty),
.matrix => |m| {
const r = k / m.cols;
const c = k % m.cols;
const stride = matrixStride(t, ty, row_major, rules);
const s = scalarSize(t, ty);
return if (row_major) r * stride + c * s else c * stride + r * s;
},
.array => |arr| {
const n = try flatCount(t, arr.elem);
return (k / n) * try arrayStride(t, arr.elem, row_major, rules) + try componentOffset(a, t, arr.elem, row_major, k % n, rules);
},
.@"struct" => |s| {
const offs = try fieldOffsets(a, t, s, rules);
var kk = k;
for (s.fields.items, offs) |f, o| {
const n = try flatCount(t, f.type);
if (kk < n) return o + try componentOffset(a, t, f.type, f.row_major, kk, rules);
kk -= n;
}
return error.Unsupported;
},
else => return error.Unsupported,
}
}
pub fn flatCount(t: *const TypeTable, ty: TypeId) Error!u32 {
return switch (t.get(ty)) {
.scalar, .@"enum" => 1,
.vector => |v| v.len,
.matrix => |m| @as(u32, m.rows) * m.cols,
.array => |a| a.len * try flatCount(t, a.elem),
.@"struct" => |s| blk: {
var n: u32 = 0;
for (s.fields.items) |f| n += try flatCount(t, f.type);
break :blk n;
},
else => error.Unsupported,
};
}
test "layouts match dxc" {
var t = try TypeTable.init(std.testing.allocator);
defer t.deinit();
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const f = try t.scalar(.float);
const f2 = try t.vector(.float, 2);
const f3 = try t.vector(.float, 3);
try std.testing.expectEqual(@as(u32, 4), try place(&t, 4, f2, false, .dx_legacy));
try std.testing.expectEqual(@as(u32, 16), try place(&t, 12, f3, false, .dx_legacy));
try std.testing.expectEqual(@as(u32, 20), try sizeOf(&t, try t.array(f, 2), false, .dx_legacy));
try std.testing.expectEqual(@as(u32, 32), try sizeOf(&t, try t.array(f, 2), false, .vk_relaxed));
// struct S { float a; float3 b; float2 c; float d; float3 e; }
const s = try a.create(types.StructInfo);
s.* = .{ .name = "S", .complete = true };
for ([_]TypeId{ f, f3, f2, f, f3 }, 0..) |ft, i| try s.fields.append(a, .{ .name = &[_]u8{@intCast('a' + i)}, .type = ft });
const st = try t.intern(.{ .@"struct" = s });
try std.testing.expectEqualSlices(u32, &.{ 0, 4, 16, 24, 32 }, try fieldOffsets(a, &t, s, .std430));
try std.testing.expectEqual(@as(u32, 48), try sizeOf(&t, st, false, .std430));
try std.testing.expectEqualSlices(u32, &.{ 0, 4, 16, 24, 28 }, try fieldOffsets(a, &t, s, .dx_packed));
// float2x3: column-major in std430 is 3 vec2 columns (stride 8).
const m23 = try t.matrix(.float, 2, 3);
try std.testing.expectEqual(@as(u32, 24), try sizeOf(&t, m23, false, .std430));
try std.testing.expectEqual(@as(u32, 32), try sizeOf(&t, m23, true, .std430));
}

2526
src/ir/lower.zig Normal file

File diff suppressed because it is too large Load Diff

698
src/ir/opt.zig Normal file
View File

@ -0,0 +1,698 @@
//! IR optimizations shared by both backends: full unrolling of loops with
//! a constant trip count (`[unroll]`, and loops whose texel offsets must
//! become constants, as dxc's unrolling makes them) and constant folding.
const std = @import("std");
const Allocator = std.mem.Allocator;
const ir = @import("ir.zig");
const types = @import("../sema/types.zig");
const texture = @import("texture.zig");
const lower = @import("lower.zig");
const Ref = ir.Ref;
const BlockId = ir.BlockId;
const Op = ir.Op;
const Constant = ir.Constant;
const TypeId = types.TypeId;
const TypeTable = types.TypeTable;
const Scalar = types.Scalar;
pub fn run(a: Allocator, m: *ir.Module) Allocator.Error!void {
for (m.functions.items) |f| {
try unrollLoops(a, m.types, f);
try fold(a, m.types, f);
}
}
// ----------------------------------------------------------------------
// Scalar folding
fn scalarOf(t: *TypeTable, ty: TypeId) ?Scalar {
return switch (t.get(ty)) {
.scalar => |s| s,
else => null,
};
}
fn bits(s: Scalar) u7 {
return switch (s) {
.literal_int, .int64, .uint64 => 64,
.int16, .uint16 => 16,
else => 32,
};
}
/// `v` wrapped to the width and signedness of `s`.
fn wrapInt(s: Scalar, v: i64) i64 {
if (s == .bool) return @intFromBool(v != 0);
const n = bits(s);
if (n == 64) return v;
const mask = (@as(u64, 1) << @intCast(n)) - 1;
const u = @as(u64, @bitCast(v)) & mask;
if (s.isUnsigned()) return @intCast(u);
const sign = @as(u64, 1) << @intCast(n - 1);
return @bitCast(if (u & sign != 0) u | ~mask else u);
}
fn normalize(s: Scalar, c: Constant) Constant {
if (s.isFloat()) {
const v = switch (c) {
.float => |x| x,
.int => |x| @as(f64, @floatFromInt(x)),
};
return .{ .float = switch (s) {
.double => v,
.float16 => @as(f64, @as(f16, @floatCast(v))),
else => @as(f64, @as(f32, @floatCast(v))),
} };
}
return .{ .int = wrapInt(s, switch (c) {
.int => |x| x,
.float => |x| lower.saturatingInt(x),
}) };
}
fn asFloat(c: Constant) f64 {
return switch (c) {
.float => |x| x,
.int => |x| @floatFromInt(x),
};
}
fn asInt(c: Constant) i64 {
return switch (c) {
.int => |x| x,
.float => |x| lower.saturatingInt(x),
};
}
pub fn foldBinary(s: Scalar, op: ir.BinaryOp, x: Constant, y: Constant) ?Constant {
if (s.isFloat()) {
const p = asFloat(x);
const q = asFloat(y);
return normalize(s, .{ .float = switch (op) {
.add => p + q,
.sub => p - q,
.mul => p * q,
.div => p / q,
.rem => if (q == 0) return null else @rem(p, q),
else => return null,
} });
}
const p = asInt(x);
const q = asInt(y);
const n: u6 = @intCast(bits(s) - 1);
const r: i64 = switch (op) {
.add => p +% q,
.sub => p -% q,
.mul => p *% q,
.div => if (q == 0) return null else if (s.isUnsigned()) @intCast(@as(u64, @bitCast(p)) / @as(u64, @bitCast(q))) else if (p == std.math.minInt(i64) and q == -1) return null else @divTrunc(p, q),
.rem => if (q == 0) return null else if (s.isUnsigned()) @intCast(@as(u64, @bitCast(p)) % @as(u64, @bitCast(q))) else if (q == -1) 0 else @rem(p, q),
.shl => p << @intCast(@as(u64, @bitCast(q)) & n),
.shr => if (s.isUnsigned()) @bitCast(@as(u64, @bitCast(p)) >> @intCast(@as(u64, @bitCast(q)) & n)) else p >> @intCast(@as(u64, @bitCast(q)) & n),
.bit_and, .log_and => p & q,
.bit_or, .log_or => p | q,
.bit_xor => p ^ q,
};
return normalize(s, .{ .int = r });
}
pub fn foldCmp(s: Scalar, op: ir.CmpOp, x: Constant, y: Constant) ?Constant {
const r: bool = if (s.isFloat()) blk: {
const p = asFloat(x);
const q = asFloat(y);
break :blk switch (op) {
.eq => p == q,
.ne => p != q,
.lt => p < q,
.le => p <= q,
.gt => p > q,
.ge => p >= q,
};
} else if (s.isUnsigned()) blk: {
const p: u64 = @bitCast(asInt(x));
const q: u64 = @bitCast(asInt(y));
break :blk switch (op) {
.eq => p == q,
.ne => p != q,
.lt => p < q,
.le => p <= q,
.gt => p > q,
.ge => p >= q,
};
} else blk: {
const p = asInt(x);
const q = asInt(y);
break :blk switch (op) {
.eq => p == q,
.ne => p != q,
.lt => p < q,
.le => p <= q,
.gt => p > q,
.ge => p >= q,
};
};
return .{ .int = @intFromBool(r) };
}
pub fn foldUnary(s: Scalar, op: ir.UnaryOp, x: Constant) ?Constant {
return switch (op) {
.neg => if (s.isFloat()) normalize(s, .{ .float = -asFloat(x) }) else normalize(s, .{ .int = 0 -% asInt(x) }),
.not => .{ .int = @intFromBool(asInt(x) == 0) },
.bit_not => if (s.isFloat()) null else normalize(s, .{ .int = ~asInt(x) }),
};
}
pub fn foldConvert(from: Scalar, to: Scalar, x: Constant) Constant {
if (to == .bool) return .{ .int = @intFromBool(if (from.isFloat()) asFloat(x) != 0 else asInt(x) != 0) };
if (from.isFloat() and !to.isFloat() and to.isUnsigned() and asFloat(x) < 0) return .{ .int = 0 };
return normalize(to, x);
}
// ----------------------------------------------------------------------
// Operand mapping
fn mapRefs(a: Allocator, xs: []const Ref, ctx: anytype) Allocator.Error![]const Ref {
const out = try a.alloc(Ref, xs.len);
for (xs, out) |x, *o| o.* = ctx.map(x);
return out;
}
/// `op` with every operand passed through `ctx.map`.
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 => 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) } },
.binary => |x| .{ .binary = .{ .op = x.op, .lhs = ctx.map(x.lhs), .rhs = ctx.map(x.rhs) } },
.unary => |x| .{ .unary = .{ .op = x.op, .operand = ctx.map(x.operand) } },
.cmp => |x| .{ .cmp = .{ .op = x.op, .lhs = ctx.map(x.lhs), .rhs = ctx.map(x.rhs) } },
.convert => |x| .{ .convert = ctx.map(x) },
.bitcast => |x| .{ .bitcast = ctx.map(x) },
.splat => |x| .{ .splat = ctx.map(x) },
.extract => |x| .{ .extract = .{ .agg = ctx.map(x.agg), .index = x.index } },
.insert => |x| .{ .insert = .{ .agg = ctx.map(x.agg), .value = ctx.map(x.value), .index = x.index } },
.construct => |xs| .{ .construct = try mapRefs(a, xs, ctx) },
.shuffle => |x| .{ .shuffle = .{ .vec = ctx.map(x.vec), .components = x.components } },
.select => |x| .{ .select = .{ .cond = ctx.map(x.cond), .t = ctx.map(x.t), .f = ctx.map(x.f) } },
.call => |x| .{ .call = .{ .func = x.func, .args = try mapRefs(a, x.args, ctx) } },
.intrinsic => |x| .{ .intrinsic = .{ .name = x.name, .args = try mapRefs(a, x.args, ctx) } },
.res_load => |x| .{ .res_load = .{ .res = ctx.map(x.res), .index = ctx.map(x.index) } },
.res_store => |x| .{ .res_store = .{ .res = ctx.map(x.res), .index = ctx.map(x.index), .value = ctx.map(x.value) } },
.method => |x| .{ .method = .{ .name = x.name, .res = ctx.map(x.res), .args = try mapRefs(a, x.args, ctx) } },
.output => |x| .{ .output = .{ .element = x.element, .value = ctx.map(x.value) } },
.heap_resource => |h| .{ .heap_resource = .{ .index = ctx.map(h.index), .sampler = h.sampler } },
.spirv_inst => |x| blk: {
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 => {},
};
const n = try a.create(ir.SpirvInst);
n.* = x.*;
n.operands = ops;
break :blk .{ .spirv_inst = n };
},
.patch_output => |x| .{ .patch_output = .{ .element = x.element, .value = ctx.map(x.value) } },
.phi => |ps| blk: {
const out = try a.alloc(@typeInfo(@TypeOf(ps)).pointer.child, ps.len);
for (ps, out) |p, *o| o.* = .{ .value = ctx.map(p.value), .block = p.block };
break :blk .{ .phi = out };
},
};
}
/// Calls `ctx.use(r)` for every operand of `op` and of terminator `term`.
fn forOperands(a: Allocator, op: Op, ctx: anytype) Allocator.Error!void {
const Collect = struct {
inner: @TypeOf(ctx),
fn map(c: @This(), r: Ref) Ref {
if (r != .none) c.inner.use(r);
return r;
}
};
_ = try mapOp(a, op, Collect{ .inner = ctx });
}
fn termRefs(term: ir.Terminator) [1]Ref {
return .{switch (term) {
.ret => |r| r,
.cond_br => |c| c.cond,
.@"switch" => |s| s.value,
else => .none,
}};
}
fn successors(a: Allocator, term: ir.Terminator) Allocator.Error![]const BlockId {
return switch (term) {
.br => |b| try a.dupe(BlockId, &.{b}),
.cond_br => |c| try a.dupe(BlockId, &.{ c.then, c.@"else" }),
.@"switch" => |s| blk: {
const out = try a.alloc(BlockId, s.cases.len + 1);
out[0] = s.default;
for (s.cases, out[1..]) |c, *o| o.* = c.block;
break :blk out;
},
else => &.{},
};
}
fn reachable(a: Allocator, f: *ir.Function) Allocator.Error![]bool {
const seen = try a.alloc(bool, f.blocks.items.len);
@memset(seen, false);
var stack: std.ArrayList(u32) = .empty;
try stack.append(a, 0);
while (stack.pop()) |b| {
if (seen[b]) continue;
seen[b] = true;
for (try successors(a, f.blocks.items[b].term)) |s| try stack.append(a, s.index());
}
return seen;
}
// ----------------------------------------------------------------------
// Constant folding
/// Component `k` of `r` if it is a known constant.
fn componentConst(t: *TypeTable, f: *ir.Function, r: Ref, k: usize) ?Constant {
const i = f.inst(r);
switch (i.op) {
.constant => |c| return c,
.construct => |xs| {
if (t.get(i.ty) != .vector or k >= xs.len) return null;
const p = f.inst(xs[k]);
return if (p.op == .constant and scalarOf(t, p.ty) != null) p.op.constant else null;
},
else => return null,
}
}
fn isConst(t: *TypeTable, f: *ir.Function, r: Ref) bool {
const i = f.inst(r);
const n = componentCount(t, i.ty) orelse return false;
for (0..n) |k| if (componentConst(t, f, r, k) == null) return false;
return true;
}
fn componentCount(t: *TypeTable, ty: TypeId) ?usize {
return switch (t.get(ty)) {
.scalar => 1,
.vector => |v| v.len,
else => null,
};
}
fn addInst(a: Allocator, f: *ir.Function, inst: ir.Inst) Allocator.Error!Ref {
try f.insts.append(a, inst);
return @enumFromInt(f.insts.items.len - 1);
}
/// Folds operations on scalar and vector constants in place (vector
/// results become constructs of new constant scalars).
pub fn fold(a: Allocator, t: *TypeTable, f: *ir.Function) Allocator.Error!void {
const live = try reachable(a, f);
for (f.blocks.items, 0..) |*blk, bi| {
if (!live[bi]) continue;
var pos: usize = 0;
while (pos < blk.insts.items.len) : (pos += 1) {
const r = blk.insts.items[pos];
const i = f.inst(r);
const n = componentCount(t, i.ty) orelse continue;
const rs = t.component(i.ty) orelse continue;
var comps: [4]Constant = undefined;
if (n > 4) continue;
const ok = for (0..n) |k| {
comps[k] = (switch (i.op) {
.binary => |x| blk2: {
const p = componentConst(t, f, x.lhs, k) orelse break :blk2 null;
const q = componentConst(t, f, x.rhs, k) orelse break :blk2 null;
break :blk2 foldBinary(rs, x.op, p, q);
},
.unary => |x| foldUnary(rs, x.op, componentConst(t, f, x.operand, k) orelse break false),
.cmp => |x| blk2: {
const os = t.component(f.inst(x.lhs).ty) orelse break :blk2 null;
const p = componentConst(t, f, x.lhs, k) orelse break :blk2 null;
const q = componentConst(t, f, x.rhs, k) orelse break :blk2 null;
break :blk2 foldCmp(os, x.op, p, q);
},
.convert => |x| blk2: {
const fs = t.component(f.inst(x).ty) orelse break :blk2 null;
break :blk2 foldConvert(fs, rs, componentConst(t, f, x, k) orelse break :blk2 null);
},
.splat => |x| componentConst(t, f, x, 0),
.extract => |x| if (t.get(f.inst(x.agg).ty) == .vector) componentConst(t, f, x.agg, x.index) else null,
.shuffle => |x| componentConst(t, f, x.vec, x.components[k]),
else => null,
}) orelse break false;
} else true;
if (!ok) continue;
if (n == 1) {
f.insts.items[r.index()].op = .{ .constant = comps[0] };
continue;
}
// New scalar constants go just before the folded instruction.
const st = try t.scalar(rs);
const parts = try a.alloc(Ref, n);
for (parts, comps[0..n]) |*p, c| {
p.* = try addInst(a, f, .{ .op = .{ .constant = c }, .ty = st });
try blk.insts.insert(a, pos, p.*);
pos += 1;
}
f.insts.items[r.index()].op = .{ .construct = parts };
}
}
}
// ----------------------------------------------------------------------
// Loop unrolling
const unroll_limit = 1024;
/// Trip limit for loops unrolled only to make texel offsets constant.
const auto_unroll_limit = 64;
/// Evaluates scalar `r` with the induction variable `iv` holding `v`.
fn eval(t: *TypeTable, f: *ir.Function, r: Ref, iv: Ref, v: ?Constant, depth: u32) ?Constant {
if (depth > 64) return null;
const i = f.inst(r);
const s = scalarOf(t, i.ty) orelse return null;
return switch (i.op) {
.constant => |c| c,
.load => |p| if (p == iv) v else null,
.convert => |x| foldConvert(scalarOf(t, f.inst(x).ty) orelse return null, s, eval(t, f, x, iv, v, depth + 1) orelse return null),
.binary => |x| foldBinary(s, x.op, eval(t, f, x.lhs, iv, v, depth + 1) orelse return null, eval(t, f, x.rhs, iv, v, depth + 1) orelse return null),
.unary => |x| foldUnary(s, x.op, eval(t, f, x.operand, iv, v, depth + 1) orelse return null),
.cmp => |x| foldCmp(scalarOf(t, f.inst(x.lhs).ty) orelse return null, x.op, eval(t, f, x.lhs, iv, v, depth + 1) orelse return null, eval(t, f, x.rhs, iv, v, depth + 1) orelse return null),
else => null,
};
}
fn unrollLoops(a: Allocator, t: *TypeTable, f: *ir.Function) Allocator.Error!void {
var kept: std.AutoHashMapUnmanaged(u32, void) = .empty;
while (true) {
const live = try reachable(a, f);
// An innermost loop not yet tried: no other candidate inside it.
var pick: ?u32 = null;
var sets: std.AutoHashMapUnmanaged(u32, []bool) = .empty;
for (f.blocks.items, 0..) |blk, bi| {
if (!live[bi] or blk.merge != .loop or kept.contains(@intCast(bi))) continue;
try sets.put(a, @intCast(bi), try loopBlocks(a, f, @intCast(bi)));
}
var it = sets.iterator();
outer: while (it.next()) |kv| {
var it2 = sets.iterator();
while (it2.next()) |other| {
if (other.key_ptr.* != kv.key_ptr.* and kv.value_ptr.*[other.key_ptr.*]) continue :outer;
}
pick = kv.key_ptr.*;
break;
}
const h = pick orelse return;
if (!try unrollOne(a, t, f, h, sets.get(h).?, live)) try kept.put(a, h, {});
}
}
/// Blocks of the loop headed by `h` (header excluded, merge excluded).
fn loopBlocks(a: Allocator, f: *ir.Function, h: u32) Allocator.Error![]bool {
const set = try a.alloc(bool, f.blocks.items.len);
@memset(set, false);
const merge = f.blocks.items[h].merge.loop.merge.index();
var stack: std.ArrayList(u32) = .empty;
for (try successors(a, f.blocks.items[h].term)) |s| try stack.append(a, s.index());
while (stack.pop()) |b| {
if (b == h or b == merge or set[b]) continue;
set[b] = true;
for (try successors(a, f.blocks.items[b].term)) |s| try stack.append(a, s.index());
}
return set;
}
fn isPure(op: Op) bool {
return switch (op) {
.constant, .load, .binary, .unary, .cmp, .convert, .splat, .extract, .shuffle, .construct => true,
else => false,
};
}
/// Whether the loop body samples or loads with texel offsets (which DXIL
/// and Vulkan need as constants).
fn hasTexelOffsets(t: *TypeTable, f: *ir.Function, set: []const bool) bool {
for (f.blocks.items, 0..) |blk, bi| {
if (!set[bi]) continue;
for (blk.insts.items) |r| {
const m = switch (f.inst(r).op) {
.method => |m| m,
else => continue,
};
const rk = switch (t.get(f.inst(m.res).ty)) {
.resource => |rk| rk,
else => continue,
};
const sh = texture.shape(rk.kind) orelse continue;
const call = texture.decode(m.name, sh, m.args.len) orelse continue;
if (call.offset != null) return true;
}
}
return false;
}
fn unrollOne(a: Allocator, t: *TypeTable, f: *ir.Function, h: u32, set: []const bool, live: []const bool) Allocator.Error!bool {
const hb = f.blocks.items[h];
const lp = hb.merge.loop;
if (lp.unroll == .dont) return false;
const merge = lp.merge.index();
const cont = lp.@"continue".index();
// header: `br check`; check: `br cond, body, merge`; continue: `br header`.
if (hb.insts.items.len != 0 or hb.term != .br) return false;
const check = hb.term.br.index();
if (!set[check] or !set[cont]) return false;
const cb = f.blocks.items[check];
if (cb.term != .cond_br or cb.term.cond_br.@"else".index() != merge) return false;
const body = cb.term.cond_br.then.index();
if (body == cont or f.blocks.items[cont].term != .br or f.blocks.items[cont].term.br.index() != h) return false;
for (cb.insts.items) |r| if (!isPure(f.inst(r).op)) return false;
// No break (other edges to merge), no continue (several edges to the
// continue block): their unrolled jumps would leave structured regions.
var preheader: ?u32 = null;
var cont_preds: u32 = 0;
for (f.blocks.items, 0..) |blk, bi| {
if (!live[bi]) continue;
for (try successors(a, blk.term)) |s| {
const si = s.index();
if (si == merge and set[bi] and bi != check) return false;
if (si == cont and set[bi]) cont_preds += 1;
if (si == h and !set[bi]) {
if (preheader != null) return false;
preheader = @intCast(bi);
}
}
}
if (cont_preds != 1) return false;
const pre = preheader orelse return false;
// The induction variable: the one local the condition reads.
var iv: Ref = .none;
for (cb.insts.items) |r| switch (f.inst(r).op) {
.load => |p| {
if (f.inst(p).op != .local_var) return false;
if (iv != .none and iv != p) return false;
iv = p;
},
else => {},
};
if (iv == .none or scalarOf(t, f.inst(iv).ty) == null) return false;
// Only loads and stores touch it; inside the loop only the continue
// block stores to it, once.
var step: Ref = .none;
var step_pos: usize = 0;
for (f.blocks.items, 0..) |blk, bi| {
if (!live[bi]) continue;
for (blk.insts.items, 0..) |r, pos| {
const op = f.inst(r).op;
switch (op) {
.load => continue,
.store => |s| {
if (s.value == iv) return false;
if (s.ptr == iv and set[bi]) {
if (bi != cont or step != .none) return false;
step = s.value;
step_pos = pos;
}
continue;
},
else => {},
}
const Uses = struct {
iv: Ref,
bad: *bool,
fn use(c: @This(), x: Ref) void {
if (x == c.iv) c.bad.* = true;
}
};
var bad = false;
try forOperands(a, op, Uses{ .iv = iv, .bad = &bad });
if (bad) return false;
}
}
if (step == .none) return false;
// Its value on entry: the last store in the preheader.
const pb = f.blocks.items[pre];
if (pb.term != .br) return false;
var init: ?Constant = null;
var k = pb.insts.items.len;
while (k > 0) {
k -= 1;
const op = f.inst(pb.insts.items[k]).op;
if (op == .store and op.store.ptr == iv) {
init = eval(t, f, op.store.value, .none, null, 0) orelse return false;
break;
}
}
var v = init orelse return false;
const wanted = lp.unroll == .unroll or hasTexelOffsets(t, f, set);
if (!wanted) return false;
const limit: usize = if (lp.unroll == .unroll) unroll_limit else auto_unroll_limit;
const cond = cb.term.cond_br.cond;
var values: std.ArrayList(Constant) = .empty;
while (true) {
const c = eval(t, f, cond, iv, v, 0) orelse return false;
if (asInt(c) == 0) break;
if (values.items.len >= limit) return false;
try values.append(a, v);
v = eval(t, f, step, iv, v, 0) orelse return false;
}
// The condition block is dropped: nothing else may use its values.
{
var from_check: std.AutoHashMapUnmanaged(u32, void) = .empty;
for (cb.insts.items) |r| try from_check.put(a, r.index(), {});
const Uses = struct {
defined: *const std.AutoHashMapUnmanaged(u32, void),
bad: *bool,
fn use(c: @This(), x: Ref) void {
if (c.defined.contains(x.index())) c.bad.* = true;
}
};
var bad = false;
for (f.blocks.items, 0..) |blk, bi| {
if (!live[bi] or bi == check) continue;
for (blk.insts.items) |r| try forOperands(a, f.inst(r).op, Uses{ .defined = &from_check, .bad = &bad });
const tr = termRefs(blk.term)[0];
if (tr != .none and from_check.contains(tr.index())) bad = true;
}
if (bad) return false;
}
// Values made inside the loop must not be used after it.
var defined: std.AutoHashMapUnmanaged(u32, void) = .empty;
for (f.blocks.items, 0..) |blk, bi| if (set[bi]) for (blk.insts.items) |r| try defined.put(a, r.index(), {});
for (f.blocks.items, 0..) |blk, bi| {
if (!live[bi] or set[bi] or bi == h) continue;
const Uses = struct {
defined: *const std.AutoHashMapUnmanaged(u32, void),
bad: *bool,
fn use(c: @This(), x: Ref) void {
if (c.defined.contains(x.index())) c.bad.* = true;
}
};
var bad = false;
for (blk.insts.items) |r| try forOperands(a, f.inst(r).op, Uses{ .defined = &defined, .bad = &bad });
const tr = termRefs(blk.term)[0];
if (tr != .none and defined.contains(tr.index())) bad = true;
if (bad) return false;
}
// Clone the body and continue block once per iteration, chained.
const iv_ty = f.inst(iv).ty;
const iv_s = scalarOf(t, iv_ty).?;
const entries = try a.alloc(u32, values.items.len);
const conts = try a.alloc(u32, values.items.len);
const n_blocks = f.blocks.items.len;
for (values.items, 0..) |val, iter| {
const next = foldStep(t, f, step, iv, val);
var bmap: std.AutoHashMapUnmanaged(u32, u32) = .empty;
for (0..n_blocks) |bi| {
if (!set[bi] or bi == check) continue;
try f.blocks.append(a, .{});
try bmap.put(a, @intCast(bi), @intCast(f.blocks.items.len - 1));
}
var imap: std.AutoHashMapUnmanaged(u32, Ref) = .empty;
for (0..n_blocks) |bi| {
if (!set[bi] or bi == check) continue;
for (f.blocks.items[bi].insts.items) |r| {
try imap.put(a, r.index(), try addInst(a, f, f.inst(r)));
}
}
const Map = struct {
m: *const std.AutoHashMapUnmanaged(u32, Ref),
fn map(c: @This(), x: Ref) Ref {
if (x == .none) return x;
return c.m.get(x.index()) orelse x;
}
};
const mp = Map{ .m = &imap };
for (0..n_blocks) |bi| {
if (!set[bi] or bi == check) continue;
const src = f.blocks.items[bi];
const nb = bmap.get(@intCast(bi)).?;
var insts: std.ArrayList(Ref) = .empty;
for (src.insts.items, 0..) |r, pos| {
const nr = imap.get(r.index()).?;
const op = f.inst(r).op;
if (op == .load and op.load == iv) {
// Loads after the step store see the next value.
const c = if (bi == cont and pos > step_pos) next orelse return false else val;
f.insts.items[nr.index()] = .{ .op = .{ .constant = normalize(iv_s, c) }, .ty = f.inst(r).ty };
} else {
f.insts.items[nr.index()].op = try mapOp(a, op, mp);
}
try insts.append(a, nr);
}
const mapBlock = struct {
fn g(bm: *const std.AutoHashMapUnmanaged(u32, u32), b: BlockId) BlockId {
return if (bm.get(b.index())) |x| @enumFromInt(x) else b;
}
}.g;
var term = src.term;
switch (term) {
.ret => |x| term = .{ .ret = mp.map(x) },
.br => |b| term = .{ .br = mapBlock(&bmap, b) },
.cond_br => |c| term = .{ .cond_br = .{ .cond = mp.map(c.cond), .then = mapBlock(&bmap, c.then), .@"else" = mapBlock(&bmap, c.@"else") } },
.@"switch" => |sw| {
const cases = try a.alloc(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases.len);
for (sw.cases, cases) |c, *o| o.* = .{ .value = c.value, .block = mapBlock(&bmap, c.block) };
term = .{ .@"switch" = .{ .value = mp.map(sw.value), .default = mapBlock(&bmap, sw.default), .cases = cases } };
},
else => {},
}
const mg: ir.Merge = switch (src.merge) {
.none => .none,
.selection => |b| .{ .selection = mapBlock(&bmap, b) },
.loop => |l| .{ .loop = .{ .merge = mapBlock(&bmap, l.merge), .@"continue" = mapBlock(&bmap, l.@"continue"), .unroll = l.unroll } },
};
f.blocks.items[nb] = .{ .insts = insts, .term = term, .merge = mg };
}
entries[iter] = bmap.get(body).?;
conts[iter] = bmap.get(cont).?;
}
for (conts, 0..) |c, iter| {
f.blocks.items[c].term = .{ .br = @enumFromInt(if (iter + 1 < entries.len) entries[iter + 1] else merge) };
}
f.blocks.items[pre].term = .{ .br = @enumFromInt(if (entries.len > 0) entries[0] else merge) };
return true;
}
fn foldStep(t: *TypeTable, f: *ir.Function, step: Ref, iv: Ref, v: Constant) ?Constant {
return eval(t, f, step, iv, v, 0);
}
test "constant folding helpers" {
try std.testing.expectEqual(@as(i64, -2147483648), foldBinary(.int, .add, .{ .int = 2147483647 }, .{ .int = 1 }).?.int);
try std.testing.expectEqual(@as(i64, 4294967295), foldBinary(.uint, .sub, .{ .int = 0 }, .{ .int = 1 }).?.int);
try std.testing.expect(foldBinary(.int, .div, .{ .int = 1 }, .{ .int = 0 }) == null);
try std.testing.expectEqual(@as(i64, 1), foldCmp(.uint, .gt, .{ .int = 4294967295 }, .{ .int = 1 }).?.int);
try std.testing.expectEqual(@as(i64, 0), foldCmp(.int, .gt, .{ .int = -1 }, .{ .int = 1 }).?.int);
try std.testing.expectEqual(@as(i64, 3), foldConvert(.float, .int, .{ .float = 3.7 }).int);
}

292
src/ir/texture.zig Normal file
View File

@ -0,0 +1,292 @@
//! Texture and typed-buffer methods, decoded for the backends: which
//! argument plays which role (sampler, coordinate, offset, LOD, ...) in
//! each overload from dxc's intrinsic table.
const std = @import("std");
const types = @import("../sema/types.zig");
pub const Kind = types.ResourceKind;
pub const Dim = enum { d1, d2, d3, cube, buffer };
pub const Shape = struct {
dim: Dim,
array: bool = false,
ms: bool = false,
rw: bool = false,
/// A combined image sampler (vk::SampledTexture*): sampling methods
/// take no sampler argument.
combined: bool = false,
/// Coordinate components, without the array index.
pub fn coords(s: Shape) u8 {
return switch (s.dim) {
.d1, .buffer => 1,
.d2 => 2,
.d3, .cube => 3,
};
}
/// Components of a texel offset (none for cubes and buffers).
pub fn offsets(s: Shape) u8 {
return switch (s.dim) {
.d1 => 1,
.d2 => 2,
.d3 => 3,
.cube, .buffer => 0,
};
}
/// Whether the resource has mip levels (Load takes one, GetDimensions
/// reports them).
pub fn hasMips(s: Shape) bool {
return !s.rw and !s.ms and s.dim != .buffer;
}
};
pub fn shape(kind: Kind) ?Shape {
return switch (kind) {
.buffer => .{ .dim = .buffer },
.rw_buffer => .{ .dim = .buffer, .rw = true },
.texture1d => .{ .dim = .d1 },
.texture1d_array => .{ .dim = .d1, .array = true },
.texture2d => .{ .dim = .d2 },
.texture2d_array => .{ .dim = .d2, .array = true },
.texture2dms => .{ .dim = .d2, .ms = true },
.texture2dms_array => .{ .dim = .d2, .array = true, .ms = true },
.texture3d => .{ .dim = .d3 },
.texture_cube => .{ .dim = .cube },
.texture_cube_array => .{ .dim = .cube, .array = true },
.rw_texture1d => .{ .dim = .d1, .rw = true },
.rw_texture1d_array => .{ .dim = .d1, .array = true, .rw = true },
.rw_texture2d => .{ .dim = .d2, .rw = true },
.rw_texture2d_array => .{ .dim = .d2, .array = true, .rw = true },
.rw_texture2dms => .{ .dim = .d2, .ms = true, .rw = true },
.rw_texture2dms_array => .{ .dim = .d2, .array = true, .ms = true, .rw = true },
.rw_texture3d => .{ .dim = .d3, .rw = true },
.sampled_texture1d => .{ .dim = .d1, .combined = true },
.sampled_texture1d_array => .{ .dim = .d1, .array = true, .combined = true },
.sampled_texture2d => .{ .dim = .d2, .combined = true },
.sampled_texture2d_array => .{ .dim = .d2, .array = true, .combined = true },
.sampled_texture2dms => .{ .dim = .d2, .ms = true, .combined = true },
.sampled_texture2dms_array => .{ .dim = .d2, .array = true, .ms = true, .combined = true },
.sampled_texture3d => .{ .dim = .d3, .combined = true },
.sampled_texture_cube => .{ .dim = .cube, .combined = true },
.sampled_texture_cube_array => .{ .dim = .cube, .array = true, .combined = true },
else => null,
};
}
pub const Op = enum {
sample,
sample_bias,
sample_level,
sample_grad,
sample_cmp,
sample_cmp_level_zero,
sample_cmp_level,
sample_cmp_bias,
sample_cmp_grad,
gather,
gather_cmp,
load,
calc_lod,
calc_lod_unclamped,
sample_position,
pub fn isCmp(op: Op) bool {
return switch (op) {
.sample_cmp, .sample_cmp_level_zero, .sample_cmp_level, .sample_cmp_bias, .sample_cmp_grad, .gather_cmp => true,
else => false,
};
}
/// Needs implicit derivatives (pixel shaders only, for zdxc).
pub fn implicitLod(op: Op) bool {
return switch (op) {
.sample, .sample_bias, .sample_cmp, .sample_cmp_bias, .calc_lod, .calc_lod_unclamped => true,
else => false,
};
}
};
/// Argument positions of one method call (null: absent).
pub const Call = struct {
op: Op,
sampler: ?u8 = null,
coord: u8 = 0,
compare: ?u8 = null,
bias: ?u8 = null,
lod: ?u8 = null,
ddx: ?u8 = null,
ddy: ?u8 = null,
/// One offset, or the first of four (Gather with per-texel offsets).
offset: ?u8 = null,
offsets4: bool = false,
clamp: ?u8 = null,
status: ?u8 = null,
sample_index: ?u8 = null,
/// Gather channel: 0 red ... 3 alpha.
channel: u2 = 0,
};
const Sampled = struct { name: []const u8, op: Op, extra: []const Role, has_clamp: bool };
const Role = enum { compare, bias, lod, ddx, ddy };
const sampled = [_]Sampled{
.{ .name = "Sample", .op = .sample, .extra = &.{}, .has_clamp = true },
.{ .name = "SampleBias", .op = .sample_bias, .extra = &.{.bias}, .has_clamp = true },
.{ .name = "SampleLevel", .op = .sample_level, .extra = &.{.lod}, .has_clamp = false },
.{ .name = "SampleGrad", .op = .sample_grad, .extra = &.{ .ddx, .ddy }, .has_clamp = true },
.{ .name = "SampleCmp", .op = .sample_cmp, .extra = &.{.compare}, .has_clamp = true },
.{ .name = "SampleCmpLevelZero", .op = .sample_cmp_level_zero, .extra = &.{.compare}, .has_clamp = false },
.{ .name = "SampleCmpLevel", .op = .sample_cmp_level, .extra = &.{ .compare, .lod }, .has_clamp = false },
.{ .name = "SampleCmpBias", .op = .sample_cmp_bias, .extra = &.{ .compare, .bias }, .has_clamp = true },
.{ .name = "SampleCmpGrad", .op = .sample_cmp_grad, .extra = &.{ .compare, .ddx, .ddy }, .has_clamp = true },
};
/// Decodes `name(args...)` on a resource of shape `s`; null for methods
/// that are not texture operations (GetDimensions is handled apart).
pub fn decode(name: []const u8, s: Shape, nargs: usize) ?Call {
if (s.combined) {
// As with a sampler argument, every index one lower.
var plain = s;
plain.combined = false;
var c = decodePlain(name, plain, nargs + 1) orelse return null;
if (c.sampler == null) return decodePlain(name, plain, nargs);
c.sampler = null;
c.coord -= 1;
inline for (.{ "compare", "bias", "lod", "ddx", "ddy", "offset", "clamp", "status", "sample_index" }) |f| {
if (@field(c, f)) |*k| k.* -= 1;
}
return c;
}
return decodePlain(name, s, nargs);
}
fn decodePlain(name: []const u8, s: Shape, nargs: usize) ?Call {
const eq = std.mem.eql;
const n: u8 = @intCast(nargs);
for (sampled) |sm| if (eq(u8, name, sm.name)) {
var c: Call = .{ .op = sm.op, .sampler = 0, .coord = 1 };
var i: u8 = 2;
for (sm.extra) |r| {
switch (r) {
.compare => c.compare = i,
.bias => c.bias = i,
.lod => c.lod = i,
.ddx => c.ddx = i,
.ddy => c.ddy = i,
}
i += 1;
}
if (i < n and s.offsets() > 0) {
c.offset = i;
i += 1;
}
if (sm.has_clamp and i < n and n - i >= 1) {
// Clamp comes before status; an overload with status has both.
c.clamp = i;
i += 1;
}
if (i < n) c.status = i;
return c;
};
if (std.mem.startsWith(u8, name, "Gather")) {
var rest = name["Gather".len..];
var c: Call = .{ .op = .gather, .sampler = 0, .coord = 1 };
if (std.mem.startsWith(u8, rest, "Cmp")) {
c.op = .gather_cmp;
c.compare = 2;
rest = rest[3..];
}
if (eq(u8, rest, "Raw")) return null;
c.channel = if (rest.len == 0 or eq(u8, rest, "Red")) 0 else if (eq(u8, rest, "Green")) 1 else if (eq(u8, rest, "Blue")) 2 else if (eq(u8, rest, "Alpha")) 3 else return null;
const first: u8 = if (c.compare != null) 3 else 2;
const left = n - first;
if (s.offsets() == 0) {
// Cubes take no offsets: only a status.
if (left == 1) c.status = first;
return c;
}
if (left == 1 or left == 2) c.offset = first;
if (left == 4 or left == 5) {
c.offset = first;
c.offsets4 = true;
}
if (left == 2 or left == 5) c.status = n - 1;
return c;
}
if (eq(u8, name, "Load")) {
var c: Call = .{ .op = .load, .coord = 0 };
var i: u8 = 1;
if (s.ms) {
c.sample_index = 1;
i = 2;
}
if (i < n and s.offsets() > 0 and !s.rw) {
c.offset = i;
i += 1;
}
if (i < n) c.status = i;
return c;
}
if (eq(u8, name, "CalculateLevelOfDetail")) return .{ .op = .calc_lod, .sampler = 0, .coord = 1 };
if (eq(u8, name, "CalculateLevelOfDetailUnclamped")) return .{ .op = .calc_lod_unclamped, .sampler = 0, .coord = 1 };
if (eq(u8, name, "GetSamplePosition")) return .{ .op = .sample_position, .sample_index = 0 };
return null;
}
/// GetDimensions(...) out parameters, in order, as the components of dxc's
/// `Dimensions` result they receive (0..2: sizes, 3: levels or samples).
pub const Dims = struct {
/// Index of the mip-level argument, if given.
mip: ?u8 = null,
/// (argument index, result component) pairs.
outs: [4]struct { arg: u8, comp: u8 } = undefined,
count: u8 = 0,
};
pub fn getDimensions(s: Shape, nargs: usize) Dims {
var d: Dims = .{};
var first: u8 = 0;
if (s.hasMips() and nargs == @as(usize, s.coords() - @intFromBool(s.dim == .cube)) + @intFromBool(s.array) + 2) {
d.mip = 0;
first = 1;
}
const n: u8 = @intCast(nargs);
var comp: u8 = 0;
var i = first;
while (i < n) : (i += 1) {
// The last of several is levels / samples (component 3), as in
// dxc's TranslateGetDimensions.
const last_special = (d.mip != null or s.ms or s.hasMips()) and i == n - 1 and i > first;
const want_levels = d.mip != null or s.ms;
const c: u8 = if (last_special and want_levels) 3 else comp;
d.outs[d.count] = .{ .arg = i, .comp = c };
d.count += 1;
comp += 1;
}
return d;
}
test "decode texture methods" {
const t2: Shape = .{ .dim = .d2 };
const c = decode("SampleGrad", t2, 6).?;
try std.testing.expectEqual(@as(?u8, 2), c.ddx);
try std.testing.expectEqual(@as(?u8, 4), c.offset);
try std.testing.expectEqual(@as(?u8, 5), c.clamp);
const g = decode("GatherCmpGreen", t2, 7).?;
try std.testing.expect(g.offsets4);
try std.testing.expectEqual(@as(u2, 1), g.channel);
const l = decode("Load", .{ .dim = .d2, .ms = true }, 3).?;
try std.testing.expectEqual(@as(?u8, 1), l.sample_index);
try std.testing.expectEqual(@as(?u8, 2), l.offset);
// GetDimensions(mip, w, h, levels) on Texture2D.
const d = getDimensions(t2, 4);
try std.testing.expectEqual(@as(?u8, 0), d.mip);
try std.testing.expectEqual(@as(u8, 3), d.outs[2].comp);
// GetDimensions(w, h) without a mip level.
const d2 = getDimensions(t2, 2);
try std.testing.expectEqual(@as(u8, 1), d2.outs[1].comp);
}

View File

@ -13,9 +13,17 @@ const Options = struct {
output: ?[]const u8 = null, output: ?[]const u8 = null,
input: ?[]const u8 = null, input: ?[]const u8 = null,
spirv: bool = false, spirv: bool = false,
/// -fspv-target-env (vulkan1.0 by default).
target_env: []const u8 = "vulkan1.0",
preprocess: bool = false, preprocess: bool = false,
pp_output: ?[]const u8 = null, pp_output: ?[]const u8 = null,
enable_16bit: bool = false, enable_16bit: bool = false,
/// -force-rootsig-ver, -Qstrip_rootsignature, -rootsig-define, -Frs.
rootsig_ver: ?[]const u8 = null,
strip_rootsig: bool = false,
rootsig_define: ?[]const u8 = null,
rootsig_output: ?[]const u8 = null,
vk: zdxc.ir.ir.VkOptions = .{},
defines: std.ArrayList(front.preproc.Define) = .empty, defines: std.ArrayList(front.preproc.Define) = .empty,
include_dirs: std.ArrayList([]const u8) = .empty, include_dirs: std.ArrayList([]const u8) = .empty,
empty: bool = false, empty: bool = false,
@ -29,6 +37,8 @@ const Options = struct {
error_limit: u32 = 20, error_limit: u32 = 20,
parse: bool = false, parse: bool = false,
dump_ast: bool = false, dump_ast: bool = false,
sema: bool = false,
dump_ir: bool = false,
/// -O0..-O3 / -Od (default -O3, as in dxc). /// -O0..-O3 / -Od (default -O3, as in dxc).
opt_level: enum { od, o0, o1, o2, o3 } = .o3, opt_level: enum { od, o0, o1, o2, o3 } = .o3,
/// Accepted options with no effect yet, reported once each. /// Accepted options with no effect yet, reported once each.
@ -91,6 +101,8 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std
opts.parse = true; opts.parse = true;
opts.dump_ast = true; opts.dump_ast = true;
}, },
.zdxc_sema => opts.sema = true,
.zdxc_ir => opts.dump_ir = true,
.fcolor_diagnostics => opts.color = true, .fcolor_diagnostics => opts.color = true,
.fno_color_diagnostics => opts.color = false, .fno_color_diagnostics => opts.color = false,
}, },
@ -118,7 +130,59 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std
}, },
.P => opts.preprocess = true, .P => opts.preprocess = true,
.spirv => opts.spirv = true, .spirv => opts.spirv = true,
.fspv_target_env_EQ => opts.target_env = v,
.enable_16bit_types => opts.enable_16bit = true, .enable_16bit_types => opts.enable_16bit = true,
.force_rootsig_ver, .force_rootsig_ver_ => opts.rootsig_ver = v,
.Qstrip_rootsignature => opts.strip_rootsig = true,
.rootsig_define => opts.rootsig_define = v,
.Frs => opts.rootsig_output = v,
.fvk_b_shift, .fvk_t_shift, .fvk_s_shift, .fvk_u_shift => {
const k: usize = switch (id) {
.fvk_b_shift => 0,
.fvk_t_shift => 1,
.fvk_s_shift => 2,
else => 3,
};
const shift = std.fmt.parseInt(u32, a.values[0], 10) catch return cli.fail("invalid {s} shift '{s}'", .{ a.spelling, a.values[0] });
const set: ?u32 = if (std.mem.eql(u8, a.values[1], "all")) null else std.fmt.parseInt(u32, a.values[1], 10) catch return cli.fail("invalid {s} space '{s}'", .{ a.spelling, a.values[1] });
try opts.vk.shifts[k].append(arena, .{ .shift = shift, .set = set });
},
.fvk_bind_globals => opts.vk.bind_globals = .{
std.fmt.parseInt(u32, a.values[0], 10) catch return cli.fail("invalid -fvk-bind-globals binding number: {s}", .{a.values[0]}),
std.fmt.parseInt(u32, a.values[1], 10) catch return cli.fail("invalid -fvk-bind-globals set number: {s}", .{a.values[1]}),
},
.fvk_bind_register, .vkbr => {
const reg = a.values[0];
if (reg.len < 2 or std.mem.indexOfScalar(u8, "btsu", reg[0]) == null) return cli.fail("invalid -fvk-bind-register register '{s}'", .{reg});
const num = struct {
fn f(c: Cli, t: []const u8) !u32 {
return std.fmt.parseInt(u32, t, 10) catch c.fail("invalid -fvk-bind-register number '{s}'", .{t});
}
}.f;
try opts.vk.bind_register.append(arena, .{ .class = reg[0], .index = try num(cli, reg[1..]), .space = try num(cli, a.values[1]), .binding = try num(cli, a.values[2]), .set = try num(cli, a.values[3]) });
},
.auto_binding_space => opts.vk.auto_binding_space = std.fmt.parseInt(u32, v, 10) catch return cli.fail("invalid -auto-binding-space '{s}'", .{v}),
.fvk_auto_shift_bindings => opts.vk.auto_shift = true,
.fspv_flatten_resource_arrays => opts.vk.flatten_arrays = true,
.fspv_use_legacy_buffer_matrix_order => opts.vk.legacy_matrix_order = true,
.fspv_use_vulkan_memory_model => opts.vk.vulkan_memory_model = true,
// (zdxc never removes interface variables.)
.fspv_preserve_interface => {},
.fvk_invert_y => opts.vk.invert_y = true,
.fvk_use_gl_layout => opts.vk.layout = .gl,
.fvk_use_dx_layout => opts.vk.layout = .dx,
.fvk_use_scalar_layout => opts.vk.layout = .scalar,
.fspv_entrypoint_name_EQ => opts.vk.entry_name = v,
.fspv_extension_EQ => try opts.vk.extensions.append(arena, v),
.fspv_reflect => opts.vk.reflect = true,
.fspv_enable_maximal_reconvergence => opts.vk.maximal_reconvergence = true,
.fvk_support_nonzero_base_instance => opts.vk.nonzero_base_instance = true,
.fvk_support_nonzero_base_vertex => opts.vk.nonzero_base_vertex = true,
.fspv_use_unknown_image_format => opts.vk.unknown_image_format = true,
.fvk_use_dx_position_w => opts.vk.dx_position_w = true,
.fvk_stage_io_order_EQ => {
if (std.mem.eql(u8, v, "alpha")) opts.vk.alpha_io_order = true else if (!std.mem.eql(u8, v, "decl")) return cli.fail("unknown -fvk-stage-io-order '{s}'", .{v});
},
._SLASH_WX => opts.warnings_as_errors = true, ._SLASH_WX => opts.warnings_as_errors = true,
.no_warnings => opts.no_warnings = true, .no_warnings => opts.no_warnings = true,
.W_Joined => { .W_Joined => {
@ -206,12 +270,24 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
return; return;
} }
// Root signature targets: the root signature in the macro -E names.
if (opts.profile) |p| if (std.mem.eql(u8, p, "rootsig_1_0") or std.mem.eql(u8, p, "rootsig_1_1")) {
const input = opts.input orelse return cli.fail("no input file", .{});
const out = opts.output orelse return cli.fail("missing -Fo <file>", .{});
const version: zdxc.dxil.rootsig.Version = if (std.mem.eql(u8, p, "rootsig_1_0")) .v1_0 else .v1_1;
const blob = try compileRootSignatureMacro(cli, arena, opts, input, opts.entry, version, .none) orelse return error.CompileFailed;
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = out, .data = try rootSignatureContainer(arena, blob) });
return;
};
const profile: ?shader.Profile = if (opts.profile) |p| const profile: ?shader.Profile = if (opts.profile) |p|
shader.Profile.parse(p) orelse return cli.fail("unknown profile '{s}'", .{p}) shader.Profile.parse(p) orelse return cli.fail("unknown profile '{s}'", .{p})
else else
null; null;
if (opts.preprocess or opts.parse) { // The front end: everything except the development modes that work on
// containers or raw tokens.
if (!opts.empty) {
const input = opts.input orelse return cli.fail("no input file", .{}); const input = opts.input orelse return cli.fail("no input file", .{});
var disk: front.source.DiskFs = .{ .io = cli.io }; var disk: front.source.DiskFs = .{ .io = cli.io };
var sm = front.source.SourceManager.init(arena, disk.fileSystem()); var sm = front.source.SourceManager.init(arena, disk.fileSystem());
@ -227,24 +303,111 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
.major = if (profile) |p| p.major else 6, .major = if (profile) |p| p.major else 6,
.minor = if (profile) |p| p.minor else 0, .minor = if (profile) |p| p.minor else 0,
.spirv = opts.spirv, .spirv = opts.spirv,
.spirv_minor = if (zdxc.spirv.emit.TargetEnv.parse(opts.target_env)) |t| t.minor else 0,
.enable_16bit = opts.enable_16bit, .enable_16bit = opts.enable_16bit,
}); });
var out: Io.Writer.Allocating = .init(arena); var out: Io.Writer.Allocating = .init(arena);
var module: ?zdxc.ir.ir.Module = null;
if (try pp.enterMainFile(input)) { if (try pp.enterMainFile(input)) {
if (opts.parse) { if (opts.preprocess) {
try front.pp_print.print(&pp, &out.writer);
} else {
var parser = try front.parser.Parser.fromPreprocessor(arena, &diags, &pp); var parser = try front.parser.Parser.fromPreprocessor(arena, &diags, &pp);
const tu = try parser.parseTranslationUnit(); const tu = try parser.parseTranslationUnit();
if (opts.dump_ast) try front.ast_dump.dumpUnit(stdout, tu); if (opts.dump_ast) try front.ast_dump.dumpUnit(stdout, tu);
} else try front.pp_print.print(&pp, &out.writer); if (!opts.parse) {
const is_lib = if (profile) |p| p.kind == .library else true;
var sema = try zdxc.sema.Sema.init(arena, &diags, .{
.entry = if (opts.sema or is_lib) null else opts.entry,
.spirv = opts.spirv,
.enable_16bit = opts.enable_16bit,
.sm_minor = if (profile) |p| p.minor else 10,
.library = is_lib,
.root = opts.entry,
});
try sema.checkUnit(tu);
if (!opts.sema and !diags.hasErrors() and profile != null) {
const stage: zdxc.ir.ir.Stage = switch (profile.?.kind) {
.vertex => .vertex,
.pixel => .pixel,
.geometry => .geometry,
.hull => .hull,
.domain => .domain,
.compute => .compute,
.mesh => .mesh,
.amplification => .amplification,
else => .library,
};
module = zdxc.ir.lower.lowerUnit(arena, &sema, .{ .entry = opts.entry, .stage = stage }) catch |e| switch (e) {
error.Unsupported => null,
else => |x| return x,
};
if (module) |*mm| {
mm.native_16bit = opts.enable_16bit;
mm.vk = opts.vk;
mm.strip_rootsig = opts.strip_rootsig;
if (opts.rootsig_ver) |rv| {
if (std.mem.eql(u8, rv, "rootsig_1_0")) mm.rootsig_version = .v1_0 else if (!std.mem.eql(u8, rv, "rootsig_1_1")) return cli.fail("unknown root signature version '{s}'", .{rv});
}
}
}
}
}
} }
const color = opts.color orelse (Io.File.stderr().supportsAnsiEscapeCodes(cli.io) catch false); const color = opts.color orelse (Io.File.stderr().supportsAnsiEscapeCodes(cli.io) catch false);
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = color }); try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = color });
try cli.stderr.flush(); try cli.stderr.flush();
if (diags.hasErrors()) return error.CompileFailed; if (diags.hasErrors()) return error.CompileFailed;
if (opts.pp_output) |path| { if (opts.preprocess) {
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = out.written() }); if (opts.pp_output) |path| {
} else try stdout.writeAll(out.written()); try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = out.written() });
return; } else try stdout.writeAll(out.written());
return;
}
if (opts.parse or opts.sema) return;
if (profile == null) return cli.fail("missing -T <profile>", .{});
if (module) |*m| {
try zdxc.ir.opt.run(arena, m);
if (opts.dump_ir) {
try zdxc.ir.ir.dump(m, stdout);
return;
}
if (opts.spirv) {
const bytes = zdxc.spirv.emit.emit(arena, m, &diags, zdxc.spirv.emit.TargetEnv.parse(opts.target_env) orelse return cli.fail("unknown SPIR-V target environment '{s}'", .{opts.target_env})) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = false });
try cli.stderr.flush();
return error.CompileFailed;
},
else => |x| return x,
};
const path = opts.output orelse return cli.fail("missing -Fo <file>", .{});
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = bytes });
return;
}
// -rootsig-define: the macro's root signature for the entry.
if (opts.rootsig_define) |macro| if (m.entries.items.len == 1) {
m.entries.items[0].root_signature = try rootSignatureMacroText(cli, arena, opts, input, macro) orelse return error.CompileFailed;
};
const bytes = zdxc.dxil.emit.emit(arena, m, profile.?, &diags) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = false });
try cli.stderr.flush();
return error.CompileFailed;
},
else => |x| return x,
};
const path = opts.output orelse return cli.fail("missing -Fo <file>", .{});
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = bytes });
if (opts.rootsig_output) |rs_path| {
const text = (if (m.entries.items.len == 1) m.entries.items[0].root_signature else null) orelse return cli.fail("-Frs: the shader has no root signature", .{});
var d: zdxc.dxil.rootsig.Diagnostic = .{};
const blob = try zdxc.dxil.rootsig.compileWithOptions(arena, text, .{ .version = if (m.rootsig_version == .v1_0) .v1_0 else .v1_1, .flags = .global }, &d) orelse return cli.fail("root signature error - {s}", .{d.message()});
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = rs_path, .data = try rootSignatureContainer(arena, blob) });
}
return;
}
return cli.fail("code generation is not implemented yet: the input was checked but no output was written (use -zdxc-empty for a placeholder shader)", .{});
} }
const prof = profile orelse return cli.fail("missing -T <profile>", .{}); const prof = profile orelse return cli.fail("missing -T <profile>", .{});
@ -259,3 +422,59 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
const out = opts.output orelse return cli.fail("missing -Fo <file>", .{}); const out = opts.output orelse return cli.fail("missing -Fo <file>", .{});
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = out, .data = bytes }); try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = out, .data = bytes });
} }
/// The text of the root signature macro `macro` defines in `input` (its
/// string literals concatenated), or null after reporting an error.
fn rootSignatureMacroText(cli: Cli, arena: std.mem.Allocator, opts: Options, input: []const u8, macro: []const u8) !?[]const u8 {
const text = try Io.Dir.cwd().readFileAlloc(cli.io, input, arena, .limited(256 << 20));
var disk: front.source.DiskFs = .{ .io = cli.io };
var sm = front.source.SourceManager.init(arena, disk.fileSystem());
var diags = zdxc.Diagnostics.init(arena);
var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{
.defines = opts.defines.items,
.include_dirs = opts.include_dirs.items,
.stage = 6,
});
// Expand the macro after a marker at the end of the file.
const marker = "__zdxc_root_signature__";
try pp.enterMainText(input, try std.mem.concat(arena, u8, &.{ text, "\n" ++ marker ++ " ", macro, "\n" }));
var parts: std.ArrayList(u8) = .empty;
var seen = false;
var any = false;
while (true) {
const t = try pp.next();
if (t.kind == .eof) break;
if (!seen) {
seen = t.kind == .identifier and std.mem.eql(u8, t.text, marker);
continue;
}
if (t.kind != .string) {
_ = diags.report(.{ .severity = .@"error", .loc = t.loc }, "root signature macro '{s}' must expand to string literals", .{macro});
break;
}
any = true;
try parts.appendSlice(arena, try zdxc.ir.lower.stringContents(arena, t.text));
}
if (!any and !diags.hasErrors()) _ = diags.report(.{ .severity = .@"error", .loc = .none }, "root signature macro '{s}' is not defined", .{macro});
if (diags.hasErrors()) {
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = false });
try cli.stderr.flush();
return null;
}
return parts.items;
}
fn compileRootSignatureMacro(cli: Cli, arena: std.mem.Allocator, opts: Options, input: []const u8, macro: []const u8, version: zdxc.dxil.rootsig.Version, flags: zdxc.dxil.rootsig.CompilationFlags) !?[]const u8 {
const text = try rootSignatureMacroText(cli, arena, opts, input, macro) orelse return null;
var d: zdxc.dxil.rootsig.Diagnostic = .{};
return try zdxc.dxil.rootsig.compileWithOptions(arena, text, .{ .version = version, .flags = flags }, &d) orelse {
try cli.stderr.print("{s}: error: root signature error - {s}\n", .{ input, d.message() });
try cli.stderr.flush();
return null;
};
}
/// A container holding only the root signature (RTS0) part.
fn rootSignatureContainer(arena: std.mem.Allocator, blob: []const u8) ![]u8 {
return zdxc.dxil.container.assemble(arena, &.{.{ .fourcc = zdxc.dxil.container.fourcc("RTS0"), .data = blob }});
}

View File

@ -27,6 +27,8 @@ pub const Extra = enum {
zdxc_lex, zdxc_lex,
zdxc_parse, zdxc_parse,
zdxc_ast, zdxc_ast,
zdxc_sema,
zdxc_ir,
fcolor_diagnostics, fcolor_diagnostics,
fno_color_diagnostics, fno_color_diagnostics,
}; };
@ -37,6 +39,8 @@ const extra_options = [_]struct { id: Extra, spelling: []const u8, help: []const
.{ .id = .zdxc_lex, .spelling = "zdxc-lex", .help = "Print the input's tokens, one per line (development)" }, .{ .id = .zdxc_lex, .spelling = "zdxc-lex", .help = "Print the input's tokens, one per line (development)" },
.{ .id = .zdxc_parse, .spelling = "zdxc-parse", .help = "Preprocess and parse the input, reporting syntax errors only (development)" }, .{ .id = .zdxc_parse, .spelling = "zdxc-parse", .help = "Preprocess and parse the input, reporting syntax errors only (development)" },
.{ .id = .zdxc_ast, .spelling = "zdxc-ast", .help = "Preprocess, parse and dump the syntax tree (development)" }, .{ .id = .zdxc_ast, .spelling = "zdxc-ast", .help = "Preprocess, parse and dump the syntax tree (development)" },
.{ .id = .zdxc_sema, .spelling = "zdxc-sema", .help = "Run the front end through semantic analysis only (development)" },
.{ .id = .zdxc_ir, .spelling = "zdxc-ir", .help = "Print the lowered IR instead of compiling (development)" },
.{ .id = .fcolor_diagnostics, .spelling = "fcolor-diagnostics", .help = "Always use colors in diagnostics" }, .{ .id = .fcolor_diagnostics, .spelling = "fcolor-diagnostics", .help = "Always use colors in diagnostics" },
.{ .id = .fno_color_diagnostics, .spelling = "fno-color-diagnostics", .help = "Never use colors in diagnostics" }, .{ .id = .fno_color_diagnostics, .spelling = "fno-color-diagnostics", .help = "Never use colors in diagnostics" },
}; };
@ -217,7 +221,11 @@ const not_yet = "not supported by zdxc yet";
pub fn support(id: Id) Support { pub fn support(id: Id) Support {
return switch (id) { return switch (id) {
// Core compilation. // Core compilation.
.target_profile, .entrypoint, .Fo, .D, .I, .P, .Fi, .hlsl_version, .spirv, .enable_16bit_types => .implemented, .target_profile, .entrypoint, .Fo, .D, .I, .P, .Fi, .hlsl_version, .spirv, .enable_16bit_types, .fspv_target_env_EQ => .implemented,
.Frs, .Qstrip_rootsignature, .force_rootsig_ver, .force_rootsig_ver_, .rootsig_define => .implemented,
.auto_binding_space, .fvk_b_shift, .fvk_t_shift, .fvk_s_shift, .fvk_u_shift, .fvk_bind_globals, .fvk_bind_register, .vkbr, .fvk_auto_shift_bindings, .fvk_stage_io_order_EQ, .fspv_flatten_resource_arrays, .fspv_use_legacy_buffer_matrix_order, .fspv_preserve_interface, .fspv_use_vulkan_memory_model, .fvk_invert_y, .fvk_use_dx_position_w, .fvk_use_gl_layout, .fvk_use_dx_layout, .fvk_use_scalar_layout, .fvk_support_nonzero_base_instance, .fvk_support_nonzero_base_vertex, .fspv_entrypoint_name_EQ, .fspv_enable_maximal_reconvergence, .fspv_use_unknown_image_format, .fspv_extension_EQ, .fspv_reflect => .implemented,
// (Output is the same with or without the unoptimized-IR switch.)
.fcgl => .ignored,
// Diagnostics. // Diagnostics.
._SLASH_WX, .no_warnings, .W_Joined, .Wno_vk_ignored_features, .Wno_vk_emulated_features => .implemented, ._SLASH_WX, .no_warnings, .W_Joined, .Wno_vk_ignored_features, .Wno_vk_emulated_features => .implemented,
.fdiagnostics_format_EQ, .ferror_limit_EQ, .fdiagnostics_color, .fdiagnostics_color_EQ => .implemented, .fdiagnostics_format_EQ, .ferror_limit_EQ, .fdiagnostics_color, .fdiagnostics_color_EQ => .implemented,
@ -229,13 +237,13 @@ pub fn support(id: Id) Support {
.VD, .validator_version => .implemented, .VD, .validator_version => .implemented,
// Accepted for build-script compatibility; no effect yet. // Accepted for build-script compatibility; no effect yet.
.Zpr, .Zpc, .Gis, .Gfa, .Gfp, .Ges, .Gec, .denorm, .all_resources_bound, .all_resources_bound_, .res_may_alias, .res_may_alias_, .pack_optimized, .pack_optimized_, .pack_prefix_stable, .pack_prefix_stable_, .ffinite_math_only, .fno_finite_math_only, .flegacy_macro_expansion, .flegacy_resource_reservation, .no_legacy_cbuf_layout, .not_use_legacy_cbuf_load_, .enable_payload_qualifiers, .disable_payload_qualifiers, .enable_lifetime_markers, .disable_lifetime_markers, .force_zero_store_lifetimes, .ignore_line_directives, .Qunused_arguments, .fdiagnostics_show_option, .fno_diagnostics_show_option, .fdiagnostics_show_category_EQ, ._vi, .verbose, .v, .encoding, .Wall, .Wdeprecated, ._all_warnings, .Fh, .Vn, .Fsh, .Frs, .Fre, .Zss, .Zsb, .Qstrip_reflect, .Qstrip_debug, .Qstrip_priv, .Qstrip_rootsignature, .Qkeep_reflect_in_dxil, .Qstrip_reflect_from_dxil, .force_rootsig_ver, .force_rootsig_ver_, .rootsig_define, .auto_binding_space, .exports, .export_shaders_only, .default_linkage, .fvk_stage_io_order_EQ, .fvk_b_shift, .fvk_t_shift, .fvk_s_shift, .fvk_u_shift, .fvk_bind_globals, .fvk_bind_register, .vkbr, .fvk_invert_y, .fvk_use_dx_position_w, .fvk_support_nonzero_base_instance, .fvk_support_nonzero_base_vertex, .fvk_use_gl_layout, .fvk_use_dx_layout, .fvk_use_scalar_layout, .fspv_use_legacy_buffer_matrix_order, .fspv_reflect, .fspv_extension_EQ, .fspv_target_env_EQ, .fspv_flatten_resource_arrays, .fspv_reduce_load_size, .fspv_fix_func_call_arguments, .fspv_entrypoint_name_EQ, .fspv_enable_maximal_reconvergence, .fspv_use_vulkan_memory_model, .fspv_use_unknown_image_format, .fvk_auto_shift_bindings, .fspv_preserve_bindings, .fspv_preserve_interface, .Oconfig => .ignored, .Zpr, .Zpc, .Gis, .Gfa, .Gfp, .Ges, .Gec, .denorm, .all_resources_bound, .all_resources_bound_, .res_may_alias, .res_may_alias_, .pack_optimized, .pack_optimized_, .pack_prefix_stable, .pack_prefix_stable_, .ffinite_math_only, .fno_finite_math_only, .flegacy_macro_expansion, .flegacy_resource_reservation, .no_legacy_cbuf_layout, .not_use_legacy_cbuf_load_, .enable_payload_qualifiers, .disable_payload_qualifiers, .enable_lifetime_markers, .disable_lifetime_markers, .force_zero_store_lifetimes, .ignore_line_directives, .Qunused_arguments, .fdiagnostics_show_option, .fno_diagnostics_show_option, .fdiagnostics_show_category_EQ, ._vi, .verbose, .v, .encoding, .Wall, .Wdeprecated, ._all_warnings, .Fh, .Vn, .Fsh, .Fre, .Zss, .Zsb, .Qstrip_reflect, .Qstrip_debug, .Qstrip_priv, .Qkeep_reflect_in_dxil, .Qstrip_reflect_from_dxil, .exports, .export_shaders_only, .default_linkage, .fspv_reduce_load_size, .fspv_fix_func_call_arguments, .fspv_preserve_bindings, .Oconfig => .ignored,
// Dropped by design (see the zdxc plan). // Dropped by design (see the zdxc plan).
._SLASH_Zi, .Zs, .Fd, .Qembed_debug, .Qsource_in_debug_module, .Qpdb_in_private, .fspv_debug_EQ => .{ .unsupported = dropped_debug }, ._SLASH_Zi, .Zs, .Fd, .Qembed_debug, .Qsource_in_debug_module, .Qpdb_in_private, .fspv_debug_EQ => .{ .unsupported = dropped_debug },
.Fc, .Cc, .Ni, .No, .Lx, .dumpbin => .{ .unsupported = dropped_disasm }, .Fc, .Cc, .Ni, .No, .Lx, .dumpbin => .{ .unsupported = dropped_disasm },
.recompile, .link, .ast_dump, .verify, .metal, .external_lib, .external_fn, .setprivate, .getprivate, .setrootsignature, .extractrootsignature, .verifyrootsignature, .rw_unchanged, .rw_skip_function_body, .rw_skip_static, .rw_global_extern_by_default, .rw_keep_user_macro, .rw_extract_entry_uniforms, .rw_remove_unused_globals, .rw_remove_unused_functions, .rw_line_directive, .rw_decl_global_cb, .import_binding_table, .binding_table_define, .ftime_report, .ftime_trace, .ftime_trace_EQ, .ftime_trace_granularity_EQ => .{ .unsupported = dropped_tooling }, .recompile, .link, .ast_dump, .verify, .metal, .external_lib, .external_fn, .setprivate, .getprivate, .setrootsignature, .extractrootsignature, .verifyrootsignature, .rw_unchanged, .rw_skip_function_body, .rw_skip_static, .rw_global_extern_by_default, .rw_keep_user_macro, .rw_extract_entry_uniforms, .rw_remove_unused_globals, .rw_remove_unused_functions, .rw_line_directive, .rw_decl_global_cb, .import_binding_table, .binding_table_define, .ftime_report, .ftime_trace, .ftime_trace_EQ, .ftime_trace_granularity_EQ => .{ .unsupported = dropped_tooling },
.Odump, .fcgl, .print_before_all, .print_before, .print_after_all, .print_after, .opt_disable, .opt_enable, .opt_select, .memdep_block_scan_limit, .fdisable_loc_tracking, .fnew_inlining_behavior, .preserve_intermediate_values, .skip_serialization, .d_Flag, .d_Joined, .ignore_opt_semdefs, .ignore_semdef, .override_semdef, .precise_output, .disable_exception_handling, .fspv_print_all, .fspv_max_id => .{ .unsupported = dropped_internal }, .Odump, .print_before_all, .print_before, .print_after_all, .print_after, .opt_disable, .opt_enable, .opt_select, .memdep_block_scan_limit, .fdisable_loc_tracking, .fnew_inlining_behavior, .preserve_intermediate_values, .skip_serialization, .d_Flag, .d_Joined, .ignore_opt_semdefs, .ignore_semdef, .override_semdef, .precise_output, .disable_exception_handling, .fspv_print_all, .fspv_max_id => .{ .unsupported = dropped_internal },
else => .{ .unsupported = not_yet }, else => .{ .unsupported = not_yet },
}; };

View File

@ -13,6 +13,7 @@ pub const front = struct {
pub const ast = @import("front/ast.zig"); pub const ast = @import("front/ast.zig");
pub const parser = @import("front/parser.zig"); pub const parser = @import("front/parser.zig");
pub const ast_dump = @import("front/ast_dump.zig"); pub const ast_dump = @import("front/ast_dump.zig");
pub const ast_clone = @import("front/ast_clone.zig");
}; };
pub const dxil = struct { pub const dxil = struct {
@ -21,10 +22,28 @@ pub const dxil = struct {
pub const hash = @import("dxil/hash.zig"); pub const hash = @import("dxil/hash.zig");
pub const module = @import("dxil/module.zig"); pub const module = @import("dxil/module.zig");
pub const shader = @import("dxil/shader.zig"); pub const shader = @import("dxil/shader.zig");
pub const signature = @import("dxil/signature.zig");
pub const emit = @import("dxil/emit.zig");
pub const rootsig = @import("dxil/rootsig.zig");
};
pub const ir = struct {
pub const ir = @import("ir/ir.zig");
pub const lower = @import("ir/lower.zig");
pub const layout = @import("ir/layout.zig");
pub const texture = @import("ir/texture.zig");
pub const opt = @import("ir/opt.zig");
};
pub const sema = struct {
pub const types = @import("sema/types.zig");
pub const intrinsics = @import("sema/intrinsics.zig");
pub const Sema = @import("sema/sema.zig").Sema;
}; };
pub const spirv = struct { pub const spirv = struct {
pub const builder = @import("spirv/builder.zig"); pub const builder = @import("spirv/builder.zig");
pub const emit = @import("spirv/emit.zig");
}; };
pub const version = "0.0.0"; pub const version = "0.0.0";
@ -33,6 +52,9 @@ test {
const std = @import("std"); const std = @import("std");
std.testing.refAllDecls(front); std.testing.refAllDecls(front);
std.testing.refAllDecls(dxil); std.testing.refAllDecls(dxil);
std.testing.refAllDecls(ir);
_ = @import("sema/types.zig");
_ = @import("sema/sema.zig");
std.testing.refAllDecls(spirv); std.testing.refAllDecls(spirv);
_ = @import("diag.zig"); _ = @import("diag.zig");
_ = @import("options.zig"); _ = @import("options.zig");

393
src/sema/intrinsics.zig Normal file
View File

@ -0,0 +1,393 @@
//! Intrinsic and builtin-method overload resolution against the table
//! generated from dxc's gen_intrin_main.txt.
//!
//! Each declaration's types are indexed 0 (return) .. n (parameters).
//! `$match<L, C>` links a type's layout to type L and its component to
//! type C (`$typeN` = `$match<N, N>`); unlinked types are their own group.
//! For each group the component is the common type of its arguments,
//! 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.
const std = @import("std");
const Allocator = std.mem.Allocator;
const table = @import("intrinsics_table");
const types = @import("types.zig");
const source = @import("../front/source.zig");
const TypeId = types.TypeId;
const TypeTable = types.TypeTable;
const Scalar = types.Scalar;
pub const ArgInfo = struct {
ty: TypeId,
/// Assignable (for out / inout parameters).
lvalue: bool,
loc: source.Loc,
/// Names (part of) a groupshared variable.
groupshared: bool = false,
};
pub const Db = struct {
/// "Namespace::name" -> indices into table.intrinsics.
by_name: std.StringHashMapUnmanaged(std.ArrayList(u16)) = .empty,
/// Plain intrinsic names (Intrinsics / VkIntrinsics / DxIntrinsics).
globals: std.StringHashMapUnmanaged(void) = .empty,
vk_globals: std.StringHashMapUnmanaged(void) = .empty,
pub fn init(a: Allocator) !Db {
var db: Db = .{};
for (table.intrinsics, 0..) |it, i| {
const key = try std.fmt.allocPrint(a, "{s}::{s}", .{ it.namespace, it.name });
const gop = try db.by_name.getOrPut(a, key);
if (!gop.found_existing) gop.value_ptr.* = .empty;
try gop.value_ptr.append(a, @intCast(i));
if (std.mem.eql(u8, it.namespace, "Intrinsics") or std.mem.eql(u8, it.namespace, "DxIntrinsics")) try db.globals.put(a, it.name, {});
if (std.mem.eql(u8, it.namespace, "VkIntrinsics")) try db.vk_globals.put(a, it.name, {});
}
return db;
}
/// `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;
const key = std.fmt.bufPrint(&buf, "{s}::{s}", .{ ns, name }) catch return true;
return db.by_name.contains(key);
}
pub fn has(db: *const Db, name: []const u8, spirv: bool) bool {
return db.globals.contains(name) or (spirv and db.vk_globals.contains(name));
}
fn candidates(db: *const Db, a: Allocator, ns: []const u8, name: []const u8) ![]const u16 {
var list: std.ArrayList(u16) = .empty;
const namespaces: []const []const u8 = if (std.mem.eql(u8, ns, "Intrinsics")) &.{ "Intrinsics", "DxIntrinsics" } else &.{ns};
for (namespaces) |n| {
const key = try std.fmt.allocPrint(a, "{s}::{s}", .{ n, name });
if (db.by_name.get(key)) |l| try list.appendSlice(a, l.items);
}
return list.items;
}
/// 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.
/// A resolved intrinsic call: the table entry and its concrete
/// parameter types (the argument's type where the table leaves a
/// parameter unconstrained).
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 {
const cands = try db.candidates(sema.arena, ns, name);
if (cands.len == 0) {
if (object) |o| {
sema.err(loc, "no member named '{s}' in '{s}'", .{ name, sema.typeName(o) });
} else sema.err(loc, "use of undeclared identifier '{s}'", .{name});
return .{ .ret = TypeTable.error_type };
}
var best: ?Match = null;
for (cands) |ci| {
var m = try matchOne(sema, &table.intrinsics[ci], object, args, explicit) orelse continue;
m.index = ci;
if (best == null or m.cost < best.?.cost) best = m;
}
// vk::static_pointer_cast / reinterpret_pointer_cast return a
// BufferPointer of the template argument: not modelled yet.
if (best != null and (std.mem.eql(u8, name, "static_pointer_cast") or std.mem.eql(u8, name, "reinterpret_pointer_cast"))) return .{ .ret = TypeTable.error_type };
const m = best orelse {
sema.err(loc, "no matching function for call to '{s}'", .{name});
return .{ .ret = TypeTable.error_type };
};
for (args, 0..) |a, i| {
if (i < m.out_params.len and m.out_params[i] and !a.lvalue) {
sema.err(a.loc, "cannot bind non-lvalue argument to out parameter", .{});
}
}
return .{ .ret = m.ret, .index = m.index, .params = m.params, .ok = true };
}
};
const Match = struct {
ret: TypeId,
cost: u32,
out_params: []const bool,
index: u16 = 0,
params: []const TypeId = &.{},
};
const Layout = struct { rows: u8, cols: u8, kind: TypeTable.Shape };
/// Symbolic dimension bindings (`r`, `c`, `r2`, `c2`, ...).
const Bindings = struct {
names: [8][]const u8 = undefined,
values: [8]u8 = undefined,
n: usize = 0,
/// The widest shape of the arguments declared `<>`: all such types of
/// an intrinsic share their dimensions (dxc's r / c), scalars
/// splatting to the widest.
any_shape: ?TypeTable.Shape = null,
fn get(b: *const Bindings, name: []const u8) ?u8 {
for (b.names[0..b.n], b.values[0..b.n]) |k, v| if (std.mem.eql(u8, k, name)) return v;
return null;
}
/// Bind or check; false on conflict.
fn bind(b: *Bindings, name: []const u8, v: u8) bool {
if (b.get(name)) |old| return old == v;
if (b.n == b.names.len) return false;
b.names[b.n] = name;
b.values[b.n] = v;
b.n += 1;
return true;
}
};
fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) !?Match {
const t = &sema.types;
if (args.len < it.params.len) return null;
if (args.len > it.params.len and !it.varargs) return null;
const n = it.params.len + 1;
const specs = try sema.arena.alloc(*const table.Spec, n);
specs[0] = &it.ret;
for (it.params, 1..) |*p, i| specs[i] = p;
const obj_elem: TypeId = if (object) |o| switch (t.get(o)) {
.resource => |r| r.elem,
.stream => |s| s.elem,
.patch => |p| p.elem,
else => TypeTable.error_type,
} else TypeTable.error_type;
// Groups: index of the type that owns a type's layout / component.
const comp_group = try sema.arena.alloc(usize, n);
const layout_group = try sema.arena.alloc(usize, n);
for (specs, 0..) |s, i| {
comp_group[i] = i;
layout_group[i] = i;
if (s.special == .type_n) {
comp_group[i] = s.type_n;
layout_group[i] = s.type_n;
} else {
if (s.match_comp) |c| if (c >= 0 and c < n) {
comp_group[i] = @intCast(c);
};
if (s.match_layout) |l| if (l >= 0 and l < n) {
layout_group[i] = @intCast(l);
};
}
}
// Components: common type of the arguments in each group.
const group_comp = try sema.arena.alloc(?Scalar, n);
@memset(group_comp, null);
for (args[0..it.params.len], 1..) |a, i| {
const g = comp_group[i];
const c = t.component(a.ty) orelse continue;
group_comp[g] = if (group_comp[g]) |old| common(old, c) else c;
}
var bindings: Bindings = .{};
for (args[0..it.params.len], 1..) |a, i| {
if (!specs[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;
const out_params = try sema.arena.alloc(bool, args.len);
@memset(out_params, false);
const param_types = try sema.arena.alloc(TypeId, args.len);
// Parameter types, checked against the arguments.
for (args, 0..) |a, ai| {
if (ai >= it.params.len) break; // varargs: anything goes
const i = ai + 1;
const s = specs[i];
out_params[ai] = s.qual == .out or s.qual == .inout or s.qual == .ref;
const pt = try paramType(sema, specs, i, comp_group, layout_group, group_comp, &bindings, args, obj_elem, explicit) orelse return null;
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;
}
// 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 };
}
/// The concrete type of spec `i`, or null if the arguments cannot fit.
/// Returns the error type for types zdxc does not constrain (objects,
/// strings, classes it does not model).
fn paramType(
sema: anytype,
specs: []const *const table.Spec,
i: usize,
comp_group: []const usize,
layout_group: []const usize,
group_comp: []const ?Scalar,
bindings: *Bindings,
args: []const ArgInfo,
obj_elem: TypeId,
explicit: ?TypeId,
) !?TypeId {
const t = &sema.types;
const s = specs[i];
switch (s.special) {
.class_t => return obj_elem,
// `$funcT`: the explicit template argument; without one, a return
// defaults to uint (ByteAddressBuffer.Load) and a parameter is
// unconstrained (Store of a struct).
.func_t => return explicit orelse if (i == 0) try t.scalar(.uint) else TypeTable.error_type,
else => {},
}
// Owner specs define the class and layout of linked types. `$match`
// links the layout's kind; explicit dimensions on the spec itself win
// (`$match<2, 2> float<2> ddx`, transpose's `any<c, r>`).
const cs = specs[comp_group[i]];
const ls = if (s.dims.len > 0) s else specs[layout_group[i]];
// Non-numeric classes.
const base = if (cs.special == .none) cs.base else s.base;
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.
if (i > 0 and i - 1 < args.len and isObjectClass(base)) return objectCheck(sema, base, args[i - 1].ty);
return TypeTable.error_type;
}
if (isObjectClass(base)) {
if (i > 0 and i - 1 < args.len) return objectCheck(sema, base, args[i - 1].ty);
return TypeTable.error_type;
}
if (std.mem.eql(u8, base, "void")) {
// `$match<0, -1> void<4>`: the object's component type.
if (s.match_comp != null and s.match_comp.? == -1 and obj_elem != TypeTable.error_type) {
const comp = t.component(obj_elem) orelse return TypeTable.error_type;
return try layoutType(sema, ls, comp, layout_group[i], bindings, args);
}
if (s.match_layout != null and s.match_layout.? == -1) return obj_elem;
return TypeTable.void_type;
}
var comp = classComponent(base, group_comp[comp_group[i]]) orelse return null;
if (comp.isLiteral()) comp = comp.concrete();
return try layoutType(sema, ls, comp, layout_group[i], bindings, args);
}
fn layoutType(sema: anytype, ls: *const table.Spec, comp: Scalar, group: usize, bindings: *Bindings, args: []const ArgInfo) !?TypeId {
const t = &sema.types;
if (ls.any_layout) {
// `<>`: the shape of the group's arguments (scalars splat to the
// widest one).
var shape: ?TypeTable.Shape = null;
if (group > 0 and group - 1 < args.len) shape = t.shape(args[group - 1].ty);
// A scalar (or no argument of its own) takes the shared shape.
if (shape == null or shape.?.count() == 1) shape = bindings.any_shape orelse shape;
if (shape == null) return try t.scalar(comp);
return try t.withShape(comp, shape.?);
}
if (ls.dims.len == 0) return try t.scalar(comp);
const arg_shape: ?TypeTable.Shape = if (group > 0 and group - 1 < args.len) t.shape(args[group - 1].ty) else null;
if (ls.dims.len == 1) {
const len = dimValue(ls.dims[0], bindings, if (arg_shape) |sh| (if (sh.kind == .vector) sh.cols else if (sh.kind == .scalar) 1 else sh.cols) else null) orelse return null;
if (len < 1 or len > 4) return null;
return try t.vector(comp, len);
}
const rows = dimValue(ls.dims[0], bindings, if (arg_shape) |sh| sh.rows else null) orelse return null;
const cols = dimValue(ls.dims[1], bindings, if (arg_shape) |sh| sh.cols else null) orelse return null;
if (rows < 1 or rows > 4 or cols < 1 or cols > 4) return null;
return try t.matrix(comp, rows, cols);
}
/// A layout dimension: a number, or a symbol bound from the argument.
fn dimValue(dim: []const u8, b: *Bindings, from_arg: ?u8) ?u8 {
if (std.fmt.parseInt(u8, dim, 10)) |v| return v else |_| {}
if (b.get(dim)) |v| return v;
const v = from_arg orelse return null;
if (!b.bind(dim, v)) return null;
return v;
}
fn common(a: Scalar, b: Scalar) Scalar {
return Scalar.combine(a, b);
}
/// The component a class gives for argument component `c` (null: no
/// argument decided it). Concrete classes ignore the arguments.
fn classComponent(base: []const u8, c: ?Scalar) ?Scalar {
const fixed = [_]struct { []const u8, Scalar }{
.{ "bool", .bool }, .{ "int", .int }, .{ "uint", .uint }, .{ "float", .float },
.{ "double", .double }, .{ "u64", .uint64 }, .{ "i64", .int64 }, .{ "int16_t", .int16 },
.{ "uint16_t", .uint16 }, .{ "float16_t", .float16 }, .{ "half", .half }, .{ "int64_t", .int64 },
.{ "uint64_t", .uint64 }, .{ "uint_only", .uint }, .{ "int32_only", .int }, .{ "int64_only", .int64 },
.{ "any_int32", .int }, .{ "any_int64", .int64 }, .{ "uint_only32", .uint }, .{ "p32i8", .uint },
.{ "p32u8", .uint }, .{ "int8_t4_packed", .int8_4packed }, .{ "uint8_t4_packed", .uint8_4packed },
};
for (fixed) |f| {
if (std.mem.eql(u8, f[0], base)) {
// Classes that only fix the width keep the argument's type
// when it fits (int32_only accepts int and uint).
if (c) |arg| {
if (std.mem.eql(u8, base, "int32_only") or std.mem.eql(u8, base, "any_int32") or std.mem.eql(u8, base, "uint_only")) {
if (arg.isInt() and arg.size() == 4) return arg.concrete();
}
if (std.mem.eql(u8, base, "int64_only") or std.mem.eql(u8, base, "any_int64")) {
if (arg.isInt() and arg.size() == 8) return arg;
}
}
return f[1];
}
}
const arg = c orelse return switch (base.len) {
else => if (std.mem.eql(u8, base, "float_like") or std.mem.eql(u8, base, "any_float")) Scalar.float else Scalar.int,
};
if (std.mem.eql(u8, base, "float_like") or std.mem.eql(u8, base, "any_float") or std.mem.eql(u8, base, "float32_only") or std.mem.eql(u8, base, "fldbl") or std.mem.eql(u8, base, "float_like16")) {
return if (arg.isFloat()) arg.concrete() else .float;
}
if (std.mem.eql(u8, base, "any_int") or std.mem.eql(u8, base, "any_int16or32") or std.mem.eql(u8, base, "sint16or32_only") or std.mem.eql(u8, base, "int16_only")) {
return if (arg.isInt()) arg.concrete() else .int;
}
if (std.mem.eql(u8, base, "numeric32_only")) return if (arg.size() == 4 and arg != .bool) arg.concrete() else if (arg.isFloat()) .float else .int;
if (std.mem.eql(u8, base, "numeric16_only")) return if (arg.size() == 2) arg else .int16;
if (std.mem.eql(u8, base, "numeric")) return if (arg == .bool) .int else arg.concrete();
// any, any_sampler... and unmodelled classes: keep the argument's type.
return arg.concrete();
}
/// Component classes that denote numeric types.
fn isNumericClass(base: []const u8) bool {
const names = [_][]const u8{
"bool", "int", "uint", "float", "double", "u64", "i64",
"int16_t", "uint16_t", "float16_t", "half", "int64_t", "uint64_t", "uint_only",
"int32_only", "int64_only", "any_int32", "any_int64", "uint_only32", "p32i8", "p32u8",
"int8_t4_packed", "uint8_t4_packed", "float_like", "any_float", "float32_only", "fldbl", "float_like16",
"any_int", "any_int16or32", "sint16or32_only", "int16_only", "numeric32_only", "numeric16_only", "numeric",
"any", "float16_t_only", "float32_t_only", "int16_t_only", "uint16_t_only",
};
for (names) |k| if (std.mem.eql(u8, k, base)) return true;
return false;
}
fn isObjectClass(base: []const u8) bool {
const names = [_][]const u8{
"sampler", "sampler_cmp", "any_sampler", "sampler1d", "sampler2d", "sampler3d", "sampler_cube", "string", "wave",
"ray_desc", "acceleration_struct", "udt", "resource", "LinAlg", "LinAlgMatrix", "node_record_or_uav", "any_node_output_record", "Texture1D",
"Texture2D", "Texture2DArray", "Texture3D", "TextureCube",
};
for (names) |k| if (std.mem.eql(u8, k, base)) return true;
return false;
}
/// Object parameters: check samplers; anything else is accepted.
fn objectCheck(sema: anytype, base: []const u8, arg: TypeId) ?TypeId {
const t = &sema.types;
const ty = t.get(arg);
if (std.mem.eql(u8, base, "sampler") or std.mem.eql(u8, base, "sampler_cmp") or std.mem.eql(u8, base, "any_sampler")) {
if (ty != .sampler) return if (ty == .@"error") TypeTable.error_type else null;
if (std.mem.eql(u8, base, "sampler_cmp") and !ty.sampler.comparison) return null;
if (std.mem.eql(u8, base, "sampler") and ty.sampler.comparison) return null;
return TypeTable.error_type;
}
return TypeTable.error_type;
}

4273
src/sema/sema.zig Normal file

File diff suppressed because it is too large Load Diff

731
src/sema/types.zig Normal file
View File

@ -0,0 +1,731 @@
//! HLSL types, interned in a TypeTable so that type identity is an integer
//! comparison.
const std = @import("std");
const Allocator = std.mem.Allocator;
pub const TypeId = u32;
/// Scalar (component) types. `literal_*` are the types of unsuffixed
/// literals, which adapt to the other operand as in dxc.
pub const Scalar = enum(u8) {
bool,
int,
uint,
half,
float,
double,
min16float,
min10float,
min16int,
min12int,
min16uint,
int16,
uint16,
int64,
uint64,
float16,
literal_int,
literal_float,
int8_4packed,
uint8_4packed,
pub fn isFloat(s: Scalar) bool {
return switch (s) {
.half, .float, .double, .min16float, .min10float, .float16, .literal_float => true,
else => false,
};
}
pub fn isInt(s: Scalar) bool {
return switch (s) {
.int, .uint, .min16int, .min12int, .min16uint, .int16, .uint16, .int64, .uint64, .literal_int, .int8_4packed, .uint8_4packed => true,
else => false,
};
}
pub fn isUnsigned(s: Scalar) bool {
return switch (s) {
.uint, .min16uint, .uint16, .uint64, .uint8_4packed => true,
else => false,
};
}
/// dxc's BPROP_INTEGER: integers, bool and integer literals.
pub fn isIntegral(s: Scalar) bool {
return s == .bool or s.isInt();
}
pub fn isLiteral(s: Scalar) bool {
return s == .literal_int or s == .literal_float;
}
const Props = packed struct(u16) {
boolean: bool = false,
literal: bool = false,
floating: bool = false,
integer: bool = false,
unsigned: bool = false,
min_precision: bool = false,
/// `half` without -enable-16bit-types (32-bit, partial precision).
partial_precision: bool = false,
_: u9 = 0,
};
/// dxc's basic-kind properties (g_uBasicKindProps in SemaHLSL.cpp):
/// bit width (0 for bool and literals) and flags.
fn props(s: Scalar) struct { bits: u8, p: Props } {
return switch (s) {
.bool => .{ .bits = 0, .p = .{ .boolean = true, .integer = true } },
.literal_float => .{ .bits = 0, .p = .{ .floating = true, .literal = true } },
.literal_int => .{ .bits = 0, .p = .{ .integer = true, .literal = true } },
.float16 => .{ .bits = 16, .p = .{ .floating = true } },
.half => .{ .bits = 32, .p = .{ .floating = true, .partial_precision = true } },
.float => .{ .bits = 32, .p = .{ .floating = true } },
.double => .{ .bits = 64, .p = .{ .floating = true } },
.int16 => .{ .bits = 16, .p = .{ .integer = true } },
.uint16 => .{ .bits = 16, .p = .{ .integer = true, .unsigned = true } },
.int => .{ .bits = 32, .p = .{ .integer = true } },
.uint, .int8_4packed, .uint8_4packed => .{ .bits = 32, .p = .{ .integer = true, .unsigned = true } },
.int64 => .{ .bits = 64, .p = .{ .integer = true } },
.uint64 => .{ .bits = 64, .p = .{ .integer = true, .unsigned = true } },
.min10float => .{ .bits = 10, .p = .{ .floating = true, .min_precision = true } },
.min16float => .{ .bits = 16, .p = .{ .floating = true, .min_precision = true } },
.min12int => .{ .bits = 12, .p = .{ .integer = true, .min_precision = true } },
.min16int => .{ .bits = 16, .p = .{ .integer = true, .min_precision = true } },
.min16uint => .{ .bits = 16, .p = .{ .integer = true, .unsigned = true, .min_precision = true } },
};
}
/// 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 {
if (a == b) return a;
const l = a.props();
const r = b.props();
var bits = @max(l.bits, r.bits);
const lb: u16 = @bitCast(l.p);
const rb: u16 = @bitCast(r.p);
const both: Props = @bitCast(lb & rb);
const either: Props = @bitCast(lb | rb);
if (both.boolean) return .bool;
const float_result = either.floating;
if (both.literal) return if (float_result) .literal_float else .literal_int;
var res: Props = .{
.integer = both.integer,
.min_precision = both.min_precision,
.partial_precision = both.partial_precision,
.floating = either.floating,
.unsigned = !float_result and either.unsigned,
};
// A literal or bool operand takes its precision from the other.
if (either.literal or either.boolean) {
res.min_precision = either.min_precision;
res.partial_precision = res.partial_precision or either.partial_precision;
}
if (res.partial_precision) return .half;
// Only one side is floating: the result comes from that side.
if (float_result and !both.floating) {
const f = if (l.p.floating) l else r;
res = f.p;
bits = f.bits;
}
if (bits == 0) bits = 32;
if (float_result) return switch (bits) {
10 => .min10float,
16 => if (res.min_precision) .min16float else .float16,
64 => .double,
else => .float,
};
return switch (bits) {
12 => .min12int,
16 => if (res.unsigned)
(if (res.min_precision) .min16uint else .uint16)
else
(if (res.min_precision) .min16int else .int16),
64 => if (res.unsigned) .uint64 else .int64,
else => if (res.unsigned) .uint else .int,
};
}
/// Rank for the usual arithmetic conversions: higher wins.
pub fn rank(s: Scalar) u8 {
return switch (s) {
.bool => 0,
.literal_int => 1,
.min12int, .min16int => 2,
.min16uint => 3,
.int16 => 4,
.uint16 => 5,
.int, .int8_4packed => 6,
.uint, .uint8_4packed => 7,
.int64 => 8,
.uint64 => 9,
.literal_float => 10,
.min10float, .min16float => 11,
.float16 => 12,
.half => 13,
.float => 14,
.double => 15,
};
}
/// Size in bytes of the component as stored (32-bit unless noted).
pub fn size(s: Scalar) u32 {
return switch (s) {
.double, .int64, .uint64 => 8,
.int16, .uint16, .float16 => 2,
else => 4,
};
}
/// The concrete type a literal becomes when nothing else decides.
pub fn concrete(s: Scalar) Scalar {
return switch (s) {
.literal_int => .int,
.literal_float => .float,
else => s,
};
}
/// HLSL spelling, as dxc prints it.
pub fn name(s: Scalar) []const u8 {
return switch (s) {
.bool => "bool",
.int => "int",
.uint => "uint",
.half => "half",
.float => "float",
.double => "double",
.min16float => "min16float",
.min10float => "min10float",
.min16int => "min16int",
.min12int => "min12int",
.min16uint => "min16uint",
.int16 => "int16_t",
.uint16 => "uint16_t",
.int64 => "int64_t",
.uint64 => "uint64_t",
.float16 => "float16_t",
.literal_int => "literal int",
.literal_float => "literal float",
.int8_4packed => "int8_t4_packed",
.uint8_4packed => "uint8_t4_packed",
};
}
/// Scalar named by an HLSL keyword (`dword`, `float32_t` are aliases).
pub fn fromName(n: []const u8) ?Scalar {
const map = [_]struct { []const u8, Scalar }{
.{ "bool", .bool }, .{ "int", .int }, .{ "uint", .uint },
.{ "dword", .uint }, .{ "half", .half }, .{ "float", .float },
.{ "double", .double }, .{ "min16float", .min16float }, .{ "min10float", .min10float },
.{ "min16int", .min16int }, .{ "min12int", .min12int }, .{ "min16uint", .min16uint },
.{ "int16_t", .int16 }, .{ "uint16_t", .uint16 }, .{ "int32_t", .int },
.{ "uint32_t", .uint }, .{ "int64_t", .int64 }, .{ "uint64_t", .uint64 },
.{ "float16_t", .float16 }, .{ "float32_t", .float }, .{ "float64_t", .double },
.{ "int8_t4_packed", .int8_4packed }, .{ "uint8_t4_packed", .uint8_4packed },
};
for (map) |m| if (std.mem.eql(u8, m[0], n)) return m[1];
return null;
}
};
pub const ResourceKind = enum(u8) {
buffer,
rw_buffer,
byte_address_buffer,
rw_byte_address_buffer,
structured_buffer,
rw_structured_buffer,
append_structured_buffer,
consume_structured_buffer,
texture1d,
texture1d_array,
texture2d,
texture2d_array,
texture2dms,
texture2dms_array,
texture3d,
texture_cube,
texture_cube_array,
rw_texture1d,
rw_texture1d_array,
rw_texture2d,
rw_texture2d_array,
rw_texture2dms,
rw_texture2dms_array,
rw_texture3d,
constant_buffer,
texture_buffer,
raytracing_acceleration_structure,
feedback_texture2d,
feedback_texture2d_array,
/// vk::SampledTexture*: combined image samplers (SPIR-V only).
sampled_texture1d,
sampled_texture1d_array,
sampled_texture2d,
sampled_texture2d_array,
sampled_texture2dms,
sampled_texture2dms_array,
sampled_texture3d,
sampled_texture_cube,
sampled_texture_cube_array,
/// Any other builtin object (RayQuery, node records, vk:: types...):
/// accepted, with methods resolved through the intrinsic table.
other,
pub fn isWritable(k: ResourceKind) bool {
return switch (k) {
.rw_buffer, .rw_byte_address_buffer, .rw_structured_buffer, .append_structured_buffer, .rw_texture1d, .rw_texture1d_array, .rw_texture2d, .rw_texture2d_array, .rw_texture2dms, .rw_texture2dms_array, .rw_texture3d => true,
else => false,
};
}
/// Dimensions of the integer index used by operator[] (0: no indexing).
pub fn indexDims(k: ResourceKind) u8 {
return switch (k) {
.buffer, .rw_buffer, .structured_buffer, .rw_structured_buffer, .texture1d, .rw_texture1d, .sampled_texture1d => 1,
.texture1d_array, .rw_texture1d_array, .texture2d, .rw_texture2d, .texture2dms, .rw_texture2dms, .sampled_texture1d_array, .sampled_texture2d, .sampled_texture2dms => 2,
.texture2d_array, .rw_texture2d_array, .texture2dms_array, .rw_texture2dms_array, .texture3d, .rw_texture3d, .sampled_texture2d_array, .sampled_texture2dms_array, .sampled_texture3d => 3,
else => 0,
};
}
pub const names = [_]struct { []const u8, ResourceKind }{
.{ "Buffer", .buffer }, .{ "RWBuffer", .rw_buffer },
.{ "ByteAddressBuffer", .byte_address_buffer }, .{ "RWByteAddressBuffer", .rw_byte_address_buffer },
.{ "StructuredBuffer", .structured_buffer }, .{ "RWStructuredBuffer", .rw_structured_buffer },
.{ "AppendStructuredBuffer", .append_structured_buffer }, .{ "ConsumeStructuredBuffer", .consume_structured_buffer },
.{ "Texture1D", .texture1d }, .{ "Texture1DArray", .texture1d_array },
.{ "Texture2D", .texture2d }, .{ "Texture2DArray", .texture2d_array },
.{ "Texture2DMS", .texture2dms }, .{ "Texture2DMSArray", .texture2dms_array },
.{ "Texture3D", .texture3d }, .{ "TextureCube", .texture_cube },
.{ "TextureCubeArray", .texture_cube_array }, .{ "RWTexture1D", .rw_texture1d },
.{ "RWTexture1DArray", .rw_texture1d_array }, .{ "RWTexture2D", .rw_texture2d },
.{ "RWTexture2DArray", .rw_texture2d_array }, .{ "RWTexture2DMS", .rw_texture2dms },
.{ "RWTexture2DMSArray", .rw_texture2dms_array }, .{ "RWTexture3D", .rw_texture3d },
.{ "ConstantBuffer", .constant_buffer }, .{ "TextureBuffer", .texture_buffer },
.{ "RaytracingAccelerationStructure", .raytracing_acceleration_structure }, .{ "FeedbackTexture2D", .feedback_texture2d },
.{ "FeedbackTexture2DArray", .feedback_texture2d_array },
// Rasterizer-ordered views behave like their RW counterparts.
.{ "RasterizerOrderedBuffer", .rw_buffer },
.{ "RasterizerOrderedByteAddressBuffer", .rw_byte_address_buffer }, .{ "RasterizerOrderedStructuredBuffer", .rw_structured_buffer },
.{ "RasterizerOrderedTexture1D", .rw_texture1d }, .{ "RasterizerOrderedTexture1DArray", .rw_texture1d_array },
.{ "RasterizerOrderedTexture2D", .rw_texture2d }, .{ "RasterizerOrderedTexture2DArray", .rw_texture2d_array },
.{ "RasterizerOrderedTexture3D", .rw_texture3d },
};
/// vk::SampledTexture* by name.
pub const vk_names = [_]struct { []const u8, ResourceKind }{
.{ "SampledTexture1D", .sampled_texture1d }, .{ "SampledTexture1DArray", .sampled_texture1d_array },
.{ "SampledTexture2D", .sampled_texture2d }, .{ "SampledTexture2DArray", .sampled_texture2d_array },
.{ "SampledTexture2DMS", .sampled_texture2dms }, .{ "SampledTexture2DMSArray", .sampled_texture2dms_array },
.{ "SampledTexture3D", .sampled_texture3d }, .{ "SampledTextureCUBE", .sampled_texture_cube },
.{ "SampledTextureCUBEArray", .sampled_texture_cube_array },
};
pub fn fromName(n: []const u8) ?ResourceKind {
for (names) |m| if (std.mem.eql(u8, m[0], n)) return m[1];
return null;
}
};
pub const Field = struct {
name: []const u8,
type: TypeId,
/// Matrices in the field are row_major (layout only).
row_major: bool = false,
/// The field's semantic (`float4 pos : SV_Position;`).
semantic: ?[]const u8 = null,
/// Interpolation modifiers (for entry-point inputs and outputs).
interp: Interp = .{},
/// Hidden storage for consecutive bitfields (see StructInfo.bitfields).
bits: bool = false,
/// Constant buffer members: `packoffset` / `register(cN)` byte offset.
pack_offset: ?u32 = null,
/// [[vk::location(n)]], [[vk::index(n)]], [[vk::offset(n)]].
vk_location: ?u32 = null,
vk_index: ?u32 = null,
vk_offset: ?u32 = null,
vk_builtin: ?[]const u8 = null,
/// [[vk::ext_decorate(...)]] / [[vk::ext_decorate_string(...)]].
decorations: []const MemberDecoration = &.{},
};
/// A decoration inline SPIR-V puts on a struct member: literal words or
/// strings.
pub const MemberDecoration = struct { decoration: u32, ints: []const u32 = &.{}, strings: []const []const u8 = &.{} };
/// A bitfield member: `width` bits at `offset` in storage field `storage`.
pub const Bitfield = struct {
name: []const u8,
type: TypeId,
storage: u32,
offset: u8,
width: u8,
};
/// Interpolation modifiers written on a parameter, field or function.
pub const Interp = packed struct(u8) {
nointerpolation: bool = false,
linear: bool = false,
centroid: bool = false,
sample: bool = false,
noperspective: bool = false,
_pad: u3 = 0,
};
/// A struct's layout-relevant information. Methods live in Sema.
pub const StructInfo = struct {
name: []const u8,
fields: std.ArrayList(Field) = .empty,
/// Direct base structs (HLSL 2021 single inheritance, in practice).
bases: std.ArrayList(*StructInfo) = .empty,
/// Bitfield members, in declaration order (their storage fields are in
/// `fields`, unnamed).
bitfields: std.ArrayList(Bitfield) = .empty,
/// Opaque pointer to Sema's per-struct data (methods, base).
sema: ?*anyopaque = null,
complete: bool = false,
/// Had errors in its members (sizeof gives 1, as in clang).
invalid: bool = false,
/// Declares operator overloads (milestone 0.2): uses of operators on
/// it are not diagnosed.
has_operators: bool = false,
/// The bitfields stored in field `storage` (consecutive).
pub fn bitfieldsIn(info: *const StructInfo, storage: u32) []const Bitfield {
var lo: usize = 0;
while (lo < info.bitfields.items.len and info.bitfields.items[lo].storage != storage) lo += 1;
var hi = lo;
while (hi < info.bitfields.items.len and info.bitfields.items[hi].storage == storage) hi += 1;
return info.bitfields.items[lo..hi];
}
pub fn overloadsOperators(info: *const StructInfo) bool {
if (info.has_operators) return true;
for (info.bases.items) |b| if (b.overloadsOperators()) return true;
return false;
}
};
/// An operand of a `vk::SpirvType` / `vk::SpirvOpaqueType`: a type, a
/// constant (`vk::integral_constant<T, v>`) or a literal word
/// (`vk::Literal<vk::integral_constant<T, v>>`).
pub const SpirvOperand = union(enum) {
type: TypeId,
constant: struct { ty: TypeId, value: i64 },
literal: i64,
};
/// `vk::SpirvType<opcode, size, alignment, operands...>` (sized) and
/// `vk::SpirvOpaqueType<opcode, operands...>`: a SPIR-V type spelled out.
pub const SpirvTypeInfo = struct {
opcode: u32,
operands: []const SpirvOperand,
/// Zero for opaque types (which cannot be in buffers).
size: u32 = 0,
alignment: u32 = 0,
/// `[[vk::ext_capability]]` / `[[vk::ext_extension]]` on an alias or
/// field of the type: declared wherever it is used (not part of its
/// identity).
capabilities: []const u32 = &.{},
extensions: []const []const u8 = &.{},
};
pub const EnumInfo = struct {
name: []const u8,
underlying: Scalar,
scoped: bool,
};
pub const Type = union(enum) {
void,
/// The type of an ill-formed expression: suppresses follow-on errors.
@"error",
scalar: Scalar,
vector: struct { elem: Scalar, len: u8 },
matrix: struct { elem: Scalar, rows: u8, cols: u8 },
/// `len == 0` means unsized (`float a[]`).
array: struct { elem: TypeId, len: u32 },
@"struct": *StructInfo,
@"enum": *EnumInfo,
/// `elem` is the template argument (or the void type when absent).
/// `flags`: RayQuery's constant ray flags (template arguments).
resource: struct { kind: ResourceKind, elem: TypeId, name: []const u8, flags: u32 = 0, flags2: u32 = 0 },
sampler: struct { comparison: bool },
string,
/// PointStream / LineStream / TriangleStream<T>.
stream: struct { kind: enum { point, line, triangle }, elem: TypeId },
/// InputPatch / OutputPatch<T, N>.
patch: struct { output: bool, elem: TypeId, count: u32 },
/// ResourceDescriptorHeap / SamplerDescriptorHeap (SM 6.6).
descriptor_heap: struct { sampler: bool },
/// `ResourceDescriptorHeap[i]`: converts to any resource / sampler.
dynamic_resource,
/// `tex.mips` / `tex.sample` and their slices (`tex.mips[level]`).
texture_view: struct { texture: TypeId, kind: enum { mips, mips_slice, sample, sample_slice } },
spirv: *const SpirvTypeInfo,
};
/// Interns types. Ids 0 and 1 are `error` and `void`.
pub const TypeTable = struct {
gpa: Allocator,
types: std.ArrayList(Type) = .empty,
map: std.AutoHashMapUnmanaged(Key, TypeId) = .empty,
pub const error_type: TypeId = 0;
pub const void_type: TypeId = 1;
/// Hashable identity of structural types.
const Key = struct { tag: u8, a: u64, b: u64 };
pub fn init(gpa: Allocator) !TypeTable {
var t: TypeTable = .{ .gpa = gpa };
try t.types.append(gpa, .@"error");
try t.types.append(gpa, .void);
return t;
}
pub fn deinit(t: *TypeTable) void {
t.types.deinit(t.gpa);
t.map.deinit(t.gpa);
}
pub fn get(t: *const TypeTable, id: TypeId) Type {
return t.types.items[id];
}
fn keyOf(ty: Type) ?Key {
return switch (ty) {
.void, .@"error" => null,
.scalar => |s| .{ .tag = 1, .a = @backingInt(s), .b = 0 },
.vector => |v| .{ .tag = 2, .a = @backingInt(v.elem), .b = v.len },
.matrix => |m| .{ .tag = 3, .a = @backingInt(m.elem), .b = (@as(u64, m.rows) << 8) | m.cols },
.array => |a| .{ .tag = 4, .a = a.elem, .b = a.len },
.@"struct" => |s| .{ .tag = 5, .a = @intFromPtr(s), .b = 0 },
.@"enum" => |e| .{ .tag = 6, .a = @intFromPtr(e), .b = 0 },
.resource => |r| .{ .tag = 7, .a = (@as(u64, @backingInt(r.kind)) << 32) | r.elem, .b = std.hash.Wyhash.hash(r.flags | (@as(u64, r.flags2) << 32), r.name) },
.sampler => |s| .{ .tag = 8, .a = @intFromBool(s.comparison), .b = 0 },
.string => .{ .tag = 9, .a = 0, .b = 0 },
.stream => |s| .{ .tag = 10, .a = @backingInt(s.kind), .b = s.elem },
.patch => |p| .{ .tag = 11, .a = (@as(u64, @intFromBool(p.output)) << 32) | p.elem, .b = p.count },
.descriptor_heap => |h| .{ .tag = 12, .a = @intFromBool(h.sampler), .b = 0 },
.dynamic_resource => .{ .tag = 13, .a = 0, .b = 0 },
.texture_view => |v| .{ .tag = 14, .a = v.texture, .b = @backingInt(v.kind) },
.spirv => |x| .{ .tag = 15, .a = (@as(u64, x.opcode) << 32) | x.size, .b = std.hash.Wyhash.hash(x.alignment, std.mem.sliceAsBytes(x.operands)) },
};
}
pub fn intern(t: *TypeTable, ty: Type) !TypeId {
const key = keyOf(ty) orelse return if (ty == .void) void_type else error_type;
const gop = try t.map.getOrPut(t.gpa, key);
if (gop.found_existing) return gop.value_ptr.*;
try t.types.append(t.gpa, ty);
gop.value_ptr.* = @intCast(t.types.items.len - 1);
return gop.value_ptr.*;
}
pub fn scalar(t: *TypeTable, s: Scalar) !TypeId {
return t.intern(.{ .scalar = s });
}
/// `len == 1` vectors are kept distinct from scalars (float1 != float).
pub fn vector(t: *TypeTable, s: Scalar, len: u8) !TypeId {
return t.intern(.{ .vector = .{ .elem = s, .len = len } });
}
pub fn matrix(t: *TypeTable, s: Scalar, rows: u8, cols: u8) !TypeId {
return t.intern(.{ .matrix = .{ .elem = s, .rows = rows, .cols = cols } });
}
pub fn array(t: *TypeTable, elem: TypeId, len: u32) !TypeId {
return t.intern(.{ .array = .{ .elem = elem, .len = len } });
}
/// Component type of a numeric (scalar / vector / matrix) type.
pub fn component(t: *const TypeTable, id: TypeId) ?Scalar {
return switch (t.get(id)) {
.scalar => |s| s,
.vector => |v| v.elem,
.matrix => |m| m.elem,
.@"enum" => |e| e.underlying,
else => null,
};
}
pub const Shape = struct {
rows: u8,
cols: u8,
kind: enum { scalar, vector, matrix },
pub fn count(sh: Shape) u32 {
return @as(u32, sh.rows) * sh.cols;
}
};
pub const DimConv = enum { identity, scalar, splat, truncation, conversion };
/// Whether a value of shape `src` converts to shape `target`, and how:
/// a port of dxc's ConvertDimensions (identical for implicit and
/// explicit conversions).
pub fn convertDimensions(target: Shape, src: Shape) ?DimConv {
const tn = target.count();
const sn = src.count();
return switch (target.kind) {
.scalar => switch (src.kind) {
.scalar => .identity,
.vector, .matrix => if (sn > 1) .truncation else .scalar,
},
.vector => switch (src.kind) {
.scalar => .splat,
.vector => if (target.cols > src.cols)
(if (src.cols == 1) .splat else null)
else if (target.cols < src.cols) .truncation else .identity,
.matrix => if (sn == 1 and target.cols != 1)
.splat
else if (src.rows == 1 or src.cols == 1)
(if (target.cols > sn) null else if (target.cols < sn) .truncation else .conversion)
else if (target.cols == 1)
.truncation
else if (target.cols != sn) null else .conversion,
},
.matrix => switch (src.kind) {
.scalar => .splat,
.vector => if (src.cols == 1 and tn != 1)
.splat
else if (tn == src.cols)
.conversion
else if (tn == 1)
.truncation
else if ((target.rows == 1 or target.cols == 1) and tn < src.cols) .truncation else null,
.matrix => if (sn == 1 and tn != 1)
.splat
else if (tn == 1)
.truncation
else if (target.rows > src.rows or target.cols > src.cols)
null
else if (target.rows < src.rows or target.cols < src.cols) .truncation else .identity,
},
};
}
/// The shape of a binary operation's result (dxc's CombineDimensions:
/// prefer the larger operand, or the left on a tie), or null if the
/// shapes do not combine.
pub fn combineDimensions(l: Shape, r: Shape) ?Shape {
if (l.count() >= r.count()) {
if (convertDimensions(l, r) != null) return l;
if (convertDimensions(r, l) != null) return r;
} else {
if (convertDimensions(r, l) != null) return r;
if (convertDimensions(l, r) != null) return l;
}
return null;
}
/// Shape of a numeric type: scalars are 1x1, vectors 1xN.
pub fn shape(t: *const TypeTable, id: TypeId) ?Shape {
return switch (t.get(id)) {
.scalar, .@"enum" => .{ .rows = 1, .cols = 1, .kind = .scalar },
.vector => |v| .{ .rows = 1, .cols = v.len, .kind = .vector },
.matrix => |m| .{ .rows = m.rows, .cols = m.cols, .kind = .matrix },
else => null,
};
}
pub fn isNumeric(t: *const TypeTable, id: TypeId) bool {
return t.component(id) != null;
}
/// Build a numeric type of `shape` with component `s`.
pub fn withShape(t: *TypeTable, s: Scalar, sh: Shape) !TypeId {
return switch (sh.kind) {
.scalar => t.scalar(s),
.vector => t.vector(s, sh.cols),
.matrix => t.matrix(s, sh.rows, sh.cols),
};
}
/// Same shape as `id`, different component.
pub fn withComponent(t: *TypeTable, id: TypeId, s: Scalar) !TypeId {
return t.withShape(s, t.shape(id) orelse return error_type);
}
/// Number of scalar components (flattened), or null for non-numeric
/// aggregates whose size is not defined.
pub fn componentCount(t: *const TypeTable, id: TypeId) ?u32 {
return switch (t.get(id)) {
.scalar, .@"enum" => 1,
.vector => |v| v.len,
.matrix => |m| @as(u32, m.rows) * m.cols,
.array => |a| if (a.len == 0) null else if (t.componentCount(a.elem)) |n| n * a.len else null,
.@"struct" => |s| blk: {
var n: u32 = 0;
for (s.fields.items, 0..) |f, i| n += if (f.bits) @as(u32, @intCast(s.bitfieldsIn(@intCast(i)).len)) else t.componentCount(f.type) orelse break :blk null;
break :blk n;
},
else => null,
};
}
/// Spelling for diagnostics, close to dxc's (`vector<float, 3>`,
/// `float4`, `MyStruct`, `Texture2D<float4>`).
pub fn format(t: *const TypeTable, gpa: Allocator, id: TypeId) Allocator.Error![]const u8 {
return switch (t.get(id)) {
.void => "void",
.@"error" => "<error>",
.scalar => |s| s.name(),
.vector => |v| std.fmt.allocPrint(gpa, "vector<{s}, {d}>", .{ v.elem.name(), v.len }),
.matrix => |m| std.fmt.allocPrint(gpa, "matrix<{s}, {d}, {d}>", .{ m.elem.name(), m.rows, m.cols }),
.array => |a| if (a.len == 0)
std.fmt.allocPrint(gpa, "{s}[]", .{try t.format(gpa, a.elem)})
else
std.fmt.allocPrint(gpa, "{s}[{d}]", .{ try t.format(gpa, a.elem), a.len }),
.@"struct" => |s| s.name,
.@"enum" => |e| e.name,
.resource => |r| if (r.elem == void_type) r.name else templateName(gpa, r.name, try t.format(gpa, r.elem), ""),
.sampler => |s| if (s.comparison) "SamplerComparisonState" else "SamplerState",
.string => "string",
.stream => |s| templateName(gpa, switch (s.kind) {
.point => "PointStream",
.line => "LineStream",
.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})),
.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) {
.mips => "mips_type",
.mips_slice => "mips_slice_type",
.sample => "sample_type",
.sample_slice => "sample_slice_type",
} }),
.spirv => |x| if (x.size == 0) "SpirvOpaqueType" else "SpirvType",
};
}
};
/// `name<arg rest>`, spelled as clang does: `> >` when `arg rest` ends
/// in `>`.
fn templateName(gpa: Allocator, name: []const u8, arg: []const u8, rest: []const u8) Allocator.Error![]const u8 {
const inner = try std.mem.concat(gpa, u8, &.{ arg, rest });
const space = if (std.mem.endsWith(u8, inner, ">")) " " else "";
return std.fmt.allocPrint(gpa, "{s}<{s}{s}>", .{ name, inner, space });
}
test "interning and shapes" {
var t = try TypeTable.init(std.testing.allocator);
defer t.deinit();
const f4 = try t.vector(.float, 4);
try std.testing.expectEqual(f4, try t.vector(.float, 4));
try std.testing.expect(f4 != try t.vector(.float, 3));
try std.testing.expect(try t.vector(.float, 1) != try t.scalar(.float));
const m = try t.matrix(.float, 4, 4);
try std.testing.expectEqual(@as(?u32, 16), t.componentCount(m));
try std.testing.expectEqual(try t.vector(.int, 4), try t.withComponent(f4, .int));
const s = try t.format(std.testing.allocator, f4);
defer std.testing.allocator.free(s);
try std.testing.expectEqualStrings("vector<float, 4>", s);
}

View File

@ -6,20 +6,250 @@ const Allocator = std.mem.Allocator;
pub const Id = u32; pub const Id = u32;
/// Opcodes used so far. Will be replaced by tables generated from /// SPIR-V opcodes (unified1 core grammar numbering).
/// vendor/spirv grammar JSON.
pub const Op = enum(u16) { pub const Op = enum(u16) {
undef = 1,
source = 3,
name = 5, name = 5,
member_name = 6,
extension = 10,
ext_inst_import = 11,
ext_inst = 12,
memory_model = 14, memory_model = 14,
entry_point = 15, entry_point = 15,
execution_mode = 16, execution_mode = 16,
capability = 17, capability = 17,
type_void = 19, type_void = 19,
type_bool = 20,
type_int = 21,
type_float = 22,
type_vector = 23,
type_matrix = 24,
type_image = 25,
type_sampler = 26,
type_sampled_image = 27,
type_array = 28,
type_runtime_array = 29,
type_struct = 30,
type_pointer = 32,
type_function = 33, type_function = 33,
constant_true = 41,
spec_constant_true = 48,
spec_constant_false = 49,
spec_constant = 50,
decorate_id = 332,
execution_mode_id = 331,
decorate_string = 5632,
begin_invocation_interlock_ext = 5364,
end_invocation_interlock_ext = 5365,
constant_false = 42,
constant = 43,
constant_composite = 44,
constant_null = 46,
function = 54, function = 54,
function_parameter = 55,
function_end = 56, function_end = 56,
function_call = 57,
variable = 59,
load = 61,
store = 62,
image_texel_pointer = 60,
access_chain = 65,
decorate = 71,
member_decorate = 72,
vector_extract_dynamic = 77,
vector_insert_dynamic = 78,
vector_shuffle = 79,
composite_construct = 80,
composite_extract = 81,
composite_insert = 82,
copy_object = 83,
transpose = 84,
array_length = 68,
sampled_image = 86,
image_sample_implicit_lod = 87,
image_sample_explicit_lod = 88,
image_sample_dref_implicit_lod = 89,
image_sample_dref_explicit_lod = 90,
image_fetch = 95,
image_gather = 96,
image_dref_gather = 97,
image_read = 98,
image = 100,
image_sparse_sample_implicit_lod = 305,
image_sparse_sample_explicit_lod = 306,
image_sparse_sample_dref_implicit_lod = 307,
image_sparse_sample_dref_explicit_lod = 308,
image_sparse_fetch = 313,
image_sparse_gather = 314,
image_sparse_dref_gather = 315,
image_sparse_texels_resident = 316,
image_sparse_read = 320,
image_write = 99,
image_query_size_lod = 103,
image_query_size = 104,
image_query_lod = 105,
image_query_levels = 106,
image_query_samples = 107,
atomic_exchange = 229,
atomic_compare_exchange = 230,
atomic_i_add = 234,
atomic_i_sub = 235,
atomic_s_min = 236,
atomic_u_min = 237,
atomic_s_max = 238,
atomic_u_max = 239,
atomic_and = 240,
atomic_or = 241,
atomic_xor = 242,
convert_f_to_u = 109,
convert_f_to_s = 110,
convert_s_to_f = 111,
convert_u_to_f = 112,
u_convert = 113,
s_convert = 114,
f_convert = 115,
bitcast = 124,
s_negate = 126,
f_negate = 127,
i_add = 128,
f_add = 129,
i_sub = 130,
f_sub = 131,
i_mul = 132,
f_mul = 133,
u_div = 134,
s_div = 135,
f_div = 136,
u_mod = 137,
s_rem = 138,
s_mod = 139,
f_rem = 140,
f_mod = 141,
vector_times_scalar = 142,
matrix_times_scalar = 143,
vector_times_matrix = 144,
matrix_times_vector = 145,
matrix_times_matrix = 146,
dot = 148,
any = 154,
all = 155,
is_nan = 156,
is_inf = 157,
logical_equal = 164,
logical_not_equal = 165,
logical_or = 166,
logical_and = 167,
logical_not = 168,
select = 169,
i_equal = 170,
i_not_equal = 171,
u_greater_than = 172,
s_greater_than = 173,
u_greater_than_equal = 174,
s_greater_than_equal = 175,
u_less_than = 176,
s_less_than = 177,
u_less_than_equal = 178,
s_less_than_equal = 179,
f_ord_equal = 180,
f_ord_not_equal = 182,
f_unord_not_equal = 183,
f_ord_less_than = 184,
f_ord_greater_than = 186,
f_ord_less_than_equal = 188,
f_ord_greater_than_equal = 190,
shift_right_logical = 194,
shift_right_arithmetic = 195,
shift_left_logical = 196,
bitwise_or = 197,
bitwise_xor = 198,
bitwise_and = 199,
not_ = 200,
bit_reverse = 204,
bit_count = 205,
dpdx = 207,
dpdy = 208,
fwidth = 209,
dpdx_fine = 210,
dpdy_fine = 211,
control_barrier = 224,
memory_barrier = 225,
phi = 245,
loop_merge = 246,
selection_merge = 247,
label = 248, label = 248,
branch = 249,
branch_conditional = 250,
@"switch" = 251,
kill = 252,
@"return" = 253, @"return" = 253,
return_value = 254,
@"unreachable" = 255,
group_non_uniform_elect = 333,
emit_mesh_tasks_ext = 5294,
trace_ray_khr = 4445,
execute_callable_khr = 4446,
convert_u_to_acceleration_structure_khr = 4447,
ignore_intersection_khr = 4448,
terminate_ray_khr = 4449,
type_ray_query_khr = 4472,
ray_query_initialize_khr = 4473,
ray_query_terminate_khr = 4474,
ray_query_generate_intersection_khr = 4475,
ray_query_confirm_intersection_khr = 4476,
ray_query_proceed_khr = 4477,
ray_query_get_intersection_type_khr = 4479,
report_intersection_khr = 5334,
ray_query_get_intersection_triangle_vertex_positions_khr = 5340,
type_acceleration_structure_khr = 5341,
ray_query_get_ray_t_min_khr = 6016,
ray_query_get_ray_flags_khr = 6017,
ray_query_get_intersection_t_khr = 6018,
ray_query_get_intersection_instance_custom_index_khr = 6019,
ray_query_get_intersection_instance_id_khr = 6020,
ray_query_get_intersection_instance_shader_binding_table_record_offset_khr = 6021,
ray_query_get_intersection_geometry_index_khr = 6022,
ray_query_get_intersection_primitive_index_khr = 6023,
ray_query_get_intersection_barycentrics_khr = 6024,
ray_query_get_intersection_front_face_khr = 6025,
ray_query_get_intersection_candidate_aabb_opaque_khr = 6026,
ray_query_get_intersection_object_ray_direction_khr = 6027,
ray_query_get_intersection_object_ray_origin_khr = 6028,
ray_query_get_world_ray_direction_khr = 6029,
ray_query_get_world_ray_origin_khr = 6030,
ray_query_get_intersection_object_to_world_khr = 6031,
ray_query_get_intersection_world_to_object_khr = 6032,
set_mesh_outputs_ext = 5295,
group_non_uniform_all = 334,
group_non_uniform_any = 335,
group_non_uniform_all_equal = 336,
group_non_uniform_broadcast = 337,
group_non_uniform_broadcast_first = 338,
group_non_uniform_ballot = 339,
group_non_uniform_ballot_bit_count = 342,
group_non_uniform_shuffle = 345,
group_non_uniform_i_add = 349,
group_non_uniform_f_add = 350,
group_non_uniform_i_mul = 351,
group_non_uniform_f_mul = 352,
group_non_uniform_s_min = 353,
group_non_uniform_u_min = 354,
group_non_uniform_f_min = 355,
group_non_uniform_s_max = 356,
group_non_uniform_u_max = 357,
group_non_uniform_f_max = 358,
group_non_uniform_bitwise_and = 359,
group_non_uniform_bitwise_or = 360,
group_non_uniform_bitwise_xor = 361,
group_non_uniform_quad_broadcast = 365,
group_non_uniform_quad_swap = 366,
emit_vertex = 218,
end_primitive = 219,
emit_stream_vertex = 220,
end_stream_primitive = 221,
/// (Inline SPIR-V may use any value.)
_,
}; };
pub const Section = enum { pub const Section = enum {

4702
src/spirv/emit.zig Normal file

File diff suppressed because it is too large Load Diff

307
src/spirv/memory_model.zig Normal file
View File

@ -0,0 +1,307 @@
//! The Vulkan memory model (-fspv-use-vulkan-memory-model, or modules that
//! need it): a port of spirv-opt's UpgradeMemoryModel pass, which dxc runs
//! on its output. Coherent and Volatile decorations become flags on the
//! loads, stores, image reads / writes and atomics that reach them, and
//! Device scopes become QueueFamily.
const std = @import("std");
const builder = @import("builder.zig");
const op_caps = @import("op_caps.zig");
const Id = builder.Id;
const coherent_dec = 23;
const volatile_dec = 21;
const scope_device = 1;
const scope_workgroup = 2;
const scope_queue_family = 5;
const Attrs = struct { coherent: bool = false, @"volatile": bool = false };
fn Pass(comptime E: type) type {
return struct {
e: E,
a: std.mem.Allocator,
/// Result id -> (section, word offset) of its instruction.
defs: std.AutoHashMapUnmanaged(Id, struct { sec: builder.Section, at: usize }) = .empty,
/// Decorations: (target, member or maxInt, decoration).
decs: std.ArrayList([3]u32) = .empty,
const Self = @This();
fn words(p: *Self, id: Id) ?[]const u32 {
const d = p.defs.get(id) orelse return null;
const s = p.e.b.sections.get(d.sec).items;
return s[d.at..][0 .. s[d.at] >> 16];
}
fn opcode(w: []const u32) u32 {
return w[0] & 0xffff;
}
fn typeOf(p: *Self, id: Id) ?Id {
const w = p.words(id) orelse return null;
const l = op_caps.resultLayout(opcode(w));
return if (l.ty) |t| w[1 + t] else null;
}
/// The storage class of a pointer-typed value.
fn storageOf(p: *Self, id: Id) ?u32 {
const t = p.words(p.typeOf(id) orelse return null) orelse return null;
return if (opcode(t) == 32) t[2] else null;
}
fn constValue(p: *Self, id: Id) ?u32 {
const w = p.words(id) orelse return null;
return if (opcode(w) == 43) w[3] else null;
}
fn hasDec(p: *Self, id: Id, member: u32, dec: u32) bool {
for (p.decs.items) |d| {
if (d[0] != id or d[2] != dec) continue;
if (d[1] == std.math.maxInt(u32) or member == std.math.maxInt(u32) or d[1] == member) return true;
}
return false;
}
/// Coherent / Volatile of a struct member reached through
/// `indices` (innermost last), then of any type below it.
fn checkType(p: *Self, ptr_type: Id, indices: []const Id) Attrs {
var r: Attrs = .{};
var elem = (p.words(ptr_type) orelse return r)[3];
var i = indices.len;
while (i > 0 and !(r.coherent and r.@"volatile")) {
i -= 1;
const w = p.words(elem) orelse return r;
switch (opcode(w)) {
32 => elem = w[3],
30 => {
const k = p.constValue(indices[i]) orelse return r;
r.coherent = r.coherent or p.hasMemberDec(elem, k, coherent_dec);
r.@"volatile" = r.@"volatile" or p.hasMemberDec(elem, k, volatile_dec);
elem = w[2 + k];
},
else => elem = w[2],
}
}
if (!(r.coherent and r.@"volatile")) {
const all = p.checkAllTypes(elem);
r.coherent = r.coherent or all.coherent;
r.@"volatile" = r.@"volatile" or all.@"volatile";
}
return r;
}
fn hasMemberDec(p: *Self, st: Id, member: u32, dec: u32) bool {
for (p.decs.items) |d| if (d[0] == st and d[2] == dec and (d[1] == member or d[1] == std.math.maxInt(u32))) return true;
return false;
}
fn checkAllTypes(p: *Self, ty: Id) Attrs {
var r: Attrs = .{};
var stack: std.ArrayList(Id) = .empty;
var seen: std.AutoHashMapUnmanaged(Id, void) = .empty;
stack.append(p.a, ty) catch return r;
while (stack.pop()) |t| {
if ((seen.getOrPut(p.a, t) catch return r).found_existing) continue;
const w = p.words(t) orelse continue;
switch (opcode(w)) {
30 => {
r.coherent = r.coherent or p.hasMemberDec(t, std.math.maxInt(u32), coherent_dec);
r.@"volatile" = r.@"volatile" or p.hasMemberDec(t, std.math.maxInt(u32), volatile_dec);
if (r.coherent and r.@"volatile") return r;
stack.appendSlice(p.a, w[2..]) catch return r;
},
23, 24, 28, 29 => stack.append(p.a, w[2]) catch return r,
32 => stack.append(p.a, w[3]) catch return r,
else => {},
}
}
return r;
}
fn isPointerLike(p: *Self, id: Id) bool {
const t = p.words(p.typeOf(id) orelse return false) orelse return false;
return switch (opcode(t)) {
25, 27, 32 => true, // image, sampled image, pointer
else => false,
};
}
/// Follows a pointer (or image) back to the variables it comes
/// from.
fn trace(p: *Self, id: Id, indices0: []const Id, visited: *std.AutoHashMapUnmanaged(Id, void)) std.mem.Allocator.Error!Attrs {
if ((try visited.getOrPut(p.a, id)).found_existing) return .{};
const w = p.words(id) orelse return .{};
var indices: std.ArrayList(Id) = .empty;
try indices.appendSlice(p.a, indices0);
switch (opcode(w)) {
59, 55 => { // OpVariable, OpFunctionParameter
var r: Attrs = .{ .coherent = p.hasDec(id, 0, coherent_dec), .@"volatile" = p.hasDec(id, 0, volatile_dec) };
if (!(r.coherent and r.@"volatile")) {
const t = p.checkType(w[1], indices.items);
r.coherent = r.coherent or t.coherent;
r.@"volatile" = r.@"volatile" or t.@"volatile";
}
return r;
},
65, 66 => { // OpAccessChain, OpInBoundsAccessChain
var i = w.len;
while (i > 4) {
i -= 1;
try indices.append(p.a, w[i]);
}
},
67, 70 => { // OpPtrAccessChain, OpInBoundsPtrAccessChain
var i = w.len;
while (i > 5) {
i -= 1;
try indices.append(p.a, w[i]);
}
},
else => {},
}
var r: Attrs = .{};
const l = op_caps.resultLayout(opcode(w));
for (w[1..], 0..) |x, k| {
if ((l.ty != null and k == l.ty.?) or (l.id != null and k == l.id.?)) continue;
if (!p.isPointerLike(x)) continue;
const o = try p.trace(x, indices.items, visited);
r.coherent = r.coherent or o.coherent;
r.@"volatile" = r.@"volatile" or o.@"volatile";
}
return r;
}
fn attributes(p: *Self, ptr: Id) std.mem.Allocator.Error!struct { Attrs, u32 } {
if (p.storageOf(ptr) == 4) return .{ .{ .coherent = true }, scope_workgroup }; // Workgroup
var visited: std.AutoHashMapUnmanaged(Id, void) = .empty;
return .{ try p.trace(ptr, &.{}, &visited), scope_queue_family };
}
};
}
/// Rewrites the module for the Vulkan memory model (the caller emits the
/// capability, extension and memory model instruction).
pub fn upgrade(e: anytype, has_tess_control: bool) !void {
var p: Pass(@TypeOf(e)) = .{ .e = e, .a = e.arena };
for ([_]builder.Section{ .types_globals, .functions }) |sec| {
const s = e.b.sections.get(sec).items;
var at: usize = 0;
while (at < s.len) : (at += s[at] >> 16) {
const l = op_caps.resultLayout(s[at] & 0xffff);
if (l.id) |k| try p.defs.put(p.a, s[at + 1 + k], .{ .sec = sec, .at = at });
}
}
{
const s = e.b.sections.get(.annotations).items;
var at: usize = 0;
while (at < s.len) : (at += s[at] >> 16) switch (s[at] & 0xffff) {
71, 332 => try p.decs.append(p.a, .{ s[at + 1], std.math.maxInt(u32), s[at + 2] }),
72 => try p.decs.append(p.a, .{ s[at + 1], s[at + 2], s[at + 3] }),
else => {},
};
}
// Tessellation control shaders that write outputs: barriers that
// order memory also order output memory.
var writes_output = false;
if (has_tess_control) {
const s = e.b.sections.get(.functions).items;
var at: usize = 0;
while (at < s.len and !writes_output) : (at += s[at] >> 16) {
for (s[at + 1 .. at + (s[at] >> 16)]) |x| if (p.storageOf(x) == 3) {
writes_output = true;
};
}
}
const old = try p.a.dupe(u32, e.b.sections.get(.functions).items);
var out: std.ArrayList(u32) = .empty;
var at: usize = 0;
while (at < old.len) : (at += old[at] >> 16) {
const n = old[at] >> 16;
var w: std.ArrayList(u32) = .empty;
try w.appendSlice(p.a, old[at..][0..n]);
const op = w.items[0] & 0xffff;
const l = op_caps.resultLayout(op);
// Word index of in-operand 0.
const in0: usize = 1 + @as(usize, @intFromBool(l.ty != null)) + @intFromBool(l.id != null);
switch (op) {
61, 62 => { // OpLoad, OpStore
const ptr = w.items[in0];
var at_s = try p.attributes(ptr);
const sc = p.storageOf(ptr);
if (sc == 7 or sc == 6) at_s[0].coherent = false; // Function, Private
try flags(e, &w, in0 + @as(usize, if (op == 61) 1 else 2), at_s[0], op == 61, false, at_s[1]);
},
98, 99, 4290 => { // OpImageRead, OpImageWrite, OpImageSparseRead
const at_s = try p.attributes(w.items[in0]);
try flags(e, &w, in0 + @as(usize, if (op == 99) 3 else 2), at_s[0], op != 99, true, at_s[1]);
},
else => {},
}
if (isAtomic(op)) {
const at_s = try p.attributes(w.items[in0]);
if (at_s[0].@"volatile") {
w.items[in0 + 2] = try e.constUint((p.constValue(w.items[in0 + 2]) orelse 0) | 0x8000);
if (op == 230 or op == 231) w.items[in0 + 3] = try e.constUint((p.constValue(w.items[in0 + 3]) orelse 0) | 0x8000);
}
if (p.constValue(w.items[in0 + 1]) == scope_device) w.items[in0 + 1] = try e.constUint(scope_queue_family);
} else if (op == 224) { // OpControlBarrier
if (p.constValue(w.items[2]) == scope_device) w.items[2] = try e.constUint(scope_queue_family);
if (writes_output) if (p.constValue(w.items[3])) |sem| if (sem & 0x1e != 0) {
w.items[3] = try e.constUint(sem | 0x1000); // OutputMemory
};
} else if (op == 225) { // OpMemoryBarrier
if (p.constValue(w.items[1]) == scope_device) w.items[1] = try e.constUint(scope_queue_family);
}
w.items[0] = (@as(u32, @intCast(w.items.len)) << 16) | op;
try out.appendSlice(p.a, w.items);
}
const fs = e.b.sections.getPtr(.functions);
fs.clearRetainingCapacity();
try fs.appendSlice(e.b.gpa, out.items);
// Coherent and Volatile decorations are gone.
const an = e.b.sections.getPtr(.annotations);
var r: usize = 0;
var wr: usize = 0;
while (r < an.items.len) {
const n = an.items[r] >> 16;
const dec_word: ?u32 = switch (an.items[r] & 0xffff) {
71, 332 => an.items[r + 2],
72 => an.items[r + 3],
else => null,
};
if (dec_word == null or (dec_word.? != coherent_dec and dec_word.? != volatile_dec)) {
std.mem.copyForwards(u32, an.items[wr..][0..n], an.items[r..][0..n]);
wr += n;
}
r += n;
}
an.shrinkRetainingCapacity(wr);
}
fn isAtomic(op: u32) bool {
return switch (op) {
227...242, 318, 319, 5614, 5615, 6035 => true,
else => false,
};
}
/// Memory access (or image operand) flags for a coherent / volatile
/// access at word `k`, then the scope operand.
fn flags(e: anytype, w: *std.ArrayList(u32), k: usize, at: Attrs, visible: bool, image: bool, scope: u32) !void {
if (!at.coherent and !at.@"volatile") return;
var f: u32 = if (k < w.items.len) w.items[k] else 0;
if (at.coherent) {
if (image) {
f |= 0x400 | @as(u32, if (visible) 0x200 else 0x100); // NonPrivateTexel, MakeTexelVisible / Available
} else {
f |= 0x20 | @as(u32, if (visible) 0x10 else 0x8); // NonPrivatePointer, MakePointerVisible / Available
}
}
if (at.@"volatile") f |= if (image) 0x800 else 0x1;
if (k < w.items.len) w.items[k] = f else try w.append(e.arena, f);
if (at.coherent) try w.append(e.arena, try e.constUint(scope));
}

1396
src/spirv/op_caps.zig Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,13 @@
// PROFILE: as_6_5
// Amplification shader: a groupshared payload (struct-typed, accessed
// through GEPs) sent with DispatchMesh.
// ZCHECK: call void @dx.op.dispatchMesh.struct.Payload(i32 173
struct Payload { uint base; float scale[2]; uint ids[8]; };
groupshared Payload pl;
[numthreads(8,1,1)]
void main(uint tid : SV_GroupIndex) {
pl.ids[tid] = tid * 2;
if (tid == 0) { pl.base = 7; pl.scale[0] = 1; pl.scale[1] = 2; }
GroupMemoryBarrierWithGroupSync();
DispatchMesh(2, 1, 1, pl);
}

23
test/dxil/atomics.hlsl Normal file
View File

@ -0,0 +1,23 @@
// PROFILE: cs_6_0
// Atomics on groupshared memory, buffers and texels; byte-address buffers.
// ZCHECK: atomicrmw add i32 addrspace(3)*
// ZCHECK: cmpxchg i32 addrspace(3)*
// ZCHECK: @dx.op.atomicBinOp.i32(i32 78, %dx.types.Handle {{.*}}, i32 8,
// ZCHECK: @dx.op.atomicCompareExchange.i32(i32 79,
groupshared uint cnt;
groupshared int mx[4];
RWStructuredBuffer<uint> sb : register(u0);
RWBuffer<uint> tb : register(u1);
RWTexture2D<int> tex : register(u2);
RWByteAddressBuffer rb : register(u3);
[numthreads(64,1,1)] void main(uint i : SV_GroupIndex) {
uint old, o2; int o3;
InterlockedAdd(cnt, 1, old);
InterlockedMax(mx[i & 3], (int)i);
InterlockedCompareExchange(cnt, 5, 6, o2);
InterlockedOr(sb[i], 2);
InterlockedMin(tb[i], i, o2);
InterlockedExchange(tex[uint2(i, 1)], 3, o3);
InterlockedCompareStore(sb[0], 1, 2);
sb[1] = old + o2 + o3;
}

10
test/dxil/barriers.hlsl Normal file
View File

@ -0,0 +1,10 @@
// PROFILE: cs_6_0
// Memory barriers (device, group, all; with and without group sync).
// ZCHECK: call void @dx.op.barrier(i32 80, i32 10)
// ZCHECK: call void @dx.op.barrier(i32 80, i32 2)
RWStructuredBuffer<uint4> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) {
AllMemoryBarrier(); AllMemoryBarrierWithGroupSync(); DeviceMemoryBarrier(); DeviceMemoryBarrierWithGroupSync(); GroupMemoryBarrier();
o[0] = uint4(firstbitlow(i), firstbithigh(i), firstbithigh((int)i), f32tof16(asfloat(i)));
o[1].x = asuint(f16tof32(i));
}

28
test/dxil/bitfields.hlsl Normal file
View File

@ -0,0 +1,28 @@
// PROFILE: cs_6_2
// Bitfields: DXIL packs same-size bitfields into one i32 (a, b, c share a
// word even though c is signed); reads mask/shift, writes read-modify-write.
// ZCHECK: and i32 {{.*}}, -249
// ZCHECK: or i32 {{.*}}, 56
// ZCHECK: ashr i32
struct Base { uint lo : 4; uint hi : 4; };
struct P : Base {
uint a : 3; uint b : 5; int c : 4;
uint d;
uint e : 30; uint f : 4;
uint sum() { return a + b + lo + hi; }
void bump() { b += 1; hi++; }
};
cbuffer CB { P cp; };
RWStructuredBuffer<P> sb : register(u0);
RWStructuredBuffer<int> o : register(u1);
[numthreads(1,1,1)] void main() {
P p = sb[0];
p.b = 7;
p.c = -3;
p.bump();
sb[1] = p;
P q = {1, 2, 3, 4, -5, 6, 7, 8};
sb[2] = q;
sb[3].f |= 2;
o[0] = p.a + p.c + cp.e + cp.f + p.sum() + q.c;
}

View File

@ -0,0 +1,11 @@
// PROFILE: cs_6_0
// Structured buffers of matrices: whole loads and stores, rows (constant
// and dynamic) and row components.
StructuredBuffer<float4x3> m : register(t0);
RWStructuredBuffer<float2x3> r : register(u1);
RWStructuredBuffer<float4> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) {
o[i] = float4(m[i][1], 1) + r[i][0].x + float4(m[0][i % 4], m[1][2].y);
r[i] = r[i] * 2;
o[i + 1] = mul(float4(1, 2, 3, 4), m[i]).xyzz;
}

View File

@ -0,0 +1,16 @@
// PROFILE: cs_6_0
// Byte-address buffer loads, stores, atomics and sizes.
RWByteAddressBuffer rb : register(u0);
ByteAddressBuffer ro : register(t0);
RWStructuredBuffer<uint> c : register(u1);
AppendStructuredBuffer<float4> ap : register(u2);
ConsumeStructuredBuffer<float4> co : register(u3);
[numthreads(64,1,1)] void main(uint i : SV_GroupIndex) {
uint4 v = ro.Load4(i * 16) + rb.Load2(4).xyxy;
rb.Store3(i * 12, v.xyz);
uint old; rb.InterlockedAdd(0, 1, old);
rb.InterlockedCompareStore(8, 1, 2);
uint n = 0;
rb.Store(20, n + old);
uint w; rb.GetDimensions(w); rb.Store(16, w);
}

View File

@ -0,0 +1,20 @@
// PROFILE: cs_6_2
// FLAGS: -enable-16bit-types
// Templated byte-address Load/Store of structs, matrices (by row in
// DXIL), 16- and 64-bit components (two words before SM 6.3); locals with
// components of several sizes in struct-typed memory.
// ZCHECK: call double @dx.op.makeDouble.f64(i32 101
// ZCHECK: rawBufferLoad.f16
struct S { float a; double b; uint16_t c; int2 d; };
RWByteAddressBuffer buf : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) {
S s = buf.Load<S>(i * 32);
float3x2 m = buf.Load<float3x2>(64);
half4 h = buf.Load<half4>(128);
S arr[2] = buf.Load<S[2]>(256);
s.a += m[1][0] + h.y + arr[1].d.x;
buf.Store<S>(i * 32 + 512, s);
buf.Store<float3x2>(96, m);
buf.Store<half4>(136, h);
buf.Store<double>(160, s.b);
}

60
test/dxil/check.sh Normal file
View File

@ -0,0 +1,60 @@
#!/bin/sh
# DXIL output checks beyond validation: for each test/dxil/*.hlsl, zdxc's
# signature tables (ISG1/OSG1 and PSV0, minus the "Used" column) must match
# dxc's, and every `// ZCHECK: text` line must appear in zdxc's disassembly
# (`{{.*}}` matches anything).
#
# Usage: test/dxil/check.sh <path-to-zdxc>
set -u
ZDXC=$1
DXC_BUILD=${DXC_BUILD:-../build}
DXC=$DXC_BUILD/bin/dxc
DXV=$DXC_BUILD/bin/dxv
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
pass=0
fail=0
# Signature table rows, cut before the "Used" column.
sigtables() {
awk '/^; (Input|Output|Patch Constant) signature:/ { on = 1; seen = 0; next }
on && /^; (-|Name|shader hash)/ { next }
on && /^;$/ { if (seen) on = 0; next }
on { print substr($0, 1, 63); seen = 1 }' "$1" | sed 's/ *$//'
}
for f in test/dxil/*.hlsl; do
profile=$(sed -n 's|^// PROFILE: *||p' "$f")
flags=$(sed -n 's|^// FLAGS: *||p' "$f")
name=$(basename "$f" .hlsl)
if ! "$ZDXC" -T "$profile" $flags "$f" -Fo "$TMP/z.dxo" > "$TMP/log" 2>&1; then
fail=$((fail + 1)); echo "FAIL $name: zdxc failed"; head -3 "$TMP/log"; continue
fi
if ! "$DXV" "$TMP/z.dxo" > "$TMP/log" 2>&1; then
fail=$((fail + 1)); echo "FAIL $name: dxv rejected the output"; head -3 "$TMP/log"; continue
fi
"$DXC" -dumpbin "$TMP/z.dxo" > "$TMP/z.ll" 2>&1
rm -f "$TMP/d.ll"
if ! "$DXC" -T "$profile" $flags "$f" -Fc "$TMP/d.ll" > "$TMP/log" 2>&1; then
fail=$((fail + 1)); echo "FAIL $name: dxc rejects this test"; head -3 "$TMP/log"; continue
fi
ok=1
sigtables "$TMP/z.ll" > "$TMP/z.sig"
sigtables "$TMP/d.ll" > "$TMP/d.sig"
if ! diff "$TMP/d.sig" "$TMP/z.sig" > "$TMP/diff"; then
ok=0; echo "FAIL $name: signatures differ from dxc (< dxc, > zdxc)"; head -10 "$TMP/diff"
fi
# Runtime data (libraries) and root signatures must match dxc byte for byte.
"$DXC" -T "$profile" $flags "$f" -Fo "$TMP/d.dxo" > /dev/null 2>&1
if ! python3 test/dxil/compare_parts.py "$TMP/d.dxo" "$TMP/z.dxo" > "$TMP/rdat" 2>&1; then
ok=0; echo "FAIL $name: RDAT / RTS0 differ from dxc"; head -10 "$TMP/rdat"
fi
sed -n 's|^// ZCHECK: *||p' "$f" > "$TMP/checks"
while IFS= read -r pat; do
re=$(printf '%s\n' "$pat" | sed -e 's/[][\.*^$()+?|{}]/\\&/g' -e 's/\\{\\{\\\.\\\*\\}\\}/.*/g')
grep -Eq -- "$re" "$TMP/z.ll" || { ok=0; echo "FAIL $name: missing '$pat'"; }
done < "$TMP/checks"
if [ $ok = 1 ]; then pass=$((pass + 1)); else fail=$((fail + 1)); fi
done
echo "dxil checks: $pass passed, $fail failed"
[ "$fail" -eq 0 ]

View File

@ -0,0 +1,23 @@
"""Exits non-zero if two DXIL containers' RDAT or RTS0 parts differ (or
only one has one). Usage: compare_parts.py <expected.dxo> <actual.dxo>"""
import struct
import sys
def part(path, fourcc):
data = open(path, 'rb').read()
count = struct.unpack_from('<I', data, 28)[0]
for off in struct.unpack_from('<%dI' % count, data, 32):
if data[off:off + 4] == fourcc:
size = struct.unpack_from('<I', data, off + 4)[0]
return data[off + 8:off + 8 + size]
return None
status = 0
for fourcc in (b'RDAT', b'RTS0'):
a, b = part(sys.argv[1], fourcc), part(sys.argv[2], fourcc)
if a != b:
print('%s: expected %s bytes, got %s' % (fourcc.decode(), None if a is None else len(a), None if b is None else len(b)))
status = 1
sys.exit(status)

View File

@ -0,0 +1,6 @@
// PROFILE: cs_6_6
// Implicit-LOD sampling and derivatives in a compute shader (SM 6.6).
Texture2D<float4> t : register(t0);
SamplerState s : register(s0);
RWStructuredBuffer<float4> o : register(u0);
[numthreads(8,8,1)] void main(uint2 id : SV_DispatchThreadID) { float2 uv = id / 64.0; o[id.x] = t.Sample(s, uv) + ddx(uv).x + t.CalculateLevelOfDetail(s, uv); }

View File

@ -0,0 +1,12 @@
// PROFILE: cs_6_0
// ConstantBuffer<T>: members (bitfields too), arrays, whole-struct reads,
// passing elements of resource arrays to (nested) functions.
// ZCHECK: cbufferLoadLegacy
struct S { float4 a; float b; uint lo : 8; uint hi : 8; };
ConstantBuffer<S> cbs[4] : register(b0);
Texture2D<float4> texs[2] : register(t0);
SamplerState smp : register(s0);
RWStructuredBuffer<float4> o : register(u0);
float4 inner(ConstantBuffer<S> c, Texture2D<float4> t) { return c.a * t.SampleLevel(smp, float2(0,0), 0) + c.hi; }
float4 outer(ConstantBuffer<S> c, Texture2D<float4> t) { return inner(c, t) + c.lo; }
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) { S s = cbs[2]; o[0] = outer(cbs[3], texs[1]) + outer(cbs[0], texs[0]) + cbs[i].a + s.b + s.lo; }

8
test/dxil/counters.hlsl Normal file
View File

@ -0,0 +1,8 @@
// PROFILE: cs_6_0
// Counters and Append/Consume buffers.
// ZCHECK: @dx.op.bufferUpdateCounter(i32 70, {{.*}}, i8 1)
// ZCHECK: @dx.op.bufferUpdateCounter(i32 70, {{.*}}, i8 -1)
RWStructuredBuffer<uint> c : register(u1);
AppendStructuredBuffer<float4> ap : register(u2);
ConsumeStructuredBuffer<float4> co : register(u3);
[numthreads(1,1,1)] void main() { uint n = c.IncrementCounter(); ap.Append(co.Consume() + n); }

View File

@ -0,0 +1,14 @@
// PROFILE: cs_6_6
// Descriptor heaps (SM 6.6): resources and samplers taken from the heaps.
// ZCHECK: call %dx.types.Handle @dx.op.createHandleFromHeap(i32 218
// ZCHECK: createHandleFromHeap(i32 218, i32 {{.*}}, i1 false, i1 true)
struct S { float4 a; float b; };
RWStructuredBuffer<float4> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) {
ConstantBuffer<S> c = ResourceDescriptorHeap[i];
Texture2D<float4> t = ResourceDescriptorHeap[i + 1];
SamplerState s = SamplerDescriptorHeap[0];
RWStructuredBuffer<float4> b = ResourceDescriptorHeap[NonUniformResourceIndex(i + 2)];
o[0] = c.a + t.SampleLevel(s, float2(0,0), 0);
b[i] = c.b;
}

22
test/dxil/domain.hlsl Normal file
View File

@ -0,0 +1,22 @@
// PROFILE: ds_6_0
// Domain shader: control points, patch constants, the domain location.
// ZCHECK: call float @dx.op.domainLocation.f32(i32 105, i8 1)
// ZCHECK: call float @dx.op.loadPatchConstant.f32(i32 104
struct HSOut { float4 pos : POSITION; float2 uv : TEXCOORD0; };
struct PC {
float edges[4] : SV_TessFactor;
float inside[2] : SV_InsideTessFactor;
float3 extra : EXTRA;
uint id : PATCHID;
};
struct DSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; nointerpolation uint id : PATCHID; };
[domain("quad")]
DSOut main(PC pc, float2 uv : SV_DomainLocation, const OutputPatch<HSOut, 4> patch, uint prim : SV_PrimitiveID) {
DSOut o;
float4 a = lerp(patch[0].pos, patch[1].pos, uv.x);
float4 b = lerp(patch[3].pos, patch[2].pos, uv.x);
o.pos = lerp(a, b, uv.y) + float4(pc.extra, pc.inside[1]);
o.uv = patch[0].uv * pc.edges[3];
o.id = pc.id + prim;
return o;
}

6
test/dxil/gather4.hlsl Normal file
View File

@ -0,0 +1,6 @@
// PROFILE: ps_6_0
// Gather with four offsets: four gathers (DXIL), ConstOffsets (SPIR-V).
// ZCHECK: textureGather.f32(i32 73, {{.*}}, i32 -1, i32 0, i32 1)
Texture2D<float4> t : register(t0);
SamplerState s : register(s0);
float4 main(float2 uv : UV) : SV_Target { return t.GatherGreen(s, uv, int2(1,0), int2(0,1), int2(-1,0), int2(0,-1)); }

13
test/dxil/geometry.hlsl Normal file
View File

@ -0,0 +1,13 @@
// PROFILE: gs_6_0
// Geometry shader: per-vertex inputs, shadow SV_PrimitiveID, streams.
// ZCHECK: @dx.op.emitStream(i32 97, i8 0)
// ZCHECK: @dx.op.cutStream(i32 98, i8 0)
// ZCHECK: @dx.op.gsInstanceID.i32(i32 100)
// ZCHECK: !{i32 3, i32 6, i32 1, i32 5, i32 2}
struct VSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; };
struct GSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; uint layer : SV_RenderTargetArrayIndex; };
[maxvertexcount(6)] [instance(2)]
void main(triangle VSOut input[3], uint pid : SV_PrimitiveID, uint iid : SV_GSInstanceID, inout TriangleStream<GSOut> stream) {
for (int k = 0; k < 3; k++) { GSOut o; o.pos = input[k].pos; o.uv = input[k].uv + pid; o.layer = iid; stream.Append(o); }
stream.RestartStrip();
}

View File

@ -0,0 +1,6 @@
// PROFILE: cs_6_0
// Groupshared memory: address-space-3 globals, and the PSV byte count.
// ZCHECK: @g = external addrspace(3) global [64 x float], align 4
groupshared float g[64];
RWStructuredBuffer<float> o : register(u0);
[numthreads(64,1,1)] void main(uint i : SV_GroupIndex) { g[i] = i; GroupMemoryBarrierWithGroupSync(); o[i] = g[63 - i]; }

36
test/dxil/hull.hlsl Normal file
View File

@ -0,0 +1,36 @@
// PROFILE: hs_6_0
// Hull shader: control points in and out, a patch constant function
// reading the input patch and the output control points.
// ZCHECK: call i32 @dx.op.outputControlPointID.i32(i32 107)
// ZCHECK: call void @dx.op.storePatchConstant.f32(i32 106
// ZCHECK: call float @dx.op.loadOutputControlPoint.f32(i32 103
struct VSOut { float4 pos : POSITION; float2 uv : TEXCOORD0; };
struct HSOut { float4 pos : POSITION; float2 uv : TEXCOORD0; };
struct PC {
float edges[4] : SV_TessFactor;
float inside[2] : SV_InsideTessFactor;
float3 extra : EXTRA;
uint id : PATCHID;
};
cbuffer CB { float tess; };
PC patchConst(InputPatch<VSOut, 4> ip, const OutputPatch<HSOut, 4> op, uint pid : SV_PrimitiveID) {
PC o;
[unroll] for (int i = 0; i < 4; i++) o.edges[i] = tess + i;
o.inside[0] = ip[0].pos.x;
o.inside[1] = op[3].uv.y;
o.extra = ip[1].pos.xyz + op[2].pos.xyz;
o.id = pid;
return o;
}
[domain("quad")]
[partitioning("fractional_even")]
[outputtopology("triangle_ccw")]
[outputcontrolpoints(4)]
[patchconstantfunc("patchConst")]
[maxtessfactor(32.0)]
HSOut main(InputPatch<VSOut, 4> ip, uint id : SV_OutputControlPointID) {
HSOut o;
o.pos = ip[id].pos * 2;
o.uv = ip[id].uv;
return o;
}

View File

@ -0,0 +1,12 @@
// PROFILE: hs_6_0
// Isoline hull shader: line tess factors (density, detail); the main
// function declares the input patch but does not read it.
struct CP { float3 p : P; };
struct PC { float f[2] : SV_TessFactor; };
PC pcf(InputPatch<CP, 2> ip) { PC o; o.f[0] = ip[0].p.x; o.f[1] = ip[1].p.y; return o; }
[domain("isoline")]
[partitioning("integer")]
[outputtopology("line")]
[outputcontrolpoints(2)]
[patchconstantfunc("pcf")]
CP main(InputPatch<CP, 2> ip, uint id : SV_OutputControlPointID) { CP c; c.p = float3(id, 0, 1); return c; }

View File

@ -0,0 +1,18 @@
// PROFILE: ps_6_6
// Intrinsics: firstbit*, f32tof16/f16tof32, and/or/select, isnan & co.,
// fmod, integer dot, any/all, fine derivatives, clip, IsHelperLane.
// ZCHECK: unaryBits.i32(i32 34
// ZCHECK: legacyF32ToF16
// ZCHECK: isHelperLane
RWStructuredBuffer<uint4> o : register(u0);
float4 main(float4 p : SV_Position, uint i : U) : SV_Target {
DeviceMemoryBarrier();
o[0] = uint4(firstbitlow(i), firstbithigh(i), firstbithigh((int)i), f32tof16(p.x));
int3 a = int3(1, 2, i), b = int3(3, i, 5);
bool3 m = and(a > 1, b < 4);
bool3 n = or(m, isnan(p.xyz));
float3 s = select(n, p.xyz, float3(1, 2, 3));
float r = fmod(p.x, 3) + f16tof32(i) + dot(a, b) + any(isinf(p)) + all(isfinite(p)) + isnormal(p.w) + ddx_fine(p.x) + ddy_fine(p.y);
clip(p.xy - 1);
return float4(s, r) + IsHelperLane();
}

View File

@ -0,0 +1,21 @@
// PROFILE: lib_6_6
// Graphics shaders in a library: entries with their signatures (no usage
// masks), stage state, and the patch constant function defined under its
// mangled name in declaration order. RDAT is checked against dxc's.
// ZCHECK: define void @"\01?pcf@@YA?AUPC@@V?$InputPatch@UCP@@$02@@@Z"()
// ZCHECK: define void @hs()
// ZCHECK: !{i32 8, i32 2, i32 1, !{{.*}}, i32 5, !{{.*}}}
struct CP { float4 p : POSITION; };
struct PC { float e[3] : SV_TessFactor; float i : SV_InsideTessFactor; };
PC pcf(InputPatch<CP, 3> ip) { PC o; o.e[0] = o.e[1] = o.e[2] = 2; o.i = 2; return o; }
[shader("hull")] [domain("tri")] [partitioning("integer")] [outputtopology("triangle_cw")] [outputcontrolpoints(3)] [patchconstantfunc("pcf")]
CP hs(InputPatch<CP, 3> ip, uint id : SV_OutputControlPointID) { return ip[id]; }
[shader("domain")] [domain("tri")]
float4 ds(PC pc, float3 uvw : SV_DomainLocation, const OutputPatch<CP, 3> op) : SV_Position { return op[0].p * uvw.x + op[1].p * uvw.y + op[2].p * uvw.z; }
struct GO { float4 p : SV_Position; };
[shader("geometry")] [maxvertexcount(3)]
void gs(triangle float4 v[3] : SV_Position, inout TriangleStream<GO> s) { for (int k = 0; k < 3; k++) { GO o; o.p = v[k]; s.Append(o); } }
Texture2D t; SamplerState s;
struct V { float4 p : SV_Position; float2 uv : TEXCOORD; };
[shader("vertex")] V vs(float3 p : POSITION, float2 uv : TEXCOORD) { V o; o.p = float4(p, 1); o.uv = uv; return o; }
[shader("pixel")] float4 ps(V i) : SV_Target { return t.Sample(s, i.uv); }

View File

@ -0,0 +1,12 @@
// PROFILE: ps_6_0
// Math intrinsics lowered to arithmetic, as dxc does.
// ZCHECK: @dx.op.unary.f32(i32 17,
// ZCHECK: @dx.op.isSpecialFloat.f32(i32 8,
// ZCHECK: @dx.op.unary.f32(i32 22,
float4 main(float3 a : A, float3 b : B, float2 c : C, float4x4 m : M, float3x3 m3 : N) : SV_Target {
float3 r = cross(a, b) + reflect(a, b) + refract(a, b, c.x) + faceforward(a, b, a);
float s = atan2(c.x, c.y) + fmod(c.x, c.y) + distance(a, b) + determinant(m) + determinant(m3);
s += smoothstep(0, 1, c.x) + step(0.5, c.y) + degrees(c.x) + radians(c.y) + ldexp(c.x, c.y);
int sg = sign(c.x) + sign((int)c.y);
return float4(r, s + sg + (isnan(c.x) ? 1 : 0) + (isinf(c.y) ? 2 : 0) + (isfinite(a.x) ? 4 : 0));
}

27
test/dxil/mesh.hlsl Normal file
View File

@ -0,0 +1,27 @@
// PROFILE: ms_6_5
// Mesh shader: vertex and primitive outputs written per element, indices,
// partial (swizzled) output writes, the payload.
// ZCHECK: call void @dx.op.setMeshOutputCounts(i32 168
// ZCHECK: call void @dx.op.emitIndices(i32 169
// ZCHECK: call void @dx.op.storePrimitiveOutput.i32(i32 172
// ZCHECK: getMeshPayload
struct V { float4 pos : SV_Position; float2 uv : TEXCOORD0; float c[2] : COLOR; };
struct P { nointerpolation uint id : PRIMID; bool cull : SV_CullPrimitive; };
struct Payload { uint base; float scale[3]; };
[numthreads(4,1,1)]
[outputtopology("triangle")]
void main(out indices uint3 tris[2], out vertices V verts[4], out primitives P prims[2], in payload Payload pl, uint tid : SV_GroupIndex) {
SetMeshOutputCounts(4, 2);
verts[tid].pos = float4(tid, 0, 0, 1) * pl.scale[tid % 3];
verts[tid].uv.y = 1;
verts[tid].uv.x = 0;
verts[tid].c[1] = 2;
verts[tid].c[0] = 3;
if (tid < 2) {
tris[tid] = uint3(0, tid + 1, tid + 2);
P p;
p.id = pl.base + tid;
p.cull = tid == 1;
prims[tid] = p;
}
}

16
test/dxil/operators.hlsl Normal file
View File

@ -0,0 +1,16 @@
// PROFILE: cs_6_0
// Operator overloading: binary operators, [] and () (dxc's subset).
struct V2 {
float x, y;
V2 operator+(V2 o) { V2 r; r.x = x + o.x; r.y = y + o.y; return r; }
V2 operator*(float k) { V2 r; r.x = x * k; r.y = y * k; return r; }
bool operator==(V2 o) { return x == o.x && y == o.y; }
float operator[](uint i) { return i == 0 ? x : y; }
float operator()(float a, float b) { return x * a + y * b; }
};
RWStructuredBuffer<float> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_DispatchThreadID) {
V2 a; a.x = 1; a.y = 2; V2 b = a * 3.0;
V2 c = a + b; c = c + a;
o[i] = c[1] + c(1, 2) + (a == a ? 1 : 0);
}

View File

@ -0,0 +1,12 @@
// PROFILE: ps_6_0
// Intrinsics with out parameters.
// ZCHECK: @dx.op.splitDouble.f64(i32 102
// ZCHECK: @dx.op.unary.f32(i32 29,
double d;
float4 main(float4 x : X) : SV_Target {
float4 s, c; sincos(x, s, c);
float3 ip; float3 fr = modf(x.xyz, ip);
float e; float m = frexp(x.w, e);
uint lo, hi; asuint(d, lo, hi);
return s + c + float4(fr + ip, m * e) + lo + hi;
}

39
test/dxil/rayquery.hlsl Normal file
View File

@ -0,0 +1,39 @@
// PROFILE: cs_6_5
// FLAGS: -E main
// RayQuery: allocated once in the prologue, its type flags as the
// allocation's constant flags; state reads by row / column / component.
// ZCHECK: call i32 @dx.op.allocateRayQuery(i32 178, i32 1)
// ZCHECK: @dx.op.rayQuery_TraceRayInline(i32 179
// ZCHECK: @dx.op.rayQuery_Proceed.i1(i32 180
// ZCHECK: @dx.op.rayQuery_StateScalar.i32(i32 185
// ZCHECK: @dx.op.rayQuery_StateVector.f32(i32 194, i32 {{.*}}, i8 1)
// ZCHECK: @dx.op.rayQuery_StateMatrix.f32(i32 188, i32 {{.*}}, i32 0, i8 3)
// ZCHECK: @dx.op.rayQuery_Abort(i32 181
// ZCHECK: i32 16, i32 0, !{{.*}}
RaytracingAccelerationStructure scene : register(t0);
RWStructuredBuffer<float4> output : register(u0);
void start(RayQuery<RAY_FLAG_FORCE_OPAQUE> q, RayDesc ray) {
q.TraceRayInline(scene, RAY_FLAG_NONE, 0xFF, ray);
}
[numthreads(8, 1, 1)]
void main(uint3 id : SV_DispatchThreadID) {
RayDesc ray = { float3(id), 0.0, float3(0, 0, 1), 100.0 };
RayQuery<RAY_FLAG_FORCE_OPAQUE> q;
start(q, ray);
while (q.Proceed()) {
if (q.CandidateType() == CANDIDATE_NON_OPAQUE_TRIANGLE)
q.CommitNonOpaqueTriangleHit();
else
q.CommitProceduralPrimitiveHit(q.RayTMin());
}
float4 r = 0;
if (q.CommittedStatus() == COMMITTED_TRIANGLE_HIT) {
r.xy = q.CommittedTriangleBarycentrics();
r.z = q.CommittedRayT() + q.CommittedInstanceIndex();
r.w = q.CommittedObjectToWorld4x3()[3][0];
}
q.Abort();
output[id.x] = r;
}

66
test/dxil/raytracing.hlsl Normal file
View File

@ -0,0 +1,66 @@
// PROFILE: lib_6_5
// Ray tracing shaders in a library: mangled entry functions taking their
// payload / attributes by pointer, resources as globals with handles from
// createHandleForLib, and RDAT matching dxc's.
// ZCHECK: define void @"\01?chit@@YAXUPayload@@UBuiltInTriangleIntersectionAttributes@@@Z"(%struct.Payload*
// ZCHECK: @dx.op.createHandleForLib.struct.RaytracingAccelerationStructure(i32 160
// ZCHECK: call void @dx.op.traceRay.struct.Payload(i32 157
// ZCHECK: call void @dx.op.callShader.struct.CallData(i32 159
// ZCHECK: call i1 @dx.op.reportHit.struct.Attr(i32 158
// ZCHECK: call void @dx.op.ignoreHit(i32 155)
// ZCHECK: call float @dx.op.objectToWorld.f32(i32 151, i32 0, i8 3)
// ZCHECK: !{i32 8, i32 10, i32 6, i32 20, i32 7, i32 8, i32 5, !{{.*}}}
struct Payload { float4 color; uint depth; };
struct Attr { float2 bary; };
struct CallData { float3 v; };
RaytracingAccelerationStructure scene : register(t0);
RWTexture2D<float4> output : register(u0);
[shader("raygeneration")]
void rgen() {
uint2 id = DispatchRaysIndex().xy;
float2 uv = (float2(id) + 0.5) / float2(DispatchRaysDimensions().xy);
RayDesc ray;
ray.Origin = float3(uv, 0);
ray.Direction = float3(0, 0, 1);
ray.TMin = 0.001;
ray.TMax = 1000;
Payload p = { float4(0, 0, 0, 0), 0 };
TraceRay(scene, RAY_FLAG_FORCE_OPAQUE, 0xFF, 0, 1, 0, ray, p);
CallData c = { p.color.rgb };
CallShader(0, c);
output[id] = float4(c.v, 1);
}
[shader("closesthit")]
void chit(inout Payload p, in BuiltInTriangleIntersectionAttributes a) {
float3x4 m = ObjectToWorld3x4();
p.color = float4(a.barycentrics, RayTCurrent(), m[0][3]) + WorldRayDirection().xyzz;
p.depth = InstanceID() + PrimitiveIndex() + HitKind() + GeometryIndex();
}
[shader("miss")]
void miss(inout Payload p) {
p.color = float4(WorldRayOrigin(), RayTMin());
}
[shader("anyhit")]
void ahit(inout Payload p, in Attr a) {
if (a.bary.x > 0.5)
IgnoreHit();
if (RayFlags() & RAY_FLAG_CULL_BACK_FACING_TRIANGLES)
AcceptHitAndEndSearch();
p.depth += 1;
}
[shader("intersection")]
void isect() {
Attr a = { ObjectRayOrigin().xy };
ReportHit(RayTCurrent() * 0.5, 0, a);
}
[shader("callable")]
void call(inout CallData c) {
c.v *= 2;
}

View File

@ -0,0 +1,14 @@
// PROFILE: ps_6_0
// Resource arrays are register ranges; elements get handles where used.
// ZCHECK: createHandle(i32 57, i8 0, i32 0, i32 3, i1 false)
// ZCHECK: createHandle(i32 57, i8 0, i32 0, i32 {{.*}}, i1 true)
// ZCHECK: ]* undef, !"", i32 0, i32 1, i32 4, i32 2, i32 0,
// ZCHECK: [2 x %struct.SamplerState]* undef
Texture2D ts[4] : register(t1);
SamplerState ss[2] : register(s0);
RWStructuredBuffer<float> bufs[3] : register(u0);
float4 main(float2 uv : UV, uint i : I) : SV_Target {
float4 c = ts[2].Sample(ss[1], uv) + ts[NonUniformResourceIndex(i)].Sample(ss[0], uv);
bufs[1][0] = c.x;
return c + bufs[i][3];
}

View File

@ -0,0 +1,10 @@
// PROFILE: ps_6_0
// Resources passed to functions and held in locals (inlined to handles).
// ZCHECK: @dx.op.sample.f32(i32 60
Texture2D<float4> t0 : register(t0);
Texture2D<float4> t1 : register(t1);
SamplerState s : register(s0);
StructuredBuffer<float> b0 : register(t2);
float4 tap(Texture2D<float4> t, SamplerState ss, float2 uv) { return t.Sample(ss, uv); }
float rd(StructuredBuffer<float> b, uint i) { return b[i]; }
float4 main(float2 uv : UV) : SV_Target { Texture2D<float4> loc = t1; return tap(t0, s, uv) + tap(loc, s, uv * 2) + rd(b0, 3); }

View File

@ -0,0 +1,10 @@
// PROFILE: ps_6_0
// Root signatures from the RootSignature attribute (a macro of
// concatenated strings): an RTS0 part matching dxc's (version 1.1).
// ZCHECK: define void @main()
#define RS "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), " \
"CBV(b0), DescriptorTable(SRV(t0), visibility=SHADER_VISIBILITY_PIXEL), StaticSampler(s0)"
cbuffer C : register(b0) { float4 k; };
Texture2D t : register(t0); SamplerState s : register(s0);
[RootSignature(RS)]
float4 main(float2 uv : TEXCOORD) : SV_Target { return t.Sample(s, uv) * k; }

15
test/dxil/rov.hlsl Normal file
View File

@ -0,0 +1,15 @@
// PROFILE: ps_6_6
// Rasterizer-ordered views and globallycoherent UAVs: resource metadata,
// annotateHandle properties and the ROVs shader flag.
// ZCHECK: Raster Ordered UAVs
// ZCHECK: ResourceProperties { i32 20491, i32 0 }
// ZCHECK: ResourceProperties { i32 12290, i32 1033 }
// ZCHECK: i32 2, i1 false, i1 false, i1 true,
// ZCHECK: i32 11, i1 true, i1 false, i1 false,
globallycoherent RWByteAddressBuffer buffer1 : register(u0);
RasterizerOrderedTexture2D<float4> rov : register(u1);
float4 main(float4 p : SV_Position) : SV_Target {
rov[uint2(p.xy)] += buffer1.Load(0);
return rov[uint2(p.xy)];
}

View File

@ -0,0 +1,2 @@
// PROFILE: vs_6_0
float4 main() : SV_Position { return 1; }

5
test/dxil/sig_order.hlsl Normal file
View File

@ -0,0 +1,5 @@
// PROFILE: vs_6_0
// Return value first, then parameters; inout packs its output side; clip
// distances and matrices span rows.
struct O { float4 a : A; float2 b[2] : B; };
float4 main(in float3 x : X, out float y : Y, inout float2 z : Z, float4x2 m : M, row_major float2x3 rm : RM, out O o, uint iid : SV_InstanceID, out float4 p : SV_Position, out float cd[2] : SV_ClipDistance) : R { y = x.x; z += 1; o.a = m[0].xyxy+rm[0].xyzx; o.b[0] = 1; o.b[1] = iid; p = 1; cd[0]=1; cd[1]=2; return 2; }

View File

@ -0,0 +1,5 @@
// PROFILE: ps_6_0
// ZCHECK: call void @dx.op.discard(i32 82, i1 true)
// ZCHECK: @dx.op.unary.f32(i32 83,
struct PSIn { float4 pos : SV_Position; float2 uv : TEXCOORD0; nointerpolation uint id : TEXCOORD1; float3 n : NORMAL; };
float4 main(PSIn i, bool ff : SV_IsFrontFace) : SV_Target { if (i.uv.x < 0) discard; return float4(i.n * (ff ? 1 : -1), i.uv.y + i.id + ddx(i.uv.x)); }

4
test/dxil/sig_ps_sv.hlsl Normal file
View File

@ -0,0 +1,4 @@
// PROFILE: ps_6_0
// Interpolation modifiers, shadow (SV_SampleIndex) and unpacked outputs.
// ZCHECK: @dx.op.sampleIndex.i32(i32 90)
float4 main(float4 p : SV_Position, centroid float c : C, noperspective float2 np : NP, sample float s : S, uint pid : SV_PrimitiveID, uint si : SV_SampleIndex, out float d : SV_Depth, out float4 t1 : SV_Target1, out uint cov : SV_Coverage) : SV_Target0 { d = 0.5; t1 = 1; cov = 3; return c + np.x + pid + si + s+p.x; }

View File

@ -0,0 +1,15 @@
// PROFILE: ps_6_0
// SV_Target arrays split into one element per render target.
uint i;
float4 main(int4 a : A, out float4 o[2] : SV_TARGET, out float4 o2[2][2] : SV_TARGET2) : SV_TARGET7
{
o[0] = a+2;
o[1] = a+3;
o[i] = a+10;
o2[0][0] = a+5;
o2[0][1] = a+6;
o2[1][0] = a+7;
o2[1][1] = a+8;
o2[i][i] = a + 12;
return a + 16;
}

5
test/dxil/sig_types.hlsl Normal file
View File

@ -0,0 +1,5 @@
// PROFILE: vs_6_0
// bool and min16float elements.
// ZCHECK: @dx.op.loadInput.f16(
struct O { float4 p : SV_Position; bool b : B; min16float h : H; int2 i : I; };
O main(bool bi : BI, min16float2 hi : HI, float4 v : SV_Position) { O o; o.p = v; o.b = bi; o.h = hi.x; o.i = 3; return o; }

View File

@ -0,0 +1,5 @@
// PROFILE: vs_6_0
cbuffer C : register(b0) { float4x4 mvp; };
struct VSIn { float3 pos : POSITION; float2 uv : TEXCOORD0; float3 n : NORMAL; uint id : SV_VertexID; };
struct VSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; nointerpolation uint id : TEXCOORD1; float3 n : NORMAL; };
VSOut main(VSIn i) { VSOut o; o.pos = mul(mvp, float4(i.pos, 1)); o.uv = i.uv; o.id = i.id; o.n = i.n; return o; }

View File

@ -0,0 +1,8 @@
// PROFILE: vs_6_0
// Static globals are initialized on entry; float constants keep their value.
// ZCHECK: store float 3.000000e+00
// ZCHECK: store float 5.000000e+00
// ZCHECK: fadd float {{.*}}, 1.500000e+00
static const float2 offs[2] = { float2(1, 2), float2(3, 4) };
static float g = 5;
float4 main(uint id : SV_VertexID) : SV_Position { g += 1.5; return float4(offs[id], g, 1); }

View File

@ -0,0 +1,5 @@
// PROFILE: cs_6_0
// Static locals: private globals initialized on entry.
RWStructuredBuffer<int> o : register(u0);
int next() { static int counter = 10; counter += 1; return counter; }
[numthreads(1,1,1)] void main() { static const float k[3] = {1, 2, 3}; o[0] = next() + next() + (int)k[2]; }

16
test/dxil/status.hlsl Normal file
View File

@ -0,0 +1,16 @@
// PROFILE: ps_6_0
// Status arguments (sparse feedback) and CheckAccessFullyMapped.
// ZCHECK: checkAccessFullyMapped.i32(i32 71
Texture2D<float4> t : register(t0);
Buffer<float4> b : register(t2);
SamplerState s : register(s0);
float4 main(float2 uv : UV) : SV_Target {
uint st0, st1, st6;
float4 a = t.Sample(s, uv, int2(1, 0), 0.5, st0);
if (!CheckAccessFullyMapped(st0)) a = 0;
float4 l = t.Load(int3(1, 2, 0), int2(0, 0), st1);
bool m = CheckAccessFullyMapped(st1);
float4 bb = b.Load(3, st6);
bool n = CheckAccessFullyMapped(st6);
return a + (m ? l : 1) + (n ? bb : 2);
}

14
test/dxil/subobjects.hlsl Normal file
View File

@ -0,0 +1,14 @@
// PROFILE: lib_6_5
// State object subobjects go to the RDAT subobject table (checked against
// dxc's RDAT).
// ZCHECK: define void @"\01?b@@YAXUP@@@Z"
StateObjectConfig soc = { STATE_OBJECT_FLAGS_ALLOW_LOCAL_DEPENDENCIES_ON_EXTERNAL_DEFINITONS };
SubobjectToExportsAssociation sea = { "rsc", "a;b;foo;c" };
SubobjectToExportsAssociation sea2 = { "rsc", ";" };
RaytracingShaderConfig rsc = { 128, 64 };
RaytracingPipelineConfig rpc = { 512 };
TriangleHitGroup trHitGt = { "a", "b" };
ProceduralPrimitiveHitGroup ppHitGt = { "a", "b", "c"};
RaytracingPipelineConfig1 rpc1 = { 32, RAYTRACING_PIPELINE_FLAG_SKIP_TRIANGLES };
struct P { float4 c; };
[shader("miss")] void b(inout P p) { p.c = 1; }

6
test/dxil/sv_pixel.hlsl Normal file
View File

@ -0,0 +1,6 @@
// PROFILE: ps_6_8
// Pixel system values: clip distances in, barycentrics, coverage in and
// out, ViewID, shading rate, stencil ref.
struct I { float4 pos : SV_Position; float2 c0 : SV_ClipDistance0; float c1 : SV_ClipDistance1; noperspective float3 b2 : SV_Barycentrics1; };
struct O { float4 c : SV_Target; uint cov : SV_Coverage; uint st : SV_StencilRef; };
O main(I i, float3 b : SV_Barycentrics, uint cov : SV_Coverage, uint v : SV_ViewID, uint sr : SV_ShadingRate) { O o; o.c = float4(b + i.b2, i.c0.y + i.c1 + v + sr); o.cov = cov; o.st = 1; return o; }

5
test/dxil/sv_vertex.hlsl Normal file
View File

@ -0,0 +1,5 @@
// PROFILE: vs_6_8
// Vertex system values: clip/cull distances, ViewID, start vertex and
// instance, viewport / render target index, shading rate.
struct O { float4 pos : SV_Position; float2 c0 : SV_ClipDistance0; float c1 : SV_ClipDistance1; float cu : SV_CullDistance; uint vp : SV_ViewportArrayIndex; uint rt : SV_RenderTargetArrayIndex; uint sr : SV_ShadingRate; };
O main(uint v : SV_ViewID, uint sv : SV_StartVertexLocation, uint si : SV_StartInstanceLocation) { O o = (O)0; o.pos = v + sv + si; o.c0 = 1; o.c1 = 2; return o; }

18
test/dxil/switch.hlsl Normal file
View File

@ -0,0 +1,18 @@
// PROFILE: cs_6_0
// switch: fallthrough, default, break, continue to the enclosing loop.
// ZCHECK: switch i32 {{.*}}, label
RWStructuredBuffer<int> o : register(u0);
[numthreads(4,1,1)] void main(uint i : SV_GroupIndex) {
int r = 0;
for (int k = 0; k < 3; k++) {
switch (i + k) {
case 0: r += 1; break;
case 1:
case 2: r += 2;
case 3: r += 3; break;
default: if (r > 4) continue; r -= 1;
}
}
switch (r) { case 7: o[1] = 7; }
o[i] = r;
}

9
test/dxil/tbuffer.hlsl Normal file
View File

@ -0,0 +1,9 @@
// PROFILE: cs_6_0
// tbuffer blocks and TextureBuffer<S>: TBuffer SRVs read a register at a
// time (cbuffer layout).
// ZCHECK: call %dx.types.ResRet.i32 @dx.op.bufferLoad.i32(i32 68
struct S { float4 a; float b; float3 c; };
tbuffer TB : register(t0) { float4 x; float y; S s; };
TextureBuffer<S> tbs : register(t1);
RWStructuredBuffer<float4> o : register(u0);
[numthreads(1,1,1)] void main() { o[0] = x * y + s.a + tbs.a * tbs.b + float4(tbs.c, 1); }

23
test/dxil/templates.hlsl Normal file
View File

@ -0,0 +1,23 @@
// PROFILE: cs_6_0
// Templates (function, class, variable; deduction, defaults, specializations) and methods.
template<typename T> T square(T x) { return x * x; }
template<typename T, int N> vector<T, N> scale(vector<T, N> v, T k) { return v * k; }
template<typename T> struct Pair { T a; T b; T sum() { return a + b; } };
template<typename T, uint N = 4> struct Arr { T v[N]; T get(uint i) { return v[i]; } };
template<typename T> T first(Pair<T> p) { return p.a; }
RWStructuredBuffer<float> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_DispatchThreadID) {
Pair<float> p; p.a = 1; p.b = 2;
Arr<int> a; a.v[0] = 3; a.v[1] = 4; a.v[2] = 5; a.v[3] = 6;
o[i] = square(2.0f) + square(3) + scale(float3(1, 2, 3), 2.0f).z + p.sum() + a.get(2) + first(p) + square<uint>(2);
}
template <class, class> static const bool is_same_v = false;
template <class T> static const bool is_same_v<T, T> = true;
template<typename T> struct Box { T v; };
template<> struct Box<int> { int v; int extra; };
struct Base { float b; float twice() { return b * 2; } };
struct Derived : Base { float d; };
[numthreads(1,1,1)] void more(uint i : SV_DispatchThreadID) {
Box<int> bi; bi.extra = 2; Derived dv; dv.b = 3;
o[i] = is_same_v<int, int> + is_same_v<int, float> + bi.extra + dv.twice();
}

43
test/dxil/templates2.hlsl Normal file
View File

@ -0,0 +1,43 @@
// PROFILE: cs_6_0
// More templates: `S<T>::member`, partial specialization through
// matrix<T, N, M>, the injected class name, member function templates,
// SFINAE (enable_if), out-of-line member definitions (plain, static and
// of class templates), alias template deduction, argument-dependent
// lookup.
// ZCHECK: @dx.op.bufferStore.f32
template <bool C, typename T> struct enable_if {};
template <typename T> struct enable_if<true, T> { using type = T; };
template <typename M> struct traits;
template <typename T, int N, int K> struct traits<matrix<T, N, K> > {
static const uint Count = N * K;
};
namespace ns {
template <typename T, int N> struct Vec {
T v[N];
Vec scaled(T k);
template <int L> Vec Shifted() { Vec r; r.v = v; r.v[0] += L; return r; }
template <int L> static Vec Make(T x) { Vec r; for (int i = 0; i < N; i++) r.v[i] = x * L; return r; }
};
template <typename T, int N> Vec<T, N> Vec<T, N>::scaled(T k) {
Vec r; for (int i = 0; i < N; i++) r.v[i] = v[i] * k; return r;
}
template <typename T> using Vec2 = Vec<T, 2>;
template <typename T> T head(Vec2<T> x) { return x.v[0]; }
}
struct S { float a; float get(float k); static float twice(float x); };
float S::get(float k) { return a * k; }
float S::twice(float x) { return x * 2; }
template <typename T> typename enable_if<(sizeof(T) == 4), T>::type pick(T x) { return x; }
template <typename T> typename enable_if<(sizeof(T) == 8), T>::type pick(T x) { return x * 2; }
RWStructuredBuffer<float> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_DispatchThreadID) {
S s; s.a = 3;
ns::Vec2<float> v = ns::Vec2<float>::Make<3>(2);
ns::Vec<float, 2> g = v.scaled(2).Shifted<1>();
o[i] = traits<float2x3>::Count + s.get(2) + S::twice(1) + head(v) + g.v[0] + pick(1.0f);
}

37
test/dxil/textures.hlsl Normal file
View File

@ -0,0 +1,37 @@
// PROFILE: ps_6_0
// Texture and sampler operations; argument layout as dxc emits it.
// ZCHECK: @dx.op.sample.f32(i32 60, %dx.types.Handle {{.*}}, float {{.*}}, float undef, float undef, i32 1, i32 2, i32 undef, float undef)
// ZCHECK: @dx.op.sampleLevel.f32(i32 62,
// ZCHECK: @dx.op.sampleBias.f32(i32 61,
// ZCHECK: @dx.op.sampleGrad.f32(i32 63,
// ZCHECK: @dx.op.sampleCmp.f32(i32 64,
// ZCHECK: @dx.op.sampleCmpLevelZero.f32(i32 65,
// ZCHECK: @dx.op.textureLoad.f32(i32 66, %dx.types.Handle {{.*}}, i32 0, i32 1, i32 2, i32 undef, i32 undef, i32 undef, i32 undef)
// ZCHECK: @dx.op.textureLoad.i32(i32 66,
// ZCHECK: @dx.op.bufferLoad.f32(i32 68,
// ZCHECK: @dx.op.textureGather.f32(i32 73, {{.*}}, i32 1, i32 1, i32 1)
// ZCHECK: @dx.op.textureGatherCmp.f32(i32 74,
// ZCHECK: @dx.op.getDimensions(i32 72, %dx.types.Handle {{.*}}, i32 1)
// ZCHECK: @dx.op.calculateLOD.f32(i32 81,
// ZCHECK: @dx.op.textureStore.f32(i32 67,
// ZCHECK: !{i32 1, %struct.SamplerComparisonState* undef, !"", i32 0, i32 1, i32 1, i32 1, null}
Texture2D<float4> t2 : register(t0);
Texture2DArray<float> t2a : register(t1);
TextureCube tc : register(t2);
Texture2DMS<float4> tms : register(t3);
Texture3D<uint2> t3 : register(t4);
Buffer<float4> buf : register(t5);
RWTexture2D<float4> rw : register(u0);
SamplerState s : register(s0);
SamplerComparisonState sc : register(s1);
float4 main(float2 uv : UV) : SV_Target {
float4 r = t2.Sample(s, uv) + t2.Sample(s, uv, int2(1, 2)) + t2.SampleLevel(s, uv, 2) + t2.SampleBias(s, uv, 0.5) + t2.SampleGrad(s, uv, uv, uv);
r.x += t2a.SampleCmp(sc, float3(uv, 1), 0.5) + t2a.SampleCmpLevelZero(sc, float3(uv, 1), 0.5);
r += tc.Sample(s, uv.xyx) + t2.Load(int3(1, 2, 0)) + tms.Load(int2(1, 1), 2) + t3[uint3(1,2,3)].x + buf[3] + buf.Load(2);
r += t2.Gather(s, uv) + t2.GatherGreen(s, uv, int2(1, 1)) + t2a.GatherCmp(sc, float3(uv, 0), 0.5);
uint w, h, l; t2.GetDimensions(1, w, h, l);
float fw, fh; rw.GetDimensions(fw, fh);
r.x += w + h + l + fw + fh + t2.CalculateLevelOfDetail(s, uv);
rw[uint2(1, 2)] = r; r += rw[uint2(3,4)];
return r;
}

26
test/dxil/unroll.hlsl Normal file
View File

@ -0,0 +1,26 @@
// PROFILE: ps_6_0
// Loops unroll so texel offsets become constants (as dxc requires).
// ZCHECK: @dx.op.sample.f32(i32 60, {{.*}}, i32 -1, i32 -2, i32 undef, float undef)
// ZCHECK: @dx.op.sample.f32(i32 60, {{.*}}, i32 0, i32 -2, i32 undef, float undef)
// ZCHECK: @dx.op.sample.f32(i32 60, {{.*}}, i32 1, i32 -2, i32 undef, float undef)
// ZCHECK: @dx.op.sample.f32(i32 60, {{.*}}, i32 -1, i32 0, i32 undef, float undef)
// ZCHECK: @dx.op.sample.f32(i32 60, {{.*}}, i32 1, i32 2, i32 undef, float undef)
// ZCHECK: @dx.op.sampleLevel.f32(i32 62, {{.*}}, i32 -1, i32 0, i32 undef, float 0.000000e+00)
// ZCHECK: @dx.op.sampleLevel.f32(i32 62, {{.*}}, i32 2, i32 0, i32 undef, float 0.000000e+00)
Texture2D t : register(t0);
SamplerState s : register(s0);
static const int R = 1;
float4 main(float2 uv : UV, uint n : N) : SV_Target {
float4 c = 0;
// Nested loops whose offsets need constants, with a static const bound.
for (int y = -R; y <= R; y++)
for (int x = -R; x <= R; x++)
c += t.Sample(s, uv, int2(x, y * 2));
// [unroll] with a step other than one and a shifted offset.
[unroll] for (uint i = 0; i < 6; i += 3) c += t.SampleLevel(s, uv, 0, int2(i - 1, 0));
// Kept as loops: [loop], a break, a run-time bound.
[loop] for (int j = 0; j < 4; j++) c.x += j;
for (int k = 0; k < 4; k++) { if (c.y > 2) break; c.y += k; }
for (uint m = 0; m < n; m++) c.z += m;
return c;
}

14
test/dxil/wave.hlsl Normal file
View File

@ -0,0 +1,14 @@
// PROFILE: cs_6_0
// Wave and quad intrinsics, as dxc emits them.
// ZCHECK: @dx.op.waveActiveOp.i32(i32 119, i32 {{.*}}, i8 2, i8 1)
// ZCHECK: @dx.op.waveAllOp(i32 135
// ZCHECK: @dx.op.quadOp.f32(i32 123
RWStructuredBuffer<uint4> o : register(u0);
[numthreads(64,1,1)] void main(uint i : SV_GroupIndex) {
uint4 b = WaveActiveBallot(i > 3);
int s = WaveActiveSum((int)i) + WavePrefixProduct((int)i) + WaveActiveMax((int)i);
uint u = WaveActiveMin(i) + WaveActiveBitXor(i) + WaveReadLaneAt(i, 2) + WaveReadLaneFirst(i) + WaveActiveCountBits(i > 1) + WavePrefixCountBits(i < 9);
bool f = WaveIsFirstLane() && WaveActiveAnyTrue(i == 0) && WaveActiveAllTrue(i < 100) && WaveActiveAllEqual(i);
float q = QuadReadAcrossX((float)i) + QuadReadLaneAt((float)i, 1);
o[i] = b + s + u + f + WaveGetLaneIndex() + WaveGetLaneCount() + (uint)q;
}

64
test/oracle/codegen.sh Normal file
View File

@ -0,0 +1,64 @@
#!/bin/sh
# Codegen oracle: compiles every dxc-valid corpus file with zdxc and runs the
# validator on what it emits. Files zdxc cannot compile yet ("code
# generation: ... not supported yet") are counted as unsupported; any output
# the validator rejects is a bug.
#
# Usage: test/oracle/codegen.sh <path-to-zdxc> spirv|dxil
# (run test/oracle/parse.sh first to build the corpus list)
set -u
ZDXC=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
BACKEND=${2:-spirv}
DXC_BUILD=${DXC_BUILD:-../build}
SPIRV_VAL=$DXC_BUILD/oracle-spirv-tools/tools/spirv-val
DXV=$DXC_BUILD/bin/dxv
CACHE=zig-out/oracle/parse-valid.txt
[ -s "$CACHE" ] || { echo "run test/oracle/parse.sh first to build $CACHE"; exit 1; }
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
valid=0; invalid=0; unsupported=0; other=0; crashed=0
: > "$TMP/invalid"; : > "$TMP/reasons"; : > "$TMP/valid"; : > "$TMP/crashed"
while read -r f; do
flags=$(sh test/oracle/run_flags.sh "$f") || continue
is_spirv=0
case "$flags" in *-spirv*) is_spirv=1 ;; esac
if [ "$BACKEND" = spirv ]; then
[ $is_spirv = 1 ] || flags="$flags -spirv"
else
[ $is_spirv = 1 ] && continue
fi
# shellcheck disable=SC2086
"$ZDXC" -fno-color-diagnostics -no-warnings $flags "$f" -Fo "$TMP/out" > "$TMP/log" 2>&1
rc=$?
if [ $rc -ge 128 ]; then
crashed=$((crashed + 1)); echo "$f" >> "$TMP/crashed"
elif [ $rc = 0 ]; then
if [ "$BACKEND" = spirv ]; then
env=$(printf '%s\n' "$flags" | sed -n 's/.*-fspv-target-env=\([a-z0-9.]*\).*/\1/p'); env=$(printf "%s" "$env" | sed -e "s/spirv1/spv1/" -e "s/universal1/spv1/")
"$SPIRV_VAL" --target-env "${env:-vulkan1.0}" --relax-block-layout "$TMP/out" > "$TMP/val" 2>&1
else
"$DXV" "$TMP/out" > "$TMP/val" 2>&1
fi
if [ $? = 0 ]; then
valid=$((valid + 1)); echo "$f" >> "$TMP/valid"
else
invalid=$((invalid + 1))
echo "$f: $(grep -m1 -i "error" "$TMP/val")" >> "$TMP/invalid"
fi
elif grep -q "code generation" "$TMP/log"; then
unsupported=$((unsupported + 1))
grep -m1 "code generation" "$TMP/log" | sed -E 's/^.*code generation: //' >> "$TMP/reasons"
else
other=$((other + 1))
echo "$f: $(grep -m1 "error" "$TMP/log")" >> "$TMP/other"
fi
done < "$CACHE"
echo "most common unsupported constructs:"
sed -E "s/'[^']*'/'X'/g" "$TMP/reasons" | sort | uniq -c | sort -rn | head -"${SHOW:-15}"
if [ "$invalid" -gt 0 ]; then echo "INVALID OUTPUT:"; head -20 "$TMP/invalid"; fi
[ -s "$TMP/other" ] && { echo "front-end errors:"; head -5 "$TMP/other"; }
cp "$TMP/valid" "zig-out/oracle/codegen-$BACKEND-valid.txt"
cp "$TMP/invalid" "zig-out/oracle/codegen-$BACKEND-invalid.txt"
[ -s "$TMP/crashed" ] && { echo "CRASHED:"; cat "$TMP/crashed"; }
echo "oracle codegen ($BACKEND): $valid valid, $invalid INVALID, $crashed CRASHED, $unsupported unsupported, $other other errors"
[ "$invalid" -eq 0 ] && [ "$crashed" -eq 0 ]

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
# Print the dxc/zdxc flags taken from the first RUN line of an HLSL test: # Print the dxc/zdxc flags taken from the first RUN line of an HLSL test:
# -T, -E, -D, -spirv and -enable-16bit-types. Exits 1 if there is no -T. # -T, -E, -D, -spirv, -fspv-target-env and -enable-16bit-types. Exits 1 if
# there is no -T.
run=$(grep -m1 'RUN:' "$1") run=$(grep -m1 'RUN:' "$1")
target=$(printf '%s' "$run" | grep -oE -- '-T *[a-z]+_6_[0-9]+' | head -1 | sed 's/-T *//') target=$(printf '%s' "$run" | grep -oE -- '-T *[a-z]+_6_[0-9]+' | head -1 | sed 's/-T *//')
[ -n "$target" ] || exit 1 [ -n "$target" ] || exit 1
@ -9,4 +10,6 @@ defs=$(printf '%s' "$run" | grep -oE -- '-D *[A-Za-z_][A-Za-z0-9_]*(=[^ ]*)?' |
extra="" extra=""
printf '%s' "$run" | grep -q -- '-spirv' && extra="$extra -spirv" printf '%s' "$run" | grep -q -- '-spirv' && extra="$extra -spirv"
printf '%s' "$run" | grep -q -- '-enable-16bit-types' && extra="$extra -enable-16bit-types" printf '%s' "$run" | grep -q -- '-enable-16bit-types' && extra="$extra -enable-16bit-types"
env=$(printf '%s' "$run" | grep -oE -- '-fspv-target-env=[a-z0-9.]+' | head -1)
[ -n "$env" ] && extra="$extra $env"
echo "-T $target $entry $extra $defs" echo "-T $target $entry $extra $defs"

34
test/oracle/sema.sh Normal file
View File

@ -0,0 +1,34 @@
#!/bin/sh
# Sema oracle (no false errors): every corpus file that dxc compiles under
# -HV 2021 must pass zdxc's semantic analysis without errors. Files whose
# only errors are "not supported yet" (milestone 0.2 features) are counted
# separately.
#
# Usage: test/oracle/sema.sh <path-to-zdxc> (run test/oracle/parse.sh first)
set -u
ZDXC=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
CACHE=zig-out/oracle/parse-valid.txt
[ -s "$CACHE" ] || { echo "run test/oracle/parse.sh first to build $CACHE"; exit 1; }
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
pass=0; later=0; fail=0
while read -r f; do
flags=$(sh test/oracle/run_flags.sh "$f") || continue
# shellcheck disable=SC2086
if "$ZDXC" -zdxc-sema -fno-color-diagnostics -no-warnings $flags "$f" > "$TMP/out" 2>&1; then
pass=$((pass + 1))
elif ! grep "error:" "$TMP/out" | grep -v "too many errors emitted" | grep -qv "not supported yet"; then
later=$((later + 1))
else
fail=$((fail + 1))
echo "$f" >> "$TMP/failed"
grep -m1 "error:" "$TMP/out" | sed -E 's/^.*error: //' >> "$TMP/errors"
fi
done < "$CACHE"
if [ "$fail" -gt 0 ]; then
echo "most common first errors:"
sed -E "s/'[^']*'/'X'/g; s/[0-9]+/N/g" "$TMP/errors" | sort | uniq -c | sort -rn | head -${SHOW:-25}
cp "$TMP/failed" zig-out/oracle/sema-failed.txt
fi
echo "oracle sema: $pass clean, $later need milestone 0.2 features, $fail false errors (of $(wc -l < "$CACHE" | tr -d ' ') dxc-valid files)"
[ "$fail" -eq 0 ]

View File

@ -0,0 +1,7 @@
#!/bin/sh
# First Sema error of each file listed in zig-out/oracle/sema-failed.txt.
while read -r f; do
flags=$(sh test/oracle/run_flags.sh "$f") || continue
# shellcheck disable=SC2086
"$1" -zdxc-sema -fno-color-diagnostics -no-warnings $flags "$f" 2>&1 | grep -m1 "error:" | sed -E "s#^[^ ]*: error: #$(basename "$f"): #"
done < zig-out/oracle/sema-failed.txt

75
test/oracle/verify.sh Normal file
View File

@ -0,0 +1,75 @@
#!/bin/sh
# Expected-diagnostics oracle: runs zdxc over dxc's SemaHLSL `-verify` tests
# (HLSL 2021 only) and compares the lines zdxc reports errors on with the
# lines the tests expect errors on.
#
# caught expected error lines zdxc also reports an error on
# missed expected error lines zdxc is silent on
# false lines zdxc reports an error on that expect none
#
# Files where zdxc reports a "not supported yet" (milestone 0.2) error are
# counted separately and left out of the line totals.
#
# Usage: test/oracle/verify.sh <path-to-zdxc> [corpus-dir]
# SHOW=N number of most common missed / false messages to print
set -u
ZDXC=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
CORPUS=${2:-../tools/clang/test/SemaHLSL}
HERE=$(cd "$(dirname "$0")" && pwd)
OUT=zig-out/oracle
mkdir -p "$OUT"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
: > "$TMP/missed"; : > "$TMP/false"; : > "$TMP/files"
files=0; exact=0; later=0; skipped=0; caught=0; missed=0; false=0
for f in $(grep -rl --include='*.hlsl' -e '-verify' "$CORPUS" | sort); do
run=$(grep -m1 'RUN:.*-verify' "$f" | sed -E 's#(^| )/([TED]) *#\1-\2 #g')
hv=$(printf '%s' "$run" | grep -oE -- '-HV *[0-9a-z]+' | sed 's/-HV *//')
target=$(printf '%s' "$run" | grep -oE -- '-T *[a-z]+_[0-9]+_[0-9]+' | head -1 | sed 's/-T *//')
if [ -n "$hv" ] && [ "$hv" != 2021 ] || [ -z "$target" ]; then
skipped=$((skipped + 1)); continue
fi
flags="-T $target"
flags="$flags $(printf '%s' "$run" | grep -oE -- '-E *[A-Za-z_][A-Za-z0-9_]*' | head -1 | sed 's/-E */-E /')"
flags="$flags $(printf '%s' "$run" | grep -oE -- '-D *[A-Za-z_][A-Za-z0-9_]*(=[^ ]*)?' | sed 's/-D */-D/' | tr '\n' ' ')"
flags="$flags $(printf '%s' "$run" | grep -oE -- ' -(spirv|enable-16bit-types|W[a-z0-9-]+)' | tr '\n' ' ')"
awk -f "$HERE/verify_expect.awk" "$f" > "$TMP/expect"
# shellcheck disable=SC2086
"$ZDXC" -zdxc-sema -fno-color-diagnostics -ferror-limit=0 $flags "$f" > "$TMP/out" 2>&1
files=$((files + 1))
if grep -q "error: .*not supported yet" "$TMP/out"; then
later=$((later + 1)); continue
fi
# Lines zdxc reports errors on, in this file only.
grep -F "$f:" "$TMP/out" | grep -E '^[^ ]+:[0-9]+:[0-9]+: (fatal )?error: ' |
sed -E "s#^[^ ]+:([0-9]+):[0-9]+: (fatal )?error: (.*)#\1 \3#" > "$TMP/got"
awk -v name="$(basename "$f")" -v missed="$TMP/missed" -v falsef="$TMP/false" '
FILENAME == ARGV[1] {
if ($1 == "error") { line = $2; $1 = ""; $2 = ""; sub(/^ +/, ""); if (!(line in want)) want[line] = $0 }
else warn[$2] = 1
next
}
{ line = $1; $1 = ""; sub(/^ +/, ""); if (!(line in got)) got[line] = $0 }
END {
c = m = x = 0
for (l in want) if (l in got) c++; else { m++; print name ":" l ": " want[l] >> missed }
for (l in got) if (!(l in want)) { x++; print name ":" l ": " got[l] (l in warn ? " [dxc: warning]" : "") >> falsef }
print c, m, x
}' "$TMP/expect" "$TMP/got" > "$TMP/counts"
read -r c m x < "$TMP/counts"
caught=$((caught + c)); missed=$((missed + m)); false=$((false + x))
[ "$m" -eq 0 ] && [ "$x" -eq 0 ] && exact=$((exact + 1))
echo "$m $x $f" >> "$TMP/files"
done
summarize() {
sed -E 's/^[^ ]+: //; s/'"'"'[^'"'"']*'"'"'/'"'"'X'"'"'/g; s/[0-9]+/N/g' "$1" | sort | uniq -c | sort -rn | head -"${SHOW:-15}"
}
echo "most common missed errors (expected by dxc, not reported):"; summarize "$TMP/missed"
echo "most common false errors (reported, not expected):"; summarize "$TMP/false"
cp "$TMP/missed" "$OUT/verify-missed.txt"
cp "$TMP/false" "$OUT/verify-false.txt"
sort -rn "$TMP/files" > "$OUT/verify-files.txt"
total=$((caught + missed))
pct=0; [ "$total" -gt 0 ] && pct=$((caught * 100 / total))
echo "oracle verify: $files files ($skipped other -HV skipped), $exact exact, $later need milestone 0.2"
echo " error lines: $caught/$total caught ($pct%), $missed missed, $false false"

View File

@ -0,0 +1,25 @@
# Print the diagnostics a clang `-verify` test expects in its own file, one
# per line: "<severity> <line> <message>". Handles `expected-error`,
# `expected-warning` (optionally `-re`), `@+N` / `@-N` / `@N` line offsets
# and repeat counts; markers aimed at other files (`@file:N`) and notes are
# skipped.
{
rest = $0
while (match(rest, /expected-(error|warning)(-re)?(@[^ {]*)?( +[0-9]+)? *\{\{/)) {
marker = substr(rest, RSTART, RLENGTH)
rest = substr(rest, RSTART + RLENGTH)
sev = (marker ~ /^expected-error/) ? "error" : "warning"
line = NR
if (match(marker, /@[^ {]*/)) {
off = substr(marker, RSTART + 1, RLENGTH - 1)
if (off ~ /^\+[0-9]+$/) line = NR + substr(off, 2)
else if (off ~ /^-[0-9]+$/) line = NR - substr(off, 2)
else if (off ~ /^[0-9]+$/) line = off + 0
else continue
}
msg = rest
end = index(msg, "}}")
if (end > 0) msg = substr(msg, 1, end - 1)
print sev, line, msg
}
}

View File

@ -0,0 +1,16 @@
// PROFILE: as_6_5
// ENV: vulkan1.3
// Amplification shader: the groupshared payload becomes TaskPayloadWorkgroupEXT
// storage, DispatchMesh OpEmitMeshTasksEXT.
// ZCHECK: OpEntryPoint TaskEXT
// ZCHECK: %pl = OpVariable {{.*}} TaskPayloadWorkgroupEXT
// ZCHECK: OpEmitMeshTasksEXT
struct Payload { uint base; float scale[2]; uint ids[8]; };
groupshared Payload pl;
[numthreads(8,1,1)]
void main(uint tid : SV_GroupIndex) {
pl.ids[tid] = tid * 2;
if (tid == 0) { pl.base = 7; pl.scale[0] = 1; pl.scale[1] = 2; }
GroupMemoryBarrierWithGroupSync();
DispatchMesh(2, 1, 1, pl);
}

22
test/spirv/atomics.hlsl Normal file
View File

@ -0,0 +1,22 @@
// PROFILE: cs_6_0
// Atomics on groupshared memory, buffers and texels.
// ZCHECK: OpAtomicIAdd %uint {{.*}} %uint_2 %uint_0 %uint_1
// ZCHECK: OpImageTexelPointer
// ZCHECK: OpAtomicCompareExchange
groupshared uint cnt;
groupshared int mx[4];
RWStructuredBuffer<uint> sb : register(u0);
RWBuffer<uint> tb : register(u1);
RWTexture2D<int> tex : register(u2);
RWByteAddressBuffer rb : register(u3);
[numthreads(64,1,1)] void main(uint i : SV_GroupIndex) {
uint old, o2; int o3;
InterlockedAdd(cnt, 1, old);
InterlockedMax(mx[i & 3], (int)i);
InterlockedCompareExchange(cnt, 5, 6, o2);
InterlockedOr(sb[i], 2);
InterlockedMin(tb[i], i, o2);
InterlockedExchange(tex[uint2(i, 1)], 3, o3);
InterlockedCompareStore(sb[0], 1, 2);
sb[1] = old + o2 + o3;
}

8
test/spirv/barriers.hlsl Normal file
View File

@ -0,0 +1,8 @@
// PROFILE: cs_6_0
// Memory barriers (device, group, all; with and without group sync).
RWStructuredBuffer<uint4> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) {
AllMemoryBarrier(); AllMemoryBarrierWithGroupSync(); DeviceMemoryBarrier(); DeviceMemoryBarrierWithGroupSync(); GroupMemoryBarrier();
o[0] = uint4(firstbitlow(i), firstbithigh(i), firstbithigh((int)i), f32tof16(asfloat(i)));
o[1].x = asuint(f16tof32(i));
}

27
test/spirv/bitfields.hlsl Normal file
View File

@ -0,0 +1,27 @@
// PROFILE: cs_6_2
// Bitfields: SPIR-V starts a new storage word when the type changes (c is
// int, a and b uint), as dxc does.
// ZCHECK: OpTypeStruct %uint %uint %int %uint %uint %uint
// ZCHECK: OpShiftRightArithmetic %int
struct Base { uint lo : 4; uint hi : 4; };
struct P : Base {
uint a : 3; uint b : 5; int c : 4;
uint d;
uint e : 30; uint f : 4;
uint sum() { return a + b + lo + hi; }
void bump() { b += 1; hi++; }
};
cbuffer CB { P cp; };
RWStructuredBuffer<P> sb : register(u0);
RWStructuredBuffer<int> o : register(u1);
[numthreads(1,1,1)] void main() {
P p = sb[0];
p.b = 7;
p.c = -3;
p.bump();
sb[1] = p;
P q = {1, 2, 3, 4, -5, 6, 7, 8};
sb[2] = q;
sb[3].f |= 2;
o[0] = p.a + p.c + cp.e + cp.f + p.sum() + q.c;
}

View File

@ -0,0 +1,13 @@
// PROFILE: cs_6_0
// Structured buffers of matrices: whole loads and stores, rows (constant
// and dynamic) and row components.
// ZCHECK: OpMemberDecorate %type_StructuredBuffer_mat4v3float 0 MatrixStride 16
// ZCHECK: OpMemberDecorate %type_RWStructuredBuffer_mat2v3float 0 MatrixStride 8
StructuredBuffer<float4x3> m : register(t0);
RWStructuredBuffer<float2x3> r : register(u1);
RWStructuredBuffer<float4> o : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) {
o[i] = float4(m[i][1], 1) + r[i][0].x + float4(m[0][i % 4], m[1][2].y);
r[i] = r[i] * 2;
o[i + 1] = mul(float4(1, 2, 3, 4), m[i]).xyzz;
}

View File

@ -0,0 +1,16 @@
// PROFILE: cs_6_0
// Byte-address buffer loads, stores, atomics and sizes.
RWByteAddressBuffer rb : register(u0);
ByteAddressBuffer ro : register(t0);
RWStructuredBuffer<uint> c : register(u1);
AppendStructuredBuffer<float4> ap : register(u2);
ConsumeStructuredBuffer<float4> co : register(u3);
[numthreads(64,1,1)] void main(uint i : SV_GroupIndex) {
uint4 v = ro.Load4(i * 16) + rb.Load2(4).xyxy;
rb.Store3(i * 12, v.xyz);
uint old; rb.InterlockedAdd(0, 1, old);
rb.InterlockedCompareStore(8, 1, 2);
uint n = 0;
rb.Store(20, n + old);
uint w; rb.GetDimensions(w); rb.Store(16, w);
}

View File

@ -0,0 +1,17 @@
// PROFILE: cs_6_2
// FLAGS: -enable-16bit-types
// Templated byte-address Load/Store of structs, matrices (by column in
// SPIR-V), 16- and 64-bit components from 32-bit words.
struct S { float a; double b; uint16_t c; int2 d; };
RWByteAddressBuffer buf : register(u0);
[numthreads(1,1,1)] void main(uint i : SV_GroupIndex) {
S s = buf.Load<S>(i * 32);
float3x2 m = buf.Load<float3x2>(64);
half4 h = buf.Load<half4>(128);
S arr[2] = buf.Load<S[2]>(256);
s.a += m[1][0] + h.y + arr[1].d.x;
buf.Store<S>(i * 32 + 512, s);
buf.Store<float3x2>(96, m);
buf.Store<half4>(136, h);
buf.Store<double>(160, s.b);
}

View File

@ -0,0 +1,19 @@
// PROFILE: cs_6_0
// ENV: vulkan1.3
// StorageBuffer + Block from SPIR-V 1.4.
// ZCHECK: OpVariable %_ptr_StorageBuffer
// Byte-address buffer loads, stores, atomics and sizes.
RWByteAddressBuffer rb : register(u0);
ByteAddressBuffer ro : register(t0);
RWStructuredBuffer<uint> c : register(u1);
AppendStructuredBuffer<float4> ap : register(u2);
ConsumeStructuredBuffer<float4> co : register(u3);
[numthreads(64,1,1)] void main(uint i : SV_GroupIndex) {
uint4 v = ro.Load4(i * 16) + rb.Load2(4).xyxy;
rb.Store3(i * 12, v.xyz);
uint old; rb.InterlockedAdd(0, 1, old);
rb.InterlockedCompareStore(8, 1, 2);
uint n = 0;
rb.Store(20, n + old);
uint w; rb.GetDimensions(w); rb.Store(16, w);
}

45
test/spirv/check.sh Normal file
View File

@ -0,0 +1,45 @@
#!/bin/sh
# SPIR-V output checks beyond validation: every test/spirv/*.hlsl must pass
# spirv-val, and every `// ZCHECK: text` line must appear in zdxc's
# disassembly (`{{.*}}` matches anything), and descriptor bindings and
# interface locations must match dxc's.
#
# Usage: test/spirv/check.sh <path-to-zdxc>
set -u
ZDXC=$1
DXC_BUILD=${DXC_BUILD:-../build}
VAL=$DXC_BUILD/oracle-spirv-tools/tools/spirv-val
DIS=$DXC_BUILD/oracle-spirv-tools/tools/spirv-dis
DXC=$DXC_BUILD/bin/dxc
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
pass=0
fail=0
for f in test/spirv/*.hlsl; do
profile=$(sed -n 's|^// PROFILE: *||p' "$f")
flags=$(sed -n 's|^// FLAGS: *||p' "$f")
name=$(basename "$f" .hlsl)
env=$(sed -n "s|^// ENV: *||p" "$f"); if ! "$ZDXC" -spirv -T "$profile" $flags -fspv-target-env="${env:-vulkan1.0}" "$f" -Fo "$TMP/z.spv" > "$TMP/log" 2>&1; then
fail=$((fail + 1)); echo "FAIL $name: zdxc failed"; head -3 "$TMP/log"; continue
fi
if ! "$VAL" --target-env "$(printf '%s' "${env:-vulkan1.0}" | sed 's/spirv1/spv1/')" --relax-block-layout "$TMP/z.spv" > "$TMP/log" 2>&1; then
fail=$((fail + 1)); echo "FAIL $name: spirv-val rejected the output"; head -3 "$TMP/log"; continue
fi
"$DIS" "$TMP/z.spv" > "$TMP/z.dis" 2>&1
ok=1
# Bindings and locations must match dxc's (when dxc compiles the test).
if "$DXC" -spirv -T "$profile" $flags -fspv-target-env="${env:-vulkan1.0}" "$f" -Fo "$TMP/d.spv" > /dev/null 2>&1; then
"$DIS" "$TMP/d.spv" > "$TMP/d.dis" 2>&1
if ! python3 test/spirv/compare_bindings.py "$TMP/d.dis" "$TMP/z.dis" > "$TMP/bind" 2>&1; then
ok=0; echo "FAIL $name: bindings / locations differ from dxc"; head -5 "$TMP/bind"
fi
fi
sed -n 's|^// ZCHECK: *||p' "$f" > "$TMP/checks"
while IFS= read -r pat; do
re=$(printf '%s\n' "$pat" | sed -e 's/[][\.*^$()+?|{}]/\\&/g' -e 's/\\{\\{\\\.\\\*\\}\\}/.*/g')
grep -Eq -- "$re" "$TMP/z.dis" || { ok=0; echo "FAIL $name: missing '$pat'"; }
done < "$TMP/checks"
if [ $ok = 1 ]; then pass=$((pass + 1)); else fail=$((fail + 1)); fi
done
echo "spirv checks: $pass passed, $fail failed"
[ "$fail" -eq 0 ]

View File

@ -0,0 +1,31 @@
"""Exits non-zero if the descriptor bindings and interface locations of two
SPIR-V disassemblies differ (variables present in both, keyed by name).
Usage: compare_bindings.py <expected.dis> <actual.dis>"""
import re, sys
def parse(path):
names = {}; decs = {}; sc = {}
for line in open(path):
m = re.match(r'\s*OpName (%\S+) "(.*)"', line)
if m: names[m.group(1)] = m.group(2); continue
m = re.match(r'\s*OpDecorate (%\S+) (DescriptorSet|Binding|Location|Component|Index|BuiltIn|InputAttachmentIndex|SpecId) (\S+)', line)
if m: decs.setdefault(m.group(1), {})[m.group(2)] = m.group(3); continue
m = re.match(r'\s*(%\S+) = OpVariable %\S+ (\S+)', line)
if m: sc[m.group(1)] = m.group(2)
out = {}
for v, s in sc.items():
if s in ('Function', 'Private', 'Workgroup'): continue
n = names.get(v, None)
if n is None:
bi = decs.get(v, {}).get('BuiltIn')
if not bi: continue
n = 'builtin.' + bi + '.' + s
pass
d = dict(decs.get(v, {})); d['sc'] = s
out.setdefault(n, []).append(tuple(sorted(d.items())))
return out
a = parse(sys.argv[1]); b = parse(sys.argv[2])
bad = []
for n in sorted(set(a) & set(b)):
if sorted(a.get(n, [])) != sorted(b.get(n, [])): bad.append('%s: dxc %s zdxc %s' % (n, a.get(n), b.get(n)))
print('\n'.join(bad))
sys.exit(1 if bad else 0)

View File

@ -0,0 +1,7 @@
// PROFILE: cs_6_6
// Implicit-LOD sampling and derivatives in a compute shader (SM 6.6).
// ZCHECK: OpExecutionMode %main DerivativeGroupQuadsKHR
Texture2D<float4> t : register(t0);
SamplerState s : register(s0);
RWStructuredBuffer<float4> o : register(u0);
[numthreads(8,8,1)] void main(uint2 id : SV_DispatchThreadID) { float2 uv = id / 64.0; o[id.x] = t.Sample(s, uv) + ddx(uv).x + t.CalculateLevelOfDetail(s, uv); }

Some files were not shown because too many files have changed in this diff Show More