Compare commits

...

79 Commits

Author SHA1 Message Date
Peter Li 05076bb91a zdxc: make the tree a clean public source drop
Move the oracle tests, the benchmark, the agent skill and the libzdxc
investigation notes to the zdxc-internal development repo, which builds
this tree as a path dependency. The public build keeps install, run and
test. build.zig.zon now lists tools/ (the build needs its generators)
and docs/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:39:53 -08:00
Peter Li 33d390816f removing the zdxc binary 2026-11-01 15:26:33 -08:00
Peter Li 44b8e0bd26 zdxc: --job=<job.json> batch mode
Compile every shader a JSON job file lists in one process, on all cores.
Each job is a dxc command line; shared args come first. Outputs are
byte-identical to separate runs and each job's diagnostics print together
in job order. 1481 corpus shaders: 0.064 s, against 1.09 s for one zdxc
per shader on 10 cores and 1.68 s for dxc.

Also: an unreadable input exits 1 as in dxc (was 5), and stdout/stderr
write in streaming mode so `2>> log` appends instead of overwriting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 09:46:47 -08:00
Peter Li c51e594db8 zdxc: number DXIL instructions once per function
The bitcode writer found an instruction's value ID by counting the
non-void instructions before it, for every operand: quadratic in the
function's size. Large functions (unrolled loops, -O0 hull shaders) took
up to 190 ms; the IDs are now computed once per function. Output is
byte-identical; SubD11_SubDToBezierHS4444 goes from 192 ms to 10 ms
(dxc: 64 ms).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 09:27:47 -08:00
Peter Li b5a47b7c8e zdxc: partial stores to shared memory; one SPIR-V type per strided array
Writing some components of a vector or matrix in an RW structured
buffer or groupshared memory read the whole value and wrote it all
back, racing with other threads writing the other components. Those
stores now write only the named components, as dxc does. Matrix rows
and elements of buffer matrices (W[i][1][2] = x, B[i].m[r] = v, at
constant or dynamic rows) are stored element by element instead of
being rejected.

SPIR-V arrays with the same element, length and stride are now one
type, so buffers of the same element share their runtime array.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 09:12:38 -08:00
Peter Li bf073b8907 zdxc: -Zpr / -Zpc and #pragma pack_matrix
-Zpr and #pragma pack_matrix were accepted but ignored, so row-major
matrices silently got the column-major layout. Now, as in dxc:

- #pragma pack_matrix sets the orientation of matrices declared after
  it and may come between any two tokens; typedefs keep theirs.
- -Zpr is the default for matrices with neither; -Zpc is accepted and
  the two together are an error.
- Entry parameters take an orientation written on them or the
  pragma's, not a typedef's (dxc's signatures lose that sugar).
- Structured buffer matrix elements follow -Zpr only in DXIL; in
  SPIR-V they take the template argument's orientation too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 08:53:09 -08:00
Peter Li 1cbdff697b zdxc: nested types of template instances; typedef members as dxc
Types declared in structs, template ones included, are accepted as the
last part of a qualified type name (TO<float>::In), which the parser
lost with the template's scope. typedef members are reported in struct
templates too (at the definition, as dxc), while alias declarations
(using F = float;) are allowed in any struct, as in dxc. Each HLSL
struct gets a module type of its own: struct types are named, and
same-named structs (two instances' nested In, or a ConstantBuffer<S>
class type and S) shared one layout, which crashed dxv.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 00:58:07 -07:00
Peter Li 964ffde8e7 zdxc: mangle template instances, classes and scoped names as dxc
Structs and enums remember their enclosing namespaces and structs, and
struct template instances their name and arguments, so mangled names
spell them as dxc does: U/V for struct/class, ?$Name@<args>@ for
instances (type arguments, $0<n> and $0?<n> integral ones, with names
of their own), each enclosing scope after the name, with back-references.
Exported functions whose signature holds a resource or matrix handle get
dxc's error instead of an invalid module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 00:39:38 -07:00
Peter Li 8ec0dd4b31 zdxc: keep [noinline] functions in DXIL libraries
[noinline] plain functions in libraries become internal functions of
their own (noinline nounwind) instead of being inlined, passed values as
exported functions are: scalars and vectors by value, structs and out /
inout values by pointer (through temporaries at the call). RDAT lists
them, and each function's shader flags, minimum shader model and stage
mask merge in its callees' (dxc's ComputeShaderCompatInfo), as do the
LinAlg extended properties. Functions with resources, matrix handles,
arrays, matrices or groupshared parameters are still inlined (the
validator rejects resources, LinAlg matrices included, in signatures).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 00:28:56 -07:00
Peter Li 506d9c0b9d zdxc: SM 6.10 LinAlg in libraries
Write each library function's RDAT ExtendedProperties the way dxc's
AddLinAlgFunctionProperties does: matrix constructions with their
operation shapes, thread mat-vec multiplies, wave and thread-group
matrix multiplies, outer products and accumulating stores, merged from
callees, in the extended property record tables (part types 13-20)
with record deduplication. Removes the library LinAlg gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 00:07:09 -07:00
Peter Li edddf5e5f8 out / inout resource parameters
- Resource locals may be declared without an initializer (an alias of
  what is stored into them; reading one first is reported).
- DXIL: inlined calls write out resources into the caller's alias; a
  resource written back to the global it is is a no-op.
- SPIR-V: out / inout resource parameters leave the parameter list (an
  inout one's value comes in by value); the callee works on a local and
  what it holds at the end is traced to a parameter or global, which the
  caller stores into the argument after the call.
- An acceleration structure that is only declared gets the ray query
  capability its type needs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 23:55:37 -07:00
Peter Li d6b2c9e712 Arrays of resources as function parameters
- DXIL: a local array of resources (a parameter's copy) aliases the
  resource array stored into it; elements index that array.
- SPIR-V: a whole resource array read to pass on stays its variable, so
  the callee is specialized on it; arrays read whole are not flattened
  (their bindings are still numbered per element), which also lets
  global structs holding resource arrays be passed to functions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:10:48 -07:00
Peter Li 076f0f7e2b SPIR-V: resources in structs (locals, values, parameters, returns)
- An IR pass for SPIR-V splits structs holding resources: resource
  members of locals become resource locals, struct values carry their
  resources alongside (construct / extract / insert / load / store),
  parameters holding resources (by value or reference, including
  `this`) gain a resource parameter per member, and functions returning
  resources return the parameter or global they trace to.
- Struct values in SPIR-V leave resource members out.
- Arrays of global structs of resources: an element per resource
  variable named by flattened index (globals[5].t), and the whole struct
  reserves one consecutive binding range, as dxc numbers them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 21:55:56 -07:00
Peter Li 99e3591481 Resources in structs (DXIL), global structs of resources (both)
- DXIL: structs and arrays holding resources as values (data plus the
  resources, statically known) and as locals (data in memory, a
  resource slot per member): copies, nested structs, arrays, init lists,
  function arguments and returns, and functions returning resources.
- Global structs with resources: each resource is its own global named
  by its path (g.tex), bound like other unbound resources; data members
  stay in $Globals with resources taking no space in the layout.
- SPIR-V: struct types drop resource members (member indices remapped);
  a global struct of textures and samplers gets a binding per resource
  and turns on per-element array bindings, as dxc does; dxc's errors
  for structs with buffers or mixed members.
- LinAlg vectors of one element stay native vectors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 21:12:07 -07:00
Peter Li dc90b606a3 SM 6.9 long vectors (DXIL)
- vector<T, N> with N up to 1024 from shader model 6.9 (vector lengths
  and shapes widen to u16); intrinsic layouts accept long vectors.
- DXIL keeps the scalarized form: buffers, groupshared memory, structs,
  intrinsics and LinAlg vector operands work for any length.
- dxc's diagnostics: no swizzles on long vectors, and none in cbuffers,
  tbuffers, $Globals, ConstantBuffer/TextureBuffer, patches, streams or
  entry point parameters / return types.
- SPIR-V reports long vectors as unsupported (Vulkan has none; dxc's
  output is invalid).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:49:41 -07:00
Peter Li 92a5690d9a SM 6.10 linear algebra (DXIL)
- __builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(c, m, n, use,
  scope)]] as a type; matrices live in locals, statics and structs as
  matrix-typed allocas (as dxc -Od); !dx.targetTypes.
- All 21 dx::__builtin_LinAlg_* builtins lowered to DXIL ops 322-342
  with dxc's overload names (matrix, native vector and scalar operands;
  results stored to the out / ref argument).
- The LinearAlgebra shader flag; PSV0 LinAlgRuntimeInfo (constructions,
  multiplies, outer products, accumulate stores), byte-identical to dxc
  where matrix loads are traceable.
- groupshared parameters alias the caller's variable (they were copied);
  constants forwarded through locals within a block (immediates through
  parameters); enum static consts folded.
- Linear algebra in libraries (RDAT properties) and long vectors are
  reported as not supported yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:25:57 -07:00
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
Peter Li 412600a56e dxc-compatible command line
zdxc now accepts dxc's command line as-is, so it can replace dxc in build
scripts.

- vendor/dxc/HLSLOptions.td (dxc's option definitions) is turned into a
  Zig table at build time by tools/gen_options.zig (no tablegen/Python).
- src/options.zig parses with LLVM OptTable's rules, as dxc does: `-`,
  `/` and `--` prefixes; flags, joined, separate, joined-or-separate,
  multi-arg and comma-joined options; longest spelling first; aliases;
  case-sensitive; `/`-prefixed non-options are input paths; the last input
  wins. `-T cs_6_0`, `/T cs_6_0` and `-Tcs_6_0` are all accepted.
- Every dxc option has a support level:
  - implemented (-T -E -Fo -D -I -P -Fi -HV -spirv -enable-16bit-types
    -WX -no-warnings -W[no-]x -fdiagnostics-format= -ferror-limit=
    -fdiagnostics-color[=] -O0..3 -Od -Vd -help --version -nologo ...),
  - accepted with a one-line note, no effect yet (-Zpr, -Gis, -Qstrip_*,
    -Fh, -fvk-*, -fspv-target-env=, ... ),
  - rejected with a reason: dropped features (-Zi/-Fd debug info,
    -Fc/-dumpbin disassembly, -recompile, -link, -verify, -ast-dump, LLVM
    internals) or "not supported by zdxc yet".
- Errors match dxc's: "unknown argument: '-x'", "argument to '-T' is
  missing"; exit codes 1 (command line / I/O) and 5 (compile errors).
- -help lists dxc's groups and help text for what zdxc accepts.
- zdxc-only options (-zdxc-*, -f[no-]color-diagnostics) use names dxc
  does not define.
- `zig build oracle-cli`: all 5873 `RUN: %dxc` command lines in the DXC
  test corpus parse; 3392 are accepted and 2481 rejected only for
  deliberately unsupported features, with 0 unknown/missing arguments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 02:27:52 -07:00
Peter Li 35222efd97 Proper error reporting: macro backtraces, include chains, clang/msvc output
Diagnostics now match dxc's layout on the cases compared (nested macros,
include chains, #line, bracket matching, missing ';', fatal errors), with
range underlines and fix-it hints on top.

Locations:
- Macro-expanded tokens get clang-style macro locations: an expansion
  record (spelling, expansion point, macro name, argument or body).
  Errors print at the expansion site with "expanded from macro" notes,
  outermost first; argument tokens report at their own position.
- Files remember the #include that entered them ("In file included from").
- #line remapping moved into the source manager so diagnostics use
  presumed locations.
- UTF-16 sources with a BOM are decoded, as dxc does.

Engine (src/diag.zig):
- Diagnostics carry a range, notes, fix-it text and a warning group.
- Rendered in source order: the preprocessor runs ahead of the parser, so
  diagnostics are sorted by token position; a fatal error hides only what
  follows it.
- -fdiagnostics-format=clang|msvc|vi, colors when stderr is a terminal
  (-f[no-]color-diagnostics), -WX, -no-warnings, -Wno-<group>,
  -ferror-limit=N (default 20, applied in source order).

Messages:
- Missing ';' is reported after the previous token with a ';' fix-it and
  context ("at end of declaration", "after expression", ...); parsing
  continues when the next token starts a new line.
- Missing ')' / ']' / '}' get "note: to match this '('".
- "expected ';' after struct", "unknown type name 'X'", macro redefinition
  with "previous definition is here" [-Wmacro-redefined], #warning
  [-W#warnings], carets on the directive name / file name.
- Errors at end of file point just past the last token.
- Empty read()/write() payload qualifiers and static_assert (HLSL 202x)
  are rejected, matching dxc under -HV 2021.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 01:50:47 -07:00
Peter Li 39b8e38765 Parser performance: keyword map and cheaper isIdent
pp_bench gains a `parse` mode (preprocess + parse). On the 4764-file,
13.1 MB DXC test corpus (ReleaseFast, interleaved A/B):
  parse  130.9 -> 78.2 ms (-40%); the parser's own share 92 -> 39 ms.

- A third of parse time was mem.eql in linear scans over keyword and
  builtin-type lists. All of them now go through one comptime
  std.StaticStringMap of per-word flags (reserved, qualifier, contextual,
  scalar, object, template): -38%.
- Token.isIdent compares lengths inline before calling mem.eql: -3%.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 01:29:58 -07:00
Peter Li f6b2e9cf36 M0.1: HLSL 2021 parser and syntax tree
- src/front/ast.zig: purely syntactic tree (declarations, statements,
  expressions, types as written, attributes, semantics/registers).
- src/front/parser.zig: recursive descent over the preprocessed tokens,
  with a scoped type-name table to tell declarations from expressions,
  casts from parenthesized expressions and template arguments from
  comparisons. Covers the M0.1 language plus the syntax M0.2 needs
  (templates incl. partial specialization and variable templates, operator
  overloading, bitfields, methods, namespaces, enums, typedef/using) and
  dxc-isms seen in the corpus: payload access qualifiers, typed
  [[attributes]], legacy annotations / state blocks, `.template` calls,
  condition declarations, functions returning arrays.
- Error recovery at declaration and statement boundaries.
- src/front/ast_dump.zig and -zdxc-ast / -zdxc-parse dev flags.
- `zig build oracle-parse`: all 1604 corpus files that dxc compiles under
  -HV 2021 parse without errors; no crashes over all 4764 test files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 01:20:46 -07:00
Peter Li b8560a5b05 Preprocessor performance, round 2: inline the lexer into lexRaw
- Lexer.next is force-inlined into the preprocessor's raw token loop and
  the _Pragma check no longer runs a string compare on every identifier
  (pp: -3%).
- pp_bench gains a `load` mode (source manager only).

Overall vs 93d1e03 (before any tuning), 4764-file DXC test corpus,
ReleaseFast, interleaved A/B:
  lex    13.28 -> 10.34 ms  (-22%)
  load    6.89 ->  3.96 ms  (-43%)
  pp     50.11 -> 38.74 ms  (-23%)
  print  70.78 -> 48.99 ms  (-31%)

Tried and dropped in this round (no gain): a single-space fast path in
Lexer.next, and vector blank skipping limited to runs of 4+ spaces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:50:49 -07:00
Peter Li 6e5860b1db Preprocessor performance, round 1: benchmark + vector scans
Adds `zig build bench` (bench/pp_bench.zig): lexes / preprocesses / prints
a file list in-process, best of N, files served from memory.

On the 4764-file, 13.1 MB DXC test corpus (Apple M-series, ReleaseFast,
interleaved A/B against the previous commit):
  lex    13.3 -> 11.2 ms  (-16%)
  pp     49.7 -> 40.1 ms  (-19%)
  print  68.6 -> 53.2 ms  (-22%)

Kept:
- src/front/scan.zig: portable @Vector scans (width from
  std.simd.suggestVectorLength). Comment bodies are skipped with vector
  searches; line-start tables are built from per-block newline bitmasks.
- An identifier character table for the (short) identifier scans.
- A line cursor for -P printing: O(1) per token instead of a binary search.
- A 1024-bit filter over macro names so most identifiers skip hashing;
  the macro table is presized.

Tried and dropped (no gain): vector skipping of blank runs (2% slower;
gaps between tokens are mostly a single space) and fusing splice detection
into the newline scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:45:52 -07:00
Peter Li 93d1e03d3b Preprocessor: close the remaining review gaps
- '#' not followed by a parameter in a function-like macro is an error
  (object-like macros keep '#' literally), as in dxc.
- _Pragma("...") is destringized and handled like a #pragma line;
  "#pragma once in main file" now warns instead of registering.
- GNU line markers (`# 40 "file" 1 3`, `#40`) work like #line.
- Macro-argument pre-expansion and #if parentheses are limited to 512
  levels of nesting with a diagnostic, instead of overflowing the stack
  (dxc segfaults at a few thousand levels).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:35:58 -07:00
Peter Li c4f2220c4e Preprocessor review fixes: include search order, #if short-circuit, caching
- Quoted includes now search the directory of every file on the include
  stack (innermost first) before -I, and angled includes search only -I
  and the compiled-in headers, matching dxc. Angled lookups that only a
  quoted include would find get dxc's "use quotes" diagnostic.
- #if evaluation short-circuits &&, || and ?:; division by zero in an
  unevaluated operand is no longer an error (dxc accepts these).
- File contents are read once per path (with negative caching); each
  inclusion still gets its own FileId so #line state stays per inclusion.
- Include-guarded files (#ifndef X / #if !defined(X) wrapping the whole
  file) are not re-entered once X is defined. 2000 guarded includes:
  65 ms -> 2 ms per run (dxc: 3 ms).
- Skipped lines are now skipped token by token, so "/*" inside a string
  in an #if 0 block no longer swallows the #endif.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:29:29 -07:00
Peter Li feab1bf63b M0.1: HLSL preprocessor matching dxc -P across the DXC test corpus
- Source manager (line splicing, UTF-8 BOM) and clang-style diagnostics.
- Lexer producing preprocessing tokens.
- Preprocessor modelled on clang's: object and function-like macros, #/##,
  variadics with GNU comma elision, painted recursion blocking, nested
  argument pre-expansion, #if/#elif expressions, #include with -I and
  #pragma once, #line, #error/#warning, pass-through #pragma, and dxc's
  predefined macros (__HLSL_VERSION, __SHADER_TARGET_*, __spirv__, ...).
- dxc's compiled-in HLSL headers (<dx/linalg.h>, <vk/spirv.h>, ...) are
  vendored as data and used as the fallback for angled includes.
- -P/-Fi/-D/-I/-HV 2021/-enable-16bit-types options; profiles now cover
  lib_, ms_, as_ and SM 6.0-6.11.
- `zig build oracle-pp`: token-for-token comparison with dxc -P. 2060 of
  2060 corpus files dxc accepts match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:16:50 -07:00
Peter Li be9b6908cf M0.0: DXIL container, hash, bitcode writer and SPIR-V builder
- Port of DXC's container hash (ComputeHashRetail); matches dxc-signed
  containers on both padding paths.
- DXIL container reader/writer that signs its output.
- LLVM bitstream writer and a minimal LLVM 3.7 IR model that encodes types,
  constants, functions, core instructions and metadata as bitcode.
- An empty compute shader that dxv accepts for SM 6.0 through 6.9.
- SPIR-V builder; the empty compute module passes spirv-val (Vulkan 1.0).
- `zig build oracle` runs these checks against the DXC build.
- Zig 0.17 skill in .claude/skills/zig.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:01:46 -07:00
60 changed files with 40465 additions and 79 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
zig-out/
.zig-cache/
.zig-pkg/
test-out/

View File

@ -4,11 +4,44 @@ pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const hlsl_headers = b.createModule(.{
.root_source_file = b.path("vendor/hlsl_headers.zig"),
.target = target,
.optimize = optimize,
});
// dxc's option table, generated from the vendored tablegen file by a
// host tool (no tablegen or Python needed).
const gen_options = b.addExecutable(.{
.name = "gen_options",
.root_module = b.createModule(.{
.root_source_file = b.path("tools/gen_options.zig"),
.target = b.graph.host,
}),
});
const gen_options_run = b.addRunArtifact(gen_options);
gen_options_run.addFileArg(b.path("vendor/dxc/HLSLOptions.td"));
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", .{
.root_source_file = b.path("src/root.zig"),
.target = target,
.optimize = optimize,
.imports = &.{.{ .name = "hlsl_headers", .module = hlsl_headers }},
});
mod.addAnonymousImport("options_table", .{ .root_source_file = options_table });
mod.addAnonymousImport("intrinsics_table", .{ .root_source_file = intrinsics_table });
const exe = b.addExecutable(.{
.name = "zdxc",
@ -32,12 +65,4 @@ pub fn build(b: *std.Build) void {
test_step.dependOn(&b.addRunArtifact(mod_tests).step);
const exe_tests = b.addTest(.{ .root_module = exe.root_module });
test_step.dependOn(&b.addRunArtifact(exe_tests).step);
// Oracle checks: compare zdxc output against the DXC build in ../build.
const oracle_step = b.step("oracle", "Validate zdxc output with dxv and spirv-val");
const oracle = b.addSystemCommand(&.{ "sh", "test/oracle/m0.sh" });
oracle.addArtifactArg(exe);
oracle.setCwd(b.path("."));
oracle.has_side_effects = true;
oracle_step.dependOn(&oracle.step);
}

View File

@ -8,7 +8,9 @@
.paths = .{
"build.zig",
"build.zig.zon",
"docs",
"src",
"tools",
"vendor",
},
}

64
docs/batch.md Normal file
View File

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

439
src/diag.zig Normal file
View File

@ -0,0 +1,439 @@
//! Diagnostics: collected during compilation, rendered clang-style (or
//! msvc / vi style) with source snippets, ranges, notes, fix-it hints,
//! include chains and macro expansion backtraces.
const std = @import("std");
const Allocator = std.mem.Allocator;
const source = @import("front/source.zig");
const Loc = source.Loc;
pub const Severity = enum {
note,
warning,
@"error",
fatal,
fn label(s: Severity) []const u8 {
return switch (s) {
.note => "note",
.warning => "warning",
.@"error" => "error",
.fatal => "fatal error",
};
}
};
pub const Note = struct {
loc: Loc,
/// Length in bytes of the highlighted range starting at `loc`.
len: u32 = 0,
message: []const u8,
};
pub const Diagnostic = struct {
severity: Severity,
loc: Loc,
len: u32 = 0,
message: []const u8,
/// Warning group, shown as `[-Wgroup]` and controlled by `-Wno-group`.
group: ?[]const u8 = null,
/// The warning was promoted by -WX.
promoted: bool = false,
/// Text to insert at `loc` (shown under the caret).
fixit: ?[]const u8 = null,
notes: std.ArrayList(Note) = .empty,
/// Ordering key: diagnostics are rendered sorted by position (stable),
/// so preprocessor and parser messages interleave in source order.
position: u64 = 0,
};
pub const Report = struct {
severity: Severity,
loc: Loc,
len: u32 = 0,
group: ?[]const u8 = null,
fixit: ?[]const u8 = null,
};
pub const Diagnostics = struct {
arena: std.heap.ArenaAllocator,
list: std.ArrayList(*Diagnostic) = .empty,
error_count: u32 = 0,
warning_count: u32 = 0,
/// -WX
warnings_as_errors: bool = false,
/// -no-warnings
suppress_warnings: bool = false,
/// Groups disabled with -Wno-<group>.
disabled_groups: std.StringHashMapUnmanaged(void) = .empty,
/// Render at most this many errors (0 = no limit), like clang's
/// -ferror-limit. Applied in source order when rendering.
error_limit: u32 = 20,
/// Set by producers (preprocessor token count, parser token index)
/// and captured by each new diagnostic.
position: u64 = 0,
/// A fatal error was reported or the error limit reached: producers
/// should stop.
stopped: bool = false,
/// Position at which compilation stopped. Diagnostics for earlier
/// positions are still accepted: the preprocessor runs ahead of the
/// parser, so a fatal error late in the file must not hide parse
/// errors before it.
stop_position: u64 = std.math.maxInt(u64),
pub fn init(gpa: Allocator) Diagnostics {
return .{ .arena = .init(gpa) };
}
pub fn deinit(d: *Diagnostics) void {
d.arena.deinit();
}
pub fn disableGroup(d: *Diagnostics, group: []const u8) !void {
const a = d.arena.allocator();
try d.disabled_groups.put(a, try a.dupe(u8, group), {});
}
/// Report a diagnostic. Returns null when it is suppressed (disabled
/// warning, or after the compilation was stopped); otherwise notes can
/// be attached to the result with `note`.
/// True once compilation has stopped at or before `position`.
pub fn stoppedAt(d: *const Diagnostics, position: u64) bool {
return d.stopped and position >= d.stop_position;
}
pub fn report(d: *Diagnostics, r: Report, comptime fmt: []const u8, args: anytype) ?*Diagnostic {
if (d.stoppedAt(d.position)) return null;
var sev = r.severity;
var promoted = false;
if (sev == .warning) {
if (d.suppress_warnings) return null;
if (r.group) |g| if (d.disabled_groups.contains(g)) return null;
if (d.warnings_as_errors) {
sev = .@"error";
promoted = true;
}
}
const a = d.arena.allocator();
const diag = a.create(Diagnostic) catch return null;
diag.* = .{
.severity = sev,
.loc = r.loc,
.len = r.len,
.message = std.fmt.allocPrint(a, fmt, args) catch "out of memory formatting diagnostic",
.group = r.group,
.promoted = promoted,
.fixit = r.fixit,
.position = d.position,
};
d.list.append(a, diag) catch return null;
switch (sev) {
.@"error" => d.error_count += 1,
.fatal => {
d.error_count += 1;
if (!d.stopped or d.position < d.stop_position) d.stop_position = d.position;
d.stopped = true;
},
.warning => d.warning_count += 1,
.note => {},
}
return diag;
}
/// Attach a note to `diag` (no-op when the diagnostic was suppressed).
pub fn note(d: *Diagnostics, diag: ?*Diagnostic, loc: Loc, len: u32, comptime fmt: []const u8, args: anytype) void {
const target = diag orelse return;
const a = d.arena.allocator();
const msg = std.fmt.allocPrint(a, fmt, args) catch return;
target.notes.append(a, .{ .loc = loc, .len = len, .message = msg }) catch {};
}
pub fn err(d: *Diagnostics, loc: Loc, comptime fmt: []const u8, args: anytype) void {
_ = d.report(.{ .severity = .@"error", .loc = loc }, fmt, args);
}
pub fn warn(d: *Diagnostics, loc: Loc, comptime fmt: []const u8, args: anytype) void {
_ = d.report(.{ .severity = .warning, .loc = loc }, fmt, args);
}
/// Compatibility shim for callers that pass a severity directly.
pub fn add(d: *Diagnostics, severity: Severity, loc: Loc, comptime fmt: []const u8, args: anytype) void {
_ = 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 {
return d.error_count != 0;
}
/// Diagnostics sorted for output (stable by position).
pub fn sorted(d: *Diagnostics) []const *Diagnostic {
std.sort.insertion(*Diagnostic, d.list.items, {}, struct {
fn lt(_: void, a: *Diagnostic, b: *Diagnostic) bool {
return a.position < b.position;
}
}.lt);
return d.list.items;
}
pub fn render(d: *Diagnostics, sm: *const source.SourceManager, w: *std.Io.Writer, style: Style) !void {
var r: Renderer = .{ .sm = sm, .w = w, .style = style };
var errors: u32 = 0;
for (d.sorted()) |diag| {
if (diag.severity == .@"error" or diag.severity == .fatal) {
if (d.error_limit != 0 and errors == d.error_limit) {
try r.message(.fatal, .none, 0, "too many errors emitted, stopping now", null, null);
return;
}
errors += 1;
}
try r.diagnostic(diag);
}
}
};
pub const Format = enum {
/// `file:line:col: error: message`
clang,
/// `file(line,col): error: message` (clickable in Visual Studio)
msvc,
/// `file +line:col: error: message`
vi,
};
pub const Style = struct {
format: Format = .clang,
color: bool = false,
/// Show source lines, carets and fix-its.
snippets: bool = true,
};
const Renderer = struct {
sm: *const source.SourceManager,
w: *std.Io.Writer,
style: Style,
/// File of the previous top-level diagnostic, to print include chains
/// only when they change (as clang does).
last_file: ?source.FileId = null,
const reset = "\x1b[0m";
const bold = "\x1b[1m";
fn color(r: *Renderer, code: []const u8) !void {
if (r.style.color) try r.w.writeAll(code);
}
fn sevColor(sev: Severity) []const u8 {
return switch (sev) {
.note => "\x1b[1;30m",
.warning => "\x1b[1;35m",
.@"error", .fatal => "\x1b[1;31m",
};
}
fn diagnostic(r: *Renderer, d: *const Diagnostic) !void {
const file_loc = if (d.loc.isNone()) d.loc else r.sm.fileLoc(d.loc);
if (!file_loc.isNone()) try r.includeChain(file_loc.file);
var group_buf: [128]u8 = undefined;
const group: ?[]const u8 = if (d.group) |g|
(if (d.promoted)
std.fmt.bufPrint(&group_buf, "-Werror,-W{s}", .{g}) catch g
else
std.fmt.bufPrint(&group_buf, "-W{s}", .{g}) catch g)
else
null;
try r.message(d.severity, d.loc, d.len, d.message, group, d.fixit);
try r.macroBacktrace(d.loc);
for (d.notes.items) |n| {
try r.message(.note, n.loc, n.len, n.message, null, null);
try r.macroBacktrace(n.loc);
}
}
fn includeChain(r: *Renderer, file: source.FileId) !void {
if (r.last_file == file) return;
r.last_file = file;
// Outermost include first, one "In file included from" per level,
// matching dxc.
var chain: [64]Loc = undefined;
var n: usize = 0;
var inc = r.sm.file(file).included_from;
while (!inc.isNone() and n < chain.len) {
chain[n] = inc;
n += 1;
inc = r.sm.file(r.sm.fileLoc(inc).file).included_from;
}
while (n > 0) {
n -= 1;
const p = r.sm.presumedLoc(chain[n]);
try r.color(bold);
try r.w.print("In file included from {s}:{d}:\n", .{ p.file, p.line });
try r.color(reset);
}
}
/// `expanded from macro` notes for each macro level of `loc`,
/// outermost first (as dxc prints them); argument levels are skipped.
fn macroBacktrace(r: *Renderer, loc: Loc) !void {
var levels: [32]*const source.Expansion = undefined;
var n: usize = 0;
var cur = loc;
while (cur.isMacro() and n < levels.len) {
const e = r.sm.expansion(cur);
if (e.is_arg) {
cur = e.spelling;
continue;
}
levels[n] = e;
n += 1;
cur = e.expansion;
}
while (n > 0) {
n -= 1;
const e = levels[n];
var buf: [256]u8 = undefined;
const msg = std.fmt.bufPrint(&buf, "expanded from macro '{s}'", .{e.macro_name}) catch "expanded from macro";
try r.message(.note, r.sm.spellingLoc(e.spelling), 0, msg, null, null);
}
}
fn message(r: *Renderer, sev: Severity, loc: Loc, len: u32, msg: []const u8, group: ?[]const u8, fixit: ?[]const u8) !void {
const w = r.w;
try r.color(bold);
if (!loc.isNone()) {
const p = r.sm.presumedLoc(loc);
const col = r.sm.lineCol(loc).col;
switch (r.style.format) {
.clang => try w.print("{s}:{d}:{d}: ", .{ p.file, p.line, col }),
.msvc => try w.print("{s}({d},{d}): ", .{ p.file, p.line, col }),
.vi => try w.print("{s} +{d}:{d}: ", .{ p.file, p.line, col }),
}
}
try r.color(sevColor(sev));
try w.print("{s}: ", .{sev.label()});
try r.color(reset);
try r.color(bold);
try w.writeAll(msg);
if (group) |g| try w.print(" [{s}]", .{g});
try r.color(reset);
try w.writeByte('\n');
if (loc.isNone() or !r.style.snippets) return;
try r.snippet(loc, len, fixit);
}
fn snippet(r: *Renderer, loc: Loc, len: u32, fixit: ?[]const u8) !void {
const w = r.w;
const line = r.sm.lineText(loc);
const col = r.sm.lineCol(loc).col;
try w.print("{s}\n", .{line});
const caret_at = col - 1;
// Indentation keeps tabs so the caret lines up with the source.
for (0..caret_at) |i| try w.writeByte(if (i < line.len and line[i] == '\t') '\t' else ' ');
try r.color("\x1b[1;32m");
try w.writeByte('^');
if (len > 1) {
const end = @min(caret_at + len, line.len);
if (end > caret_at + 1) try w.splatByteAll('~', end - caret_at - 1);
}
try r.color(reset);
try w.writeByte('\n');
if (fixit) |text| {
for (0..caret_at) |i| try w.writeByte(if (i < line.len and line[i] == '\t') '\t' else ' ');
try r.color("\x1b[0;32m");
try w.writeAll(text);
try r.color(reset);
try w.writeByte('\n');
}
}
};
test "rendering: ranges, notes, fix-its, groups, formats" {
const gpa = std.testing.allocator;
var mfs: source.MemoryFs = .{};
var sm = source.SourceManager.init(gpa, mfs.fileSystem());
defer sm.deinit();
const f = try sm.addFile("a.hlsl", "float x = foo(1\n\tint y;\n");
var d = Diagnostics.init(gpa);
defer d.deinit();
const e = d.report(.{ .severity = .@"error", .loc = .{ .file = f, .offset = 15 }, .fixit = ")" }, "expected ')'", .{});
d.note(e, .{ .file = f, .offset = 13 }, 1, "to match this '('", .{});
_ = d.report(.{ .severity = .warning, .loc = .{ .file = f, .offset = 17 }, .len = 3, .group = "demo" }, "suspicious", .{});
var out: std.Io.Writer.Allocating = .init(gpa);
defer out.deinit();
try d.render(&sm, &out.writer, .{});
try std.testing.expectEqualStrings(
\\a.hlsl:1:16: error: expected ')'
\\float x = foo(1
\\ ^
\\ )
\\a.hlsl:1:14: note: to match this '('
\\float x = foo(1
\\ ^
\\a.hlsl:2:2: warning: suspicious [-Wdemo]
\\
++ "\tint y;\n\t^~~\n", out.written());
var out2: std.Io.Writer.Allocating = .init(gpa);
defer out2.deinit();
try d.render(&sm, &out2.writer, .{ .format = .msvc, .snippets = false });
try std.testing.expectEqualStrings(
\\a.hlsl(1,16): error: expected ')'
\\a.hlsl(1,14): note: to match this '('
\\a.hlsl(2,2): warning: suspicious [-Wdemo]
\\
, out2.written());
}
test "warning policy and error limit" {
const gpa = std.testing.allocator;
var d = Diagnostics.init(gpa);
defer d.deinit();
try d.disableGroup("quiet");
try std.testing.expect(d.report(.{ .severity = .warning, .loc = .none, .group = "quiet" }, "x", .{}) == null);
d.warnings_as_errors = true;
const w = d.report(.{ .severity = .warning, .loc = .none, .group = "loud" }, "y", .{}).?;
try std.testing.expectEqual(Severity.@"error", w.severity);
d.error_limit = 2;
d.err(.none, "e2", .{});
d.err(.none, "e3", .{});
var mfs: source.MemoryFs = .{};
var sm = source.SourceManager.init(gpa, mfs.fileSystem());
defer sm.deinit();
var out: std.Io.Writer.Allocating = .init(gpa);
defer out.deinit();
try d.render(&sm, &out.writer, .{});
try std.testing.expectEqualStrings(
\\error: y [-Werror,-Wloud]
\\error: e2
\\fatal error: too many errors emitted, stopping now
\\
, out.written());
}
test "a fatal error hides only what follows it" {
const gpa = std.testing.allocator;
var d = Diagnostics.init(gpa);
defer d.deinit();
d.position = 10;
d.add(.fatal, .none, "missing include", .{});
try std.testing.expect(d.stoppedAt(10) and !d.stoppedAt(9));
d.position = 5;
d.err(.none, "earlier parse error", .{});
d.position = 12;
d.err(.none, "later error", .{});
try std.testing.expectEqual(@as(usize, 2), d.list.items.len);
try std.testing.expectEqualStrings("earlier parse error", d.sorted()[0].message);
}

119
src/dxil/bitstream.zig Normal file
View File

@ -0,0 +1,119 @@
//! LLVM bitstream writer (the container format under LLVM bitcode).
//! Only unabbreviated records are emitted for now; they are always valid and
//! the LLVM 3.7 reader accepts them everywhere.
const std = @import("std");
const Allocator = std.mem.Allocator;
pub const abbrev_end_block = 0;
pub const abbrev_enter_subblock = 1;
pub const abbrev_define = 2;
pub const abbrev_unabbrev_record = 3;
pub const Writer = struct {
gpa: Allocator,
bytes: std.ArrayList(u8) = .empty,
cur: u64 = 0,
cur_bits: u6 = 0,
abbrev_width: u32 = 2,
blocks: std.ArrayList(Block) = .empty,
const Block = struct { prev_width: u32, size_word_index: usize };
pub fn init(gpa: Allocator) Writer {
return .{ .gpa = gpa };
}
pub fn deinit(w: *Writer) void {
w.bytes.deinit(w.gpa);
w.blocks.deinit(w.gpa);
}
pub fn emit(w: *Writer, value: u64, width: u32) !void {
std.debug.assert(width <= 32);
if (width == 0) return;
std.debug.assert(width == 32 or value >> @intCast(width) == 0);
w.cur |= value << w.cur_bits;
const total = @as(u32, w.cur_bits) + width;
if (total >= 32) {
var word: [4]u8 = undefined;
std.mem.writeInt(u32, &word, @truncate(w.cur), .little);
try w.bytes.appendSlice(w.gpa, &word);
w.cur >>= 32;
w.cur_bits = @intCast(total - 32);
} else {
w.cur_bits = @intCast(total);
}
}
pub fn emitVbr(w: *Writer, value: u64, width: u32) !void {
const threshold: u64 = @as(u64, 1) << @intCast(width - 1);
var v = value;
while (v >= threshold) {
try w.emit((v & (threshold - 1)) | threshold, width);
v >>= @intCast(width - 1);
}
try w.emit(v, width);
}
pub fn alignTo32(w: *Writer) !void {
if (w.cur_bits > 0) try w.emit(0, 32 - @as(u32, w.cur_bits));
}
pub fn enterBlock(w: *Writer, block_id: u32, abbrev_width: u32) !void {
try w.emit(abbrev_enter_subblock, w.abbrev_width);
try w.emitVbr(block_id, 8);
try w.emitVbr(abbrev_width, 4);
try w.alignTo32();
const idx = w.bytes.items.len;
try w.emit(0, 32); // block size in words, patched in endBlock
try w.blocks.append(w.gpa, .{ .prev_width = w.abbrev_width, .size_word_index = idx });
w.abbrev_width = abbrev_width;
}
pub fn endBlock(w: *Writer) !void {
try w.emit(abbrev_end_block, w.abbrev_width);
try w.alignTo32();
const blk = w.blocks.pop().?;
const words: u32 = @intCast((w.bytes.items.len - blk.size_word_index - 4) / 4);
std.mem.writeInt(u32, w.bytes.items[blk.size_word_index..][0..4], words, .little);
w.abbrev_width = blk.prev_width;
}
pub fn record(w: *Writer, code: u32, ops: []const u64) !void {
try w.emit(abbrev_unabbrev_record, w.abbrev_width);
try w.emitVbr(code, 6);
try w.emitVbr(ops.len, 6);
for (ops) |op| try w.emitVbr(op, 6);
}
/// Record whose operands are the bytes of `str`, optionally prefixed.
pub fn recordString(w: *Writer, code: u32, prefix: []const u64, str: []const u8) !void {
try w.emit(abbrev_unabbrev_record, w.abbrev_width);
try w.emitVbr(code, 6);
try w.emitVbr(prefix.len + str.len, 6);
for (prefix) |op| try w.emitVbr(op, 6);
for (str) |c| try w.emitVbr(c, 6);
}
/// Flush pending bits and return the finished stream (caller owns it).
pub fn finish(w: *Writer) ![]u8 {
std.debug.assert(w.blocks.items.len == 0);
try w.alignTo32();
return w.bytes.toOwnedSlice(w.gpa);
}
};
test "vbr and fixed fields pack little-endian" {
var w = Writer.init(std.testing.allocator);
defer w.deinit();
try w.emit('B', 8);
try w.emit('C', 8);
try w.emit(0x0, 4);
try w.emit(0xC, 4);
try w.emit(0xE, 4);
try w.emit(0xD, 4);
const out = try w.finish();
defer std.testing.allocator.free(out);
try std.testing.expectEqualSlices(u8, &.{ 'B', 'C', 0xC0, 0xDE }, out);
}

100
src/dxil/container.zig Normal file
View File

@ -0,0 +1,100 @@
//! DXIL container ("DXBC" header + parts). See
//! include/dxc/DxilContainer/DxilContainer.h.
const std = @import("std");
const Allocator = std.mem.Allocator;
const hash = @import("hash.zig");
pub fn fourcc(comptime s: *const [4]u8) u32 {
return std.mem.readInt(u32, s, .little);
}
pub const Part = struct {
fourcc: u32,
data: []const u8,
};
const header_size = 32; // FourCC, hash[16], version, size, part count
/// Assemble parts into a container and sign it (as the validator would).
pub fn assemble(gpa: Allocator, parts: []const Part) ![]u8 {
var size: usize = header_size + 4 * parts.len;
for (parts) |p| size += 8 + std.mem.alignForward(usize, p.data.len, 4);
const out = try gpa.alloc(u8, size);
@memset(out, 0);
std.mem.writeInt(u32, out[0..4], fourcc("DXBC"), .little);
std.mem.writeInt(u16, out[20..22], 1, .little); // version major
std.mem.writeInt(u16, out[22..24], 0, .little); // version minor
std.mem.writeInt(u32, out[24..28], @intCast(size), .little);
std.mem.writeInt(u32, out[28..32], @intCast(parts.len), .little);
var off: usize = header_size + 4 * parts.len;
for (parts, 0..) |p, i| {
std.mem.writeInt(u32, out[header_size + 4 * i ..][0..4], @intCast(off), .little);
std.mem.writeInt(u32, out[off..][0..4], p.fourcc, .little);
const padded = std.mem.alignForward(usize, p.data.len, 4);
std.mem.writeInt(u32, out[off + 4 ..][0..4], @intCast(padded), .little);
@memcpy(out[off + 8 ..][0..p.data.len], p.data);
off += 8 + padded;
}
hash.signContainer(out);
return out;
}
pub const ParseError = error{InvalidContainer};
/// Parsed view into a container; part data slices alias `bytes`.
pub const View = struct {
bytes: []const u8,
parts: std.ArrayList(Part),
pub fn deinit(v: *View, gpa: Allocator) void {
v.parts.deinit(gpa);
}
pub fn find(v: *const View, cc: u32) ?[]const u8 {
for (v.parts.items) |p| if (p.fourcc == cc) return p.data;
return null;
}
};
pub fn parse(gpa: Allocator, bytes: []const u8) !View {
if (bytes.len < header_size) return error.InvalidContainer;
if (std.mem.readInt(u32, bytes[0..4], .little) != fourcc("DXBC")) return error.InvalidContainer;
const size = std.mem.readInt(u32, bytes[24..28], .little);
const count = std.mem.readInt(u32, bytes[28..32], .little);
if (size > bytes.len or header_size + 4 * @as(usize, count) > size) return error.InvalidContainer;
var parts: std.ArrayList(Part) = .empty;
errdefer parts.deinit(gpa);
for (0..count) |i| {
const off = std.mem.readInt(u32, bytes[header_size + 4 * i ..][0..4], .little);
if (@as(usize, off) + 8 > size) return error.InvalidContainer;
const cc = std.mem.readInt(u32, bytes[off..][0..4], .little);
const len = std.mem.readInt(u32, bytes[off + 4 ..][0..4], .little);
if (@as(usize, off) + 8 + len > size) return error.InvalidContainer;
try parts.append(gpa, .{ .fourcc = cc, .data = bytes[off + 8 ..][0..len] });
}
return .{ .bytes = bytes[0..size], .parts = parts };
}
/// True if the stored hash matches a fresh ComputeHashRetail of the container.
pub fn hashMatches(bytes: []const u8) bool {
const digest = hash.computeRetail(bytes[hash.hash_start_offset..]);
return std.mem.eql(u8, &digest, bytes[4..20]);
}
test "assemble round-trips through parse and verifies its hash" {
const gpa = std.testing.allocator;
const parts = [_]Part{
.{ .fourcc = fourcc("SFI0"), .data = &@as([8]u8, @splat(0)) },
.{ .fourcc = fourcc("PRIV"), .data = "abc" },
};
const out = try assemble(gpa, &parts);
defer gpa.free(out);
try std.testing.expect(hashMatches(out));
var view = try parse(gpa, out);
defer view.deinit(gpa);
try std.testing.expectEqual(@as(usize, 2), view.parts.items.len);
try std.testing.expectEqualSlices(u8, "abc\x00", view.find(fourcc("PRIV")).?);
}

5559
src/dxil/emit.zig Normal file

File diff suppressed because it is too large Load Diff

View File

@ -4,7 +4,7 @@
const std = @import("std");
const padding = [_]u8{0x80} ++ [_]u8{0} ** 63;
const padding: [64]u8 = .{0x80} ++ @as([63]u8, @splat(0));
const shifts = [64]u5{
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,

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

@ -0,0 +1,325 @@
//! 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,
/// A callee's requirements added to its caller's.
pub fn merge(info: *Info, callee: Info) void {
info.flags |= callee.flags;
info.min_minor = @max(info.min_minor, callee.min_minor);
info.mask &= callee.mask;
}
};
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;
pub const linear_algebra = 1 << 41;
/// 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;
if (code >= 322 and code <= 342) fl |= bit.linear_algebra;
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 }, .{ 1 << 41, 0x200000000 }, .{ bit.raytracing_1_1, 0x100000 }, .{ bit.sampler_feedback, 0x200000 },
.{ bit.advanced_texture_ops, 0x20000000 }, .{ bit.uses_derivatives, 0x100 << 32 }, .{ bit.requires_group, 0x200 << 32 },
};
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,
};
}

400
src/dxil/linalg_info.zig Normal file
View File

@ -0,0 +1,400 @@
//! The SM 6.10 linear algebra usage the PSV0 part records (and the
//! validator recomputes from the module): matrix constructions, matrix-
//! vector and matrix-matrix multiplies, outer products and accumulating
//! stores. A port of dxc's LinAlgRuntimeInfoCollector.
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const rdat = @import("rdat.zig");
/// A matrix type's attributes (`!dx.targetTypes`).
pub const Matrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u32 };
pub const Shape = struct { m: u32, n: u32, k: u32 };
/// The serialized tables (PSVLinAlg*0 records) and the shape index runs to
/// put in the semantic index table first.
pub const Tables = struct {
shapes: []const Shape,
/// PSVLinAlgRuntimeInfo0 record bytes, per table in declaration order:
/// constructions, thread mat-vec multiplies, wave multiplies,
/// thread-group multiplies, outer products, accumulate stores.
records: [6][]const u8,
counts: [6]u32,
sizes: [6]u32 = .{ 12, 4, 12, 12, 4, 4 },
semantic_indices: []const u32,
pub fn empty(t: Tables) bool {
if (t.shapes.len > 0) return false;
for (t.counts) |c| if (c > 0) return false;
return true;
}
};
const Key2 = [2]u8;
const Key3 = [3]u8;
const Key4 = [4]u8;
pub const Info = struct {
constructions: std.AutoArrayHashMapUnmanaged(Key2, std.AutoArrayHashMapUnmanaged(Shape, void)) = .empty,
matvec: std.AutoArrayHashMapUnmanaged(Key3, u8) = .empty,
multiplies: std.AutoArrayHashMapUnmanaged(Key4, std.AutoArrayHashMapUnmanaged(Shape, void)) = .empty,
outer: std.AutoArrayHashMapUnmanaged(Key2, void) = .empty,
accumulate: std.AutoArrayHashMapUnmanaged(u8, u8) = .empty,
};
const transposed: u8 = 1;
const non_mul_optimal: u8 = 2;
pub const Matrices = []const struct { module.TypeId, Matrix };
/// Collects the usage in every function of `m`; `matrices` maps matrix
/// types to their attributes.
pub fn collect(a: Allocator, m: *const module.Module, matrices: Matrices) Allocator.Error!Tables {
var info: Info = .{};
const c: C = .{ .m = m, .mats = matrices };
for (m.functions.items) |*f| try collectFunction(a, c, &info, f);
return serialize(a, &info);
}
/// The usage of function `func` and of the functions it calls (dxc merges
/// callee usage into callers).
pub fn functionInfo(a: Allocator, m: *const module.Module, matrices: Matrices, func: u32) Allocator.Error!Info {
var info: Info = .{};
const c: C = .{ .m = m, .mats = matrices };
var seen: std.AutoArrayHashMapUnmanaged(u32, void) = .empty;
try seen.put(a, func, {});
var k: usize = 0;
while (k < seen.count()) : (k += 1) {
const f = &m.functions.items[seen.keys()[k]];
try collectFunction(a, c, &info, f);
for (f.insts.items) |inst| if (inst.op == .call) {
const callee = inst.op.call.callee;
if (m.functions.items[callee].num_blocks > 0) try seen.put(a, callee, {});
};
}
return info;
}
const C = struct {
m: *const module.Module,
mats: Matrices,
fn matrix(c: @This(), ty: ?module.TypeId) ?Matrix {
const t = ty orelse return null;
for (c.mats) |x| if (x[0] == t) return x[1];
return null;
}
fn constInt(c: @This(), v: module.Value) ?u32 {
if (v != .constant) return null;
return switch (c.m.constants.items[v.constant].kind) {
.int => |x| @truncate(@as(u64, @bitCast(x))),
else => null,
};
}
/// DXIL::ComponentType of a scalar (or a vector's element).
fn component(c: @This(), ty: module.TypeId, signed: bool) u8 {
const t = switch (c.m.types.items[ty]) {
.vector => |v| c.m.types.items[v.elem],
else => |x| x,
};
return switch (t) {
.half => 8,
.float => 9,
.double => 10,
.int => |w| switch (w) {
8 => if (signed) 19 else 20,
16 => if (signed) 2 else 3,
32 => if (signed) 4 else 5,
64 => if (signed) 6 else 7,
else => 0,
},
else => 0,
};
}
};
fn collectFunction(a: Allocator, c: C, info: *Info, f: *const module.Function) Allocator.Error!void {
const m = c.m;
const fty = m.types.items[f.ty].function;
const typeOf = struct {
fn t(mm: *const module.Module, ff: *const module.Function, ft: @FieldType(module.Type, "function"), v: module.Value) ?module.TypeId {
return switch (v) {
.global => |g| mm.globals.items[g].ptr_ty,
.function => null,
.constant => |k| mm.constants.items[k].ty,
.arg => |x| ft.params[x],
.inst => |i| ff.insts.items[i].ty,
};
}
}.t;
for (f.insts.items) |inst| {
if (inst.op != .call) continue;
const call = inst.op.call;
if (!std.mem.startsWith(u8, m.functions.items[call.callee].name, "dx.op.linAlg") or call.args.len == 0) continue;
const op = c.constInt(call.args[0]) orelse continue;
const arg = struct {
fn t(cc: C, ff: *const module.Function, ft: @FieldType(module.Type, "function"), args: []const module.Value, k: usize) ?module.TypeId {
return if (k < args.len) typeOf(cc.m, ff, ft, args[k]) else null;
}
}.t;
switch (op) {
336, 337 => {
const mat = c.matrix(arg(c, f, fty, call.args, 1)) orelse continue;
const signed = (c.constInt(call.args[2]) orelse 0) != 0;
const key: Key3 = .{ c.component(inst.ty, signed), @intCast(mat.comp), @intCast(c.constInt(call.args[4]) orelse 0) };
const gop = try info.matvec.getOrPut(a, key);
if (!gop.found_existing) gop.value_ptr.* = 0;
gop.value_ptr.* |= layoutFlags(c, f, call.args[1]);
},
334, 322 => {
const r = c.matrix(inst.ty) orelse continue;
const ma = c.matrix(arg(c, f, fty, call.args, 1)) orelse continue;
const mb = c.matrix(arg(c, f, fty, call.args, 2)) orelse continue;
const key: Key4 = .{ @intCast(r.scope), @intCast(r.comp), @intCast(ma.comp), @intCast(mb.comp) };
const gop = try info.multiplies.getOrPut(a, key);
if (!gop.found_existing) gop.value_ptr.* = .empty;
try gop.value_ptr.put(a, .{ .m = ma.m, .n = mb.n, .k = ma.n }, {});
},
340 => {
const r = c.matrix(inst.ty) orelse continue;
const signed = (c.constInt(call.args[1]) orelse 0) != 0;
const vt = arg(c, f, fty, call.args, 2) orelse continue;
try info.outer.put(a, .{ @intCast(r.comp), c.component(vt, signed) }, {});
},
338, 339 => {
const mat = c.matrix(arg(c, f, fty, call.args, 1)) orelse continue;
const gop = try info.accumulate.getOrPut(a, @intCast(mat.comp));
if (!gop.found_existing) gop.value_ptr.* = 0;
gop.value_ptr.* |= if (op == 338) 1 else 2;
},
342 => {
const vt = arg(c, f, fty, call.args, 4) orelse continue;
const gop = try info.accumulate.getOrPut(a, c.component(vt, true));
if (!gop.found_existing) gop.value_ptr.* = 0;
gop.value_ptr.* |= 1;
},
else => {
try construction(a, info, c.matrix(inst.ty));
for (call.args, 0..) |_, k| try construction(a, info, c.matrix(arg(c, f, fty, call.args, k)));
},
}
}
}
fn construction(a: Allocator, info: *Info, mat: ?Matrix) Allocator.Error!void {
const x = mat orelse return;
if (x.scope == 0) return; // Thread
const shape: Shape = .{
.m = if (x.use == 1) 0 else x.m,
.n = if (x.use == 0) 0 else x.n,
.k = if (x.use == 2) 0 else if (x.use == 0) x.n else x.m,
};
const gop = try info.constructions.getOrPut(a, .{ @intCast(x.comp), @intCast(x.use) });
if (!gop.found_existing) gop.value_ptr.* = .empty;
try gop.value_ptr.put(a, shape, {});
}
/// How a mat-vec multiply's matrix was loaded (both flags when unknown:
/// zdxc's matrices pass through local variables).
fn layoutFlags(c: anytype, f: *const module.Function, v0: module.Value) u8 {
var v = v0;
var flags: u8 = 0;
var steps: usize = 0;
while (steps < 64) : (steps += 1) {
if (v != .inst) return transposed | non_mul_optimal;
const inst = f.insts.items[v.inst];
if (inst.op != .call) return transposed | non_mul_optimal;
const call = inst.op.call;
const op = if (call.args.len > 0) c.constInt(call.args[0]) else null;
if (op == 324) {
v = call.args[1];
continue;
}
if (op == 325) {
const layout = c.constInt(call.args[4]) orelse return transposed | non_mul_optimal;
if (layout == 3) flags |= transposed else if (layout != 2) flags |= non_mul_optimal;
return flags;
}
return transposed | non_mul_optimal;
}
return transposed | non_mul_optimal;
}
fn lessShape(_: void, x: Shape, y: Shape) bool {
if (x.m != y.m) return x.m < y.m;
if (x.n != y.n) return x.n < y.n;
return x.k < y.k;
}
fn sortedShapes(a: Allocator, set: std.AutoArrayHashMapUnmanaged(Shape, void)) Allocator.Error![]Shape {
const out = try a.dupe(Shape, set.keys());
std.sort.insertion(Shape, out, {}, lessShape);
return out;
}
fn sortedKeys(comptime K: type, a: Allocator, keys: []const K) Allocator.Error![]K {
const out = try a.dupe(K, keys);
std.sort.insertion(K, out, {}, struct {
fn lt(_: void, x: K, y: K) bool {
return std.mem.order(u8, std.mem.asBytes(&x), std.mem.asBytes(&y)) == .lt;
}
}.lt);
return out;
}
const Writer = struct {
a: Allocator,
shapes: std.ArrayList(Shape) = .empty,
indices: std.ArrayList(u32) = .empty,
/// AddLinAlgShapes: shape table indexes, as a run in the semantic
/// index table (shared with an equal earlier run).
fn shapeRun(w: *Writer, shapes: []const Shape) Allocator.Error![2]u32 {
var idx: std.ArrayList(u32) = .empty;
for (shapes) |s| {
const k = for (w.shapes.items, 0..) |x, i| {
if (std.meta.eql(x, s)) break i;
} else blk: {
try w.shapes.append(w.a, s);
break :blk w.shapes.items.len - 1;
};
try idx.append(w.a, @intCast(k));
}
var off: usize = 0;
while (off + idx.items.len <= w.indices.items.len) : (off += 1) {
if (std.mem.eql(u32, w.indices.items[off..][0..idx.items.len], idx.items)) return .{ @intCast(off), @intCast(idx.items.len) };
}
const at: u32 = @intCast(w.indices.items.len);
try w.indices.appendSlice(w.a, idx.items);
return .{ at, @intCast(idx.items.len) };
}
};
fn put32(a: Allocator, out: *std.ArrayList(u8), v: u32) Allocator.Error!void {
var b: [4]u8 = undefined;
std.mem.writeInt(u32, &b, v, .little);
try out.appendSlice(a, &b);
}
fn serialize(a: Allocator, info: *Info) Allocator.Error!Tables {
var w: Writer = .{ .a = a };
var recs: [6]std.ArrayList(u8) = .{ .empty, .empty, .empty, .empty, .empty, .empty };
var counts: [6]u32 = .{ 0, 0, 0, 0, 0, 0 };
// (std::map order: keys sorted.)
for (try sortedKeys(Key2, a, info.constructions.keys())) |k| {
const run = try w.shapeRun(try sortedShapes(a, info.constructions.get(k).?));
try put32(a, &recs[0], run[0]);
try put32(a, &recs[0], run[1]);
try recs[0].appendSlice(a, &.{ k[0], 0, 0, 0 });
counts[0] += 1;
}
for (try sortedKeys(Key3, a, info.matvec.keys())) |k| {
try recs[1].appendSlice(a, &.{ k[0], k[1], k[2], info.matvec.get(k).? });
counts[1] += 1;
}
for (try sortedKeys(Key4, a, info.multiplies.keys())) |k| {
const run = try w.shapeRun(try sortedShapes(a, info.multiplies.get(k).?));
const t: usize = if (k[0] == 1) 2 else 3; // Wave, else ThreadGroup
try put32(a, &recs[t], run[0]);
try put32(a, &recs[t], run[1]);
try recs[t].appendSlice(a, &.{ k[1], k[2], k[3], 0 });
counts[t] += 1;
}
for (try sortedKeys(Key2, a, info.outer.keys())) |k| {
try recs[4].appendSlice(a, &.{ k[0], k[1], 0, 0 });
counts[4] += 1;
}
for (try sortedKeys(u8, a, info.accumulate.keys())) |k| {
try recs[5].appendSlice(a, &.{ k, info.accumulate.get(k).?, 0, 0 });
counts[5] += 1;
}
return .{
.shapes = w.shapes.items,
.records = .{ recs[0].items, recs[1].items, recs[2].items, recs[3].items, recs[4].items, recs[5].items },
.counts = counts,
.semantic_indices = w.indices.items,
};
}
/// The PSV0 LinAlg block: PSVLinAlgRuntimeInfo0, then each non-empty
/// table as its record size and records.
pub fn psvBlock(a: Allocator, t: Tables, out: *std.ArrayList(u8)) Allocator.Error!void {
try put32(a, out, 28); // sizeof(PSVLinAlgRuntimeInfo0)
try put32(a, out, @intCast(t.shapes.len));
for (t.counts) |n| try put32(a, out, n);
if (t.shapes.len > 0) {
try put32(a, out, 12);
for (t.shapes) |s| for ([_]u32{ s.m, s.n, s.k }) |v| try put32(a, out, v);
}
for (t.records, t.counts, t.sizes) |r, n, sz| if (n > 0) {
try put32(a, out, sz);
try out.appendSlice(a, r);
};
}
/// AddLinAlgShapes: the shape records' index array.
fn rdatShapes(a: Allocator, b: *rdat.Builder, set: std.AutoArrayHashMapUnmanaged(Shape, void)) Allocator.Error!u32 {
var idx: std.ArrayList(u32) = .empty;
for (try sortedShapes(a, set)) |s| {
var rec: [12]u8 = undefined;
for ([_]u32{ s.m, s.n, s.k }, 0..) |v, k| std.mem.writeInt(u32, rec[4 * k ..][0..4], v, .little);
try idx.append(a, try b.record(.shapes, &rec));
}
return b.array(idx.items);
}
/// A record with an index array reference, then four bytes.
fn refRecord(ref: u32, tail: [4]u8) [8]u8 {
var rec: [8]u8 = undefined;
std.mem.writeInt(u32, rec[0..4], ref, .little);
rec[4..8].* = tail;
return rec;
}
/// The function's RDAT ExtendedProperties (dxc's
/// AddLinAlgFunctionProperties): one property per non-empty kind, in
/// FunctionPropertyType order.
pub fn rdatProperties(a: Allocator, b: *rdat.Builder, info: *const Info) Allocator.Error!u32 {
var props: std.ArrayList(u32) = .empty;
var recs: std.ArrayList(u32) = .empty;
const flush = struct {
fn f(aa: Allocator, bb: *rdat.Builder, ps: *std.ArrayList(u32), rs: *std.ArrayList(u32), ty: u32) Allocator.Error!void {
if (rs.items.len == 0) return;
var arr: [4]u8 = undefined;
std.mem.writeInt(u32, &arr, try bb.array(rs.items), .little);
try ps.append(aa, try bb.record(.properties, &refRecord(ty, arr)));
rs.clearRetainingCapacity();
}
}.f;
for (try sortedKeys(Key2, a, info.constructions.keys())) |k| {
const shapes = try rdatShapes(a, b, info.constructions.get(k).?);
try recs.append(a, try b.record(.constructions, &refRecord(shapes, .{ k[0], 0, 0, 0 })));
}
try flush(a, b, &props, &recs, 1);
for (try sortedKeys(Key3, a, info.matvec.keys())) |k| {
try recs.append(a, try b.record(.thread_matvec, &.{ k[0], k[1], k[2], info.matvec.get(k).? }));
}
try flush(a, b, &props, &recs, 2);
const mul_keys = try sortedKeys(Key4, a, info.multiplies.keys());
for ([_]u8{ 1, 2 }, [_]rdat.Ext{ .wave_multiplies, .group_multiplies }, [_]u32{ 3, 4 }) |scope, t, ty| {
for (mul_keys) |k| if (k[0] == scope) {
const shapes = try rdatShapes(a, b, info.multiplies.get(k).?);
try recs.append(a, try b.record(t, &refRecord(shapes, .{ k[1], k[2], k[3], 0 })));
};
try flush(a, b, &props, &recs, ty);
}
for (try sortedKeys(Key2, a, info.outer.keys())) |k| {
try recs.append(a, try b.record(.outer_products, &.{ k[0], k[1], 0, 0 }));
}
try flush(a, b, &props, &recs, 5);
for (try sortedKeys(u8, a, info.accumulate.keys())) |k| {
try recs.append(a, try b.record(.accumulate_stores, &.{ k, info.accumulate.get(k).?, 0, 0 }));
}
try flush(a, b, &props, &recs, 6);
if (props.items.len == 0) return rdat.null_ref;
return b.array(props.items);
}

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

@ -0,0 +1,222 @@
//! 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 qualifiedName(a, t, "W4", en.name, en.scopes, 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 qualifiedName(a, t, if (st.is_class) "V" else "U", try structName(a, t, st), st.scopes, 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'),
}
}
/// A struct's own name: `name`, or `?$name@<args>@` for a template
/// instance (its arguments with names of their own).
fn structName(a: Allocator, t: *TypeTable, st: *const types.StructInfo) Allocator.Error![]const u8 {
const base = st.base_name orelse return st.name;
var out: std.ArrayList(u8) = .empty;
var inner: Names = .{};
try inner.add(a, base);
try out.print(a, "?${s}@", .{base});
for (st.template_args) |arg| switch (arg) {
.type => |ty| try typeCode(a, t, ty, &out, &inner),
.value => |v| {
try out.appendSlice(a, "$0");
if (v < 0) try out.append(a, '?');
try number(a, @abs(v), &out);
},
};
try out.append(a, '@');
return out.items;
}
/// `<kind><name><scope>@...@`: the name and each enclosing scope's,
/// innermost first, each a back-reference when already spelled.
fn qualifiedName(a: Allocator, t: *TypeTable, kind: []const u8, name: []const u8, scopes: []const types.ScopeName, out: *std.ArrayList(u8), names: *Names) Allocator.Error!void {
try out.appendSlice(a, kind);
try namePart(a, name, out, names);
for (scopes) |sc| try namePart(a, switch (sc) {
.name => |n| n,
.strct => |st| try structName(a, t, st),
}, out, names);
try out.append(a, '@');
}
/// One part of a qualified name: `name@` (template instances end in `@`
/// themselves), or a back-reference digit.
fn namePart(a: Allocator, name: []const u8, out: *std.ArrayList(u8), names: *Names) Allocator.Error!void {
if (names.find(name)) |k| return out.append(a, '0' + @as(u8, @intCast(k)));
try out.appendSlice(a, name);
if (name[0] != '?') try out.append(a, '@');
try names.add(a, name);
}
/// `<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);
}

695
src/dxil/module.zig Normal file
View File

@ -0,0 +1,695 @@
//! A minimal LLVM 3.7 IR model plus its bitcode encoder: just enough of LLVM
//! to express DXIL. Mirrors lib/Bitcode/Writer/BitcodeWriter.cpp, emitting
//! unabbreviated records only.
const std = @import("std");
const Allocator = std.mem.Allocator;
const bitstream = @import("bitstream.zig");
pub const TypeId = u32;
pub const ConstId = u32;
pub const MdId = u32;
pub const Type = union(enum) {
void,
label,
metadata,
half,
float,
double,
int: u32,
pointer: struct { elem: TypeId, addr_space: u32 = 0 },
function: struct { ret: TypeId, params: []const TypeId },
@"struct": struct { name: []const u8, elems: []const TypeId, @"packed": bool = false },
array: struct { len: u64, elem: TypeId },
vector: struct { len: u32, elem: TypeId },
fn eql(a: Type, b: Type) bool {
if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false;
return switch (a) {
.void, .label, .metadata, .half, .float, .double => true,
.int => |w| w == b.int,
.pointer => |p| p.elem == b.pointer.elem and p.addr_space == b.pointer.addr_space,
.function => |f| f.ret == b.function.ret and std.mem.eql(TypeId, f.params, b.function.params),
// Named structs are nominal.
.@"struct" => |s| std.mem.eql(u8, s.name, b.@"struct".name),
.array => |x| x.len == b.array.len and x.elem == b.array.elem,
.vector => |x| x.len == b.vector.len and x.elem == b.vector.elem,
};
}
};
pub const Constant = struct {
ty: TypeId,
kind: union(enum) {
int: i64,
/// Raw IEEE bits (f16/f32/f64 per type).
float_bits: u64,
undef,
null,
/// Struct / array / vector of earlier constants.
aggregate: []const ConstId,
},
};
pub const Linkage = enum(u32) { external = 0, internal = 3 };
/// Attribute group for function declarations (e.g. dx.op functions).
pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly, noreturn_nounwind, noinline_nounwind };
pub const Value = union(enum) {
/// Index into Module.globals (a pointer to the variable).
global: u32,
/// Index into Module.functions.
function: u32,
constant: ConstId,
arg: u32,
/// Index into Function.insts; must produce a value.
inst: u32,
};
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 Inst = struct {
/// Result type; `void` for instructions without a result.
ty: TypeId,
op: union(enum) {
ret: ?Value,
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 },
binop: struct { op: BinOp, lhs: Value, rhs: Value, flags: u32 = 0 },
cast: struct { op: CastOp, val: Value },
cmp: struct { pred: u32, lhs: Value, rhs: Value },
select: struct { cond: Value, t: Value, f: Value },
extractvalue: struct { agg: Value, index: 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 },
},
};
pub const Function = struct {
name: []const u8,
ty: TypeId,
linkage: Linkage = .external,
attrs: FnAttrs = .none,
/// Declarations have no blocks.
num_blocks: u32 = 0,
/// Instructions in block order; a terminator ends each block.
insts: std.ArrayList(Inst) = .empty,
};
pub const Metadata = union(enum) {
string: []const u8,
value: struct { ty: TypeId, val: Value },
/// Operands: null entries encode as 0 (no metadata).
node: []const ?MdId,
};
pub const Module = struct {
arena: std.heap.ArenaAllocator,
triple: []const u8 = "dxil-ms-dx",
datalayout: []const u8 = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64",
types: std.ArrayList(Type) = .empty,
constants: std.ArrayList(Constant) = .empty,
functions: std.ArrayList(Function) = .empty,
globals: std.ArrayList(GlobalVar) = .empty,
metadata: std.ArrayList(Metadata) = .empty,
named_metadata: std.ArrayList(struct { name: []const u8, nodes: []const MdId }) = .empty,
pub fn init(gpa: Allocator) Module {
return .{ .arena = .init(gpa) };
}
pub fn deinit(m: *Module) void {
m.arena.deinit();
}
pub fn allocator(m: *Module) Allocator {
return m.arena.allocator();
}
pub fn getType(m: *Module, t: Type) !TypeId {
for (m.types.items, 0..) |existing, i| {
if (existing.eql(t)) return @intCast(i);
}
const a = m.allocator();
var owned = t;
switch (owned) {
.function => |*f| f.params = try a.dupe(TypeId, f.params),
.@"struct" => |*s| {
s.name = try a.dupe(u8, s.name);
s.elems = try a.dupe(TypeId, s.elems);
},
else => {},
}
try m.types.append(a, owned);
return @intCast(m.types.items.len - 1);
}
pub fn intType(m: *Module, bits: u32) !TypeId {
return m.getType(.{ .int = bits });
}
pub fn fnType(m: *Module, ret: TypeId, params: []const TypeId) !TypeId {
return m.getType(.{ .function = .{ .ret = ret, .params = params } });
}
pub fn ptrType(m: *Module, elem: TypeId) !TypeId {
return m.getType(.{ .pointer = .{ .elem = elem } });
}
/// Lookup of an existing pointer type, used while encoding. Function
/// pointer types are created by addFunction.
fn ptrTypeConst(m: *const Module, elem: TypeId) TypeId {
for (m.types.items, 0..) |t, i| {
if (t == .pointer and t.pointer.elem == elem and t.pointer.addr_space == 0) return @intCast(i);
}
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 {
for (m.constants.items, 0..) |existing, i| {
if (existing.ty == c.ty and std.meta.eql(existing.kind, c.kind)) return .{ .constant = @intCast(i) };
}
try m.constants.append(m.allocator(), c);
return .{ .constant = @intCast(m.constants.items.len - 1) };
}
pub fn constInt(m: *Module, bits: u32, v: i64) !Value {
return m.constant(.{ .ty = try m.intType(bits), .kind = .{ .int = v } });
}
pub fn addFunction(m: *Module, f: Function) !u32 {
var owned = f;
owned.name = try m.allocator().dupe(u8, f.name);
_ = try m.ptrType(f.ty);
try m.functions.append(m.allocator(), owned);
return @intCast(m.functions.items.len - 1);
}
pub fn findFunction(m: *Module, name: []const u8) ?u32 {
for (m.functions.items, 0..) |f, i| if (std.mem.eql(u8, f.name, name)) return @intCast(i);
return null;
}
pub fn addInst(m: *Module, func: u32, inst: Inst) !Value {
const f = &m.functions.items[func];
try f.insts.append(m.allocator(), inst);
return .{ .inst = @intCast(f.insts.items.len - 1) };
}
pub fn mdString(m: *Module, s: []const u8) !MdId {
for (m.metadata.items, 0..) |md, i| {
if (md == .string and std.mem.eql(u8, md.string, s)) return @intCast(i);
}
try m.metadata.append(m.allocator(), .{ .string = try m.allocator().dupe(u8, s) });
return @intCast(m.metadata.items.len - 1);
}
pub fn mdValue(m: *Module, ty: TypeId, val: Value) !MdId {
for (m.metadata.items, 0..) |md, i| {
if (md == .value and md.value.ty == ty and std.meta.eql(md.value.val, val)) return @intCast(i);
}
try m.metadata.append(m.allocator(), .{ .value = .{ .ty = ty, .val = val } });
return @intCast(m.metadata.items.len - 1);
}
pub fn mdI32(m: *Module, v: i64) !MdId {
return m.mdValue(try m.intType(32), try m.constInt(32, v));
}
pub fn mdNode(m: *Module, ops: []const ?MdId) !MdId {
try m.metadata.append(m.allocator(), .{ .node = try m.allocator().dupe(?MdId, ops) });
return @intCast(m.metadata.items.len - 1);
}
pub fn addNamedMetadata(m: *Module, name: []const u8, nodes: []const MdId) !void {
const a = m.allocator();
try m.named_metadata.append(a, .{ .name = try a.dupe(u8, name), .nodes = try a.dupe(MdId, nodes) });
}
/// Encode the module as raw LLVM bitcode (starting with 'BC' 0xC0DE).
pub fn writeBitcode(m: *Module, gpa: Allocator) ![]u8 {
var enc: Encoder = .{ .m = m, .w = .init(gpa) };
defer enc.w.deinit();
return enc.write();
}
};
const block_module = 8;
const block_paramattr = 9;
const block_paramattr_group = 10;
const block_constants = 11;
const block_function = 12;
const block_value_symtab = 14;
const block_metadata = 15;
const block_type = 17;
const Encoder = struct {
m: *Module,
w: bitstream.Writer,
ops: std.ArrayList(u64) = .empty,
/// The function being written, and each of its instructions' value
/// ID offset (non-void instructions before it).
numbered: ?*const Function = null,
inst_ids: std.ArrayList(u32) = .empty,
fn gpa(e: *Encoder) Allocator {
return e.w.gpa;
}
fn rec(e: *Encoder, code: u32) !void {
try e.w.record(code, e.ops.items);
e.ops.clearRetainingCapacity();
}
fn push(e: *Encoder, v: u64) !void {
try e.ops.append(e.gpa(), v);
}
fn moduleValueCount(e: *Encoder) u32 {
return @intCast(e.m.globals.items.len + e.m.functions.items.len + e.m.constants.items.len);
}
/// Absolute value ID. Module values: globals, functions, constants.
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);
return switch (v) {
.global => |i| i,
.function => |i| nglobals + i,
.constant => |c| nglobals + nfuncs + c,
.arg => |a| e.moduleValueCount() + a,
.inst => |i| blk: {
const func = f.?;
std.debug.assert(e.numbered == func);
const nargs: u32 = @intCast(e.m.types.items[func.ty].function.params.len);
break :blk e.moduleValueCount() + nargs + e.inst_ids.items[i];
},
};
}
fn typeOf(e: *Encoder, f: ?*const Function, v: Value) TypeId {
return switch (v) {
.global => |i| e.m.globals.items[i].ptr_ty,
.function => |i| e.m.ptrTypeConst(e.m.functions.items[i].ty),
.constant => |c| e.m.constants.items[c].ty,
.arg => |a| e.m.types.items[f.?.ty].function.params[a],
.inst => |i| f.?.insts.items[i].ty,
};
}
fn pushValueAndType(e: *Encoder, f: *const Function, inst_id: u32, v: Value) !void {
const id = e.valueId(f, v);
try e.push(inst_id -% id);
if (id >= inst_id) try e.push(e.typeOf(f, v));
}
fn pushValue(e: *Encoder, f: *const Function, inst_id: u32, v: Value) !void {
try e.push(inst_id -% e.valueId(f, v));
}
fn write(e: *Encoder) ![]u8 {
defer e.ops.deinit(e.gpa());
defer e.inst_ids.deinit(e.gpa());
const w = &e.w;
try w.emit('B', 8);
try w.emit('C', 8);
try w.emit(0x0, 4);
try w.emit(0xC, 4);
try w.emit(0xE, 4);
try w.emit(0xD, 4);
try w.enterBlock(block_module, 3);
try e.push(1);
try e.rec(1); // MODULE_CODE_VERSION: relative value IDs
try e.writeAttributes();
try e.writeTypes();
try w.recordString(2, &.{}, e.m.triple);
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| {
// FUNCTION: [type, cc, isproto, linkage, paramattr, align, section,
// visibility, gc, unnamed_addr, prologue, dllstorage,
// comdat, prefix, personality]
const is_proto: u64 = @intFromBool(f.num_blocks == 0);
try e.ops.appendSlice(e.gpa(), &.{ f.ty, 0, is_proto, @backingInt(f.linkage), attrId(f.attrs), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
try e.rec(8);
}
try e.writeConstants();
try e.writeMetadata();
try e.writeSymtab();
for (e.m.functions.items) |*f| {
if (f.num_blocks != 0) try e.writeFunction(f);
}
try w.endBlock();
return w.finish();
}
fn attrId(a: FnAttrs) u64 {
return @backingInt(a);
}
fn writeAttributes(e: *Encoder) !void {
// Groups 1..5 match FnAttrs order; each applies to the function (index 0xFFFFFFFF).
// Attribute kinds: noinline = 14, noreturn = 17, nounwind = 18,
// readnone = 20, readonly = 21.
const w = &e.w;
try w.enterBlock(block_paramattr_group, 3);
const groups = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 }, &.{ 17, 18 }, &.{ 14, 18 } };
for (groups, 1..) |kinds, id| {
try e.push(id);
try e.push(0xFFFFFFFF);
for (kinds) |k| {
try e.push(0); // enum attribute
try e.push(k);
}
try e.rec(3); // PARAMATTR_GRP_CODE_ENTRY
}
try w.endBlock();
try w.enterBlock(block_paramattr, 3);
for (0..groups.len) |i| {
try e.push(i + 1);
try e.rec(2); // PARAMATTR_CODE_ENTRY: [group ids]
}
try w.endBlock();
}
fn writeTypes(e: *Encoder) !void {
const w = &e.w;
try w.enterBlock(block_type, 4);
try e.push(e.m.types.items.len);
try e.rec(1); // NUMENTRY
for (e.m.types.items) |t| {
switch (t) {
.void => try e.rec(2),
.float => try e.rec(3),
.double => try e.rec(4),
.label => try e.rec(5),
.half => try e.rec(10),
.metadata => try e.rec(16),
.int => |bits| {
try e.push(bits);
try e.rec(7);
},
.pointer => |p| {
try e.push(p.elem);
try e.push(p.addr_space);
try e.rec(8);
},
.function => |f| {
try e.push(0);
try e.push(f.ret);
for (f.params) |p| try e.push(p);
try e.rec(21);
},
.@"struct" => |s| {
if (s.name.len != 0) try w.recordString(19, &.{}, s.name);
try e.push(@intFromBool(s.@"packed"));
for (s.elems) |el| try e.push(el);
try e.rec(if (s.name.len != 0) 20 else 18);
},
.array => |a| {
try e.push(a.len);
try e.push(a.elem);
try e.rec(11);
},
.vector => |v| {
try e.push(v.len);
try e.push(v.elem);
try e.rec(12);
},
}
}
try w.endBlock();
}
fn writeConstants(e: *Encoder) !void {
if (e.m.constants.items.len == 0) return;
const w = &e.w;
try w.enterBlock(block_constants, 4);
var cur_ty: ?TypeId = null;
for (e.m.constants.items) |c| {
if (cur_ty != c.ty) {
try e.push(c.ty);
try e.rec(1); // SETTYPE
cur_ty = c.ty;
}
switch (c.kind) {
.int => |v| {
try e.push(encodeSigned(v));
try e.rec(4);
},
.float_bits => |b| {
try e.push(b);
try e.rec(6);
},
.undef => try e.rec(3),
.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();
}
fn writeMetadata(e: *Encoder) !void {
const m = e.m;
if (m.metadata.items.len == 0 and m.named_metadata.items.len == 0) return;
const w = &e.w;
try w.enterBlock(block_metadata, 3);
for (m.metadata.items) |md| {
switch (md) {
.string => |s| try w.recordString(1, &.{}, s),
.value => |v| {
try e.push(v.ty);
try e.push(e.valueId(null, v.val));
try e.rec(2);
},
.node => |ops| {
for (ops) |op| try e.push(if (op) |id| id + 1 else 0);
try e.rec(3);
},
}
}
for (m.named_metadata.items) |nmd| {
try w.recordString(4, &.{}, nmd.name);
for (nmd.nodes) |n| try e.push(n);
try e.rec(10);
}
try w.endBlock();
}
fn writeSymtab(e: *Encoder) !void {
const w = &e.w;
// dxc sorts entries by name for deterministic output.
const order = try e.gpa().alloc(u32, e.m.functions.items.len);
defer e.gpa().free(order);
for (order, 0..) |*o, i| o.* = @intCast(i);
const funcs = e.m.functions.items;
std.mem.sort(u32, order, funcs, struct {
fn lt(fs: []const Function, a: u32, b: u32) bool {
return std.mem.lessThan(u8, fs[a].name, fs[b].name);
}
}.lt);
try w.enterBlock(block_value_symtab, 4);
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();
}
fn writeFunction(e: *Encoder, f: *const Function) !void {
const w = &e.w;
e.inst_ids.clearRetainingCapacity();
var n: u32 = 0;
for (f.insts.items) |inst| {
try e.inst_ids.append(e.gpa(), n);
if (e.m.types.items[inst.ty] != .void) n += 1;
}
e.numbered = f;
try w.enterBlock(block_function, 4);
try e.push(f.num_blocks);
try e.rec(1); // DECLAREBLOCKS
const nargs: u32 = @intCast(e.m.types.items[f.ty].function.params.len);
var inst_id: u32 = e.moduleValueCount() + nargs;
for (f.insts.items) |inst| {
switch (inst.op) {
.ret => |v| {
if (v) |val| try e.pushValueAndType(f, inst_id, val);
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| {
try e.push(b.then);
if (b.@"else") |el| {
try e.push(el);
try e.pushValue(f, inst_id, b.cond.?);
}
try e.rec(11);
},
.call => |c| {
const callee = e.m.functions.items[c.callee];
try e.push(0); // paramattrs on the call site
try e.push(1 << 15); // explicit function type, ccc
try e.push(callee.ty);
try e.pushValueAndType(f, inst_id, .{ .function = c.callee });
for (c.args) |arg| try e.pushValue(f, inst_id, arg);
try e.rec(34);
},
.binop => |b| {
try e.pushValueAndType(f, inst_id, b.lhs);
try e.pushValue(f, inst_id, b.rhs);
try e.push(@backingInt(b.op));
if (b.flags != 0) try e.push(b.flags);
try e.rec(2);
},
.cast => |c| {
try e.pushValueAndType(f, inst_id, c.val);
try e.push(inst.ty);
try e.push(@backingInt(c.op));
try e.rec(3);
},
.cmp => |c| {
try e.pushValueAndType(f, inst_id, c.lhs);
try e.pushValue(f, inst_id, c.rhs);
try e.push(c.pred);
try e.rec(28);
},
.select => |s| {
try e.pushValueAndType(f, inst_id, s.t);
try e.pushValue(f, inst_id, s.f);
try e.pushValueAndType(f, inst_id, s.cond);
try e.rec(29);
},
.extractvalue => |x| {
try e.pushValueAndType(f, inst_id, x.agg);
try e.push(x.index);
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(if (l.@"align" == 0) 0 else @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(if (s.@"align" == 0) 0 else @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| {
try e.push(inst.ty);
for (p.incoming) |in| {
const diff = @as(i64, inst_id) - @as(i64, e.valueId(f, in.val));
try e.push(encodeSigned(diff));
try e.push(in.block);
}
try e.rec(16);
},
}
if (e.m.types.items[inst.ty] != .void) inst_id += 1;
}
try w.endBlock();
}
};
fn encodeSigned(v: i64) u64 {
return if (v >= 0) @as(u64, @intCast(v)) << 1 else (@as(u64, @intCast(-v)) << 1) | 1;
}
test "encodeSigned" {
try std.testing.expectEqual(@as(u64, 4), encodeSigned(2));
try std.testing.expectEqual(@as(u64, 3), encodeSigned(-1));
}

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 };
}

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

@ -0,0 +1,235 @@
//! 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, then the record tables of the extended
//! function properties (SM 6.10 linear algebra).
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,
};
/// The extended function property tables, in part order (part types
/// 13..20).
pub const Ext = enum(u32) {
properties = 13,
shapes,
constructions,
thread_matvec,
wave_multiplies,
group_multiplies,
outer_products,
accumulate_stores,
/// Record size in bytes.
pub fn stride(t: Ext) usize {
return switch (t) {
.shapes => 12,
.properties, .constructions, .wave_multiplies, .group_multiplies => 8,
.thread_matvec, .outer_products, .accumulate_stores => 4,
};
}
};
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,
ext: [8]std.ArrayList(u8) = @splat(.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);
}
/// Index of a record in table `t`; an identical record is shared
/// (record deduplication, validator 1.7+).
pub fn record(b: *Builder, t: Ext, rec: []const u8) Allocator.Error!u32 {
std.debug.assert(rec.len == t.stride());
const tab = &b.ext[@intFromEnum(t) - 13];
var at: usize = 0;
while (at < tab.items.len) : (at += rec.len) {
if (std.mem.eql(u8, tab.items[at..][0..rec.len], rec)) return @intCast(at / rec.len);
}
try tab.appendSlice(b.gpa, rec);
return @intCast(at / rec.len);
}
/// 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 });
}
for (b.ext, 13..) |rows, ty| if (rows.items.len > 0) {
const stride = @as(Ext, @enumFromInt(ty)).stride();
const t = try table(b.gpa, stride / 4, rows.items, rows.items.len / stride);
try tables.append(b.gpa, t);
try parts.append(b.gpa, .{ .ty = @intCast(ty), .data = t });
};
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);
for (&b.ext) |*t| t.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

290
src/dxil/shader.zig Normal file
View File

@ -0,0 +1,290 @@
//! Builds a complete DXIL container for a shader entry point. For now this
//! only covers an empty compute shader; later milestones feed it from the IR.
const std = @import("std");
const linalg_info = @import("linalg_info.zig");
const Allocator = std.mem.Allocator;
const Module = @import("module.zig").Module;
const container = @import("container.zig");
const signature = @import("signature.zig");
pub const ShaderKind = enum(u8) {
pixel = 0,
vertex = 1,
geometry = 2,
hull = 3,
domain = 4,
compute = 5,
library = 6,
mesh = 13,
amplification = 14,
pub fn profilePrefix(k: ShaderKind) []const u8 {
return switch (k) {
.pixel => "ps",
.vertex => "vs",
.geometry => "gs",
.hull => "hs",
.domain => "ds",
.compute => "cs",
.library => "lib",
.mesh => "ms",
.amplification => "as",
};
}
};
/// Highest shader model minor version accepted (matches the oracle dxc).
pub const max_minor = 11;
pub const Profile = struct {
kind: ShaderKind,
major: u8,
minor: u8,
/// Parses `<stage>_6_<minor>`, e.g. `cs_6_6` or `lib_6_10`.
pub fn parse(s: []const u8) ?Profile {
var it = std.mem.splitScalar(u8, s, '_');
const prefix = it.next() orelse return null;
const major_str = it.next() orelse return null;
const minor_str = it.next() orelse return null;
if (it.next() != null) return null;
const kind: ShaderKind = for (std.enums.values(ShaderKind)) |k| {
if (std.mem.eql(u8, prefix, k.profilePrefix())) break k;
} else return null;
if (!std.mem.eql(u8, major_str, "6")) return null;
const minor = std.fmt.parseInt(u8, minor_str, 10) catch return null;
if (minor > max_minor) return null;
const min_minor: u8 = switch (kind) {
.library => 1,
.mesh, .amplification => 5,
else => 0,
};
if (minor < min_minor) return null;
return .{ .kind = kind, .major = 6, .minor = minor };
}
};
pub const ComputeInfo = struct {
entry: []const u8 = "main",
profile: Profile,
num_threads: [3]u32,
};
/// Validator version we claim in !dx.valver (matches the oracle dxc).
const valver = .{ 1, 11 };
pub fn buildEmptyCompute(gpa: Allocator, info: ComputeInfo) ![]u8 {
var m = Module.init(gpa);
defer m.deinit();
const void_ty = try m.getType(.void);
const fn_ty = try m.fnType(void_ty, &.{});
const main_fn = try m.addFunction(.{ .name = info.entry, .ty = fn_ty, .num_blocks = 1 });
_ = try m.addInst(main_fn, .{ .ty = void_ty, .op = .{ .ret = null } });
// Metadata, in the same shape dxc emits.
const ident = try m.mdNode(&.{try m.mdString("zdxc 0.0.0")});
const version = try m.mdNode(&.{ try m.mdI32(1), try m.mdI32(info.profile.minor) });
const val_ver = try m.mdNode(&.{ try m.mdI32(valver[0]), try m.mdI32(valver[1]) });
const sm = try m.mdNode(&.{ try m.mdString(info.profile.kind.profilePrefix()), try m.mdI32(info.profile.major), try m.mdI32(info.profile.minor) });
const threads = try m.mdNode(&.{ try m.mdI32(info.num_threads[0]), try m.mdI32(info.num_threads[1]), try m.mdI32(info.num_threads[2]) });
const props = try m.mdNode(&.{ try m.mdI32(4), threads }); // kDxilNumThreadsTag
const fn_ref = try m.mdValue(try m.ptrType(fn_ty), .{ .function = main_fn });
const entry = try m.mdNode(&.{ fn_ref, try m.mdString(info.entry), null, null, props });
try m.addNamedMetadata("llvm.ident", &.{ident});
try m.addNamedMetadata("dx.version", &.{version});
try m.addNamedMetadata("dx.valver", &.{val_ver});
try m.addNamedMetadata("dx.shaderModel", &.{sm});
try m.addNamedMetadata("dx.entryPoints", &.{entry});
const bitcode = try m.writeBitcode(gpa);
defer gpa.free(bitcode);
const dxil_part = try programPart(gpa, info.profile, bitcode);
defer gpa.free(dxil_part);
const psv_part = try psvCompute(gpa, info.entry, info.num_threads, &.{});
defer gpa.free(psv_part);
const empty_sig = [_]u8{ 0, 0, 0, 0, 8, 0, 0, 0 }; // ParamCount 0, ParamOffset 8
const parts = [_]container.Part{
.{ .fourcc = container.fourcc("SFI0"), .data = &@as([8]u8, @splat(0)) },
.{ .fourcc = container.fourcc("ISG1"), .data = &empty_sig },
.{ .fourcc = container.fourcc("OSG1"), .data = &empty_sig },
.{ .fourcc = container.fourcc("PSV0"), .data = psv_part },
.{ .fourcc = container.fourcc("DXIL"), .data = dxil_part },
};
return container.assemble(gpa, &parts);
}
/// DxilProgramHeader + DxilBitcodeHeader + bitcode.
pub fn programPart(gpa: Allocator, profile: Profile, bitcode: []const u8) ![]u8 {
const padded = std.mem.alignForward(usize, bitcode.len, 4);
const out = try gpa.alloc(u8, 24 + padded);
@memset(out, 0);
const program_version: u32 = (@as(u32, @backingInt(profile.kind)) << 16) | (@as(u32, profile.major) << 4) | profile.minor;
std.mem.writeInt(u32, out[0..4], program_version, .little);
std.mem.writeInt(u32, out[4..8], @intCast(out.len / 4), .little);
std.mem.writeInt(u32, out[8..12], container.fourcc("DXIL"), .little);
std.mem.writeInt(u32, out[12..16], (1 << 8) | @as(u32, profile.minor), .little); // DXIL version
std.mem.writeInt(u32, out[16..20], 16, .little); // bitcode offset from bitcode header
std.mem.writeInt(u32, out[20..24], @intCast(bitcode.len), .little);
@memcpy(out[24..][0..bitcode.len], bitcode);
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,
/// SM 6.10 linear algebra usage.
linalg: ?linalg_info.Tables = null,
};
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.
pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
var buf: std.ArrayList(u8) = .empty;
errdefer buf.deinit(gpa);
const w = signature.put32;
const in_vectors = signature.vectorsUsed(info.inputs, 0);
var out_vectors: [4]u32 = undefined;
for (&out_vectors, 0..) |*v, s| v.* = signature.vectorsUsed(info.outputs, @intCast(s));
const pc_vectors = signature.vectorsUsed(info.patch_constants, 0);
try w(&buf, gpa, 60); // sizeof(PSVRuntimeInfo4)
// PSVRuntimeInfo0
try buf.appendSlice(gpa, &info.stage_info);
try w(&buf, gpa, 0); // MinimumExpectedWaveLaneCount
try w(&buf, gpa, 0xFFFFFFFF); // MaximumExpectedWaveLaneCount
// PSVRuntimeInfo1: stage, UsesViewID, MaxVertexCount, element counts,
// vector counts.
// (The MaxVertexCount union holds SigPatchConstOrPrimVectors for hull
// 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
for (info.num_threads) |t| try w(&buf, gpa, t);
// 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);
// (Linear algebra shape runs come first, as in dxc.)
const linalg: ?linalg_info.Tables = if (info.linalg) |t| (if (t.empty()) null else t) else null;
if (linalg) |t| try indices.appendSlice(gpa, t.semantic_indices);
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
try w(&buf, gpa, info.groupshared_bytes); // NumBytesGroupSharedMemory
try w(&buf, gpa, @intFromBool(linalg != null)); // Flags: LinAlgRuntimeInfoPresent
try w(&buf, gpa, @intCast(info.resources.len));
if (info.resources.len > 0) {
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);
}
}
try w(&buf, gpa, @intCast(strings.items.len));
try buf.appendSlice(gpa, strings.items);
try w(&buf, gpa, @intCast(indices.items.len));
for (indices.items) |v| try w(&buf, gpa, v);
if (info.inputs.len + info.outputs.len + info.patch_constants.len > 0) {
try w(&buf, gpa, 16); // sizeof(PSVSignatureElement0)
try buf.appendSlice(gpa, records.items);
}
// 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);
if (linalg) |t| try linalg_info.psvBlock(gpa, t, &buf);
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" {
const p = Profile.parse("cs_6_6").?;
try std.testing.expectEqual(ShaderKind.compute, p.kind);
try std.testing.expectEqual(@as(u8, 6), p.minor);
try std.testing.expect(Profile.parse("cs_5_0") == null);
try std.testing.expectEqual(ShaderKind.library, Profile.parse("lib_6_3").?.kind);
try std.testing.expectEqual(@as(u8, 10), Profile.parse("cs_6_10").?.minor);
try std.testing.expect(Profile.parse("ms_6_4") == null);
}

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));
}

306
src/front/ast.zig Normal file
View File

@ -0,0 +1,306 @@
//! Syntax tree for HLSL 2021. Purely syntactic: names are not resolved and
//! types are recorded as written. Nodes live in the parser's arena.
const std = @import("std");
const source = @import("source.zig");
pub const Loc = source.Loc;
/// A possibly qualified name as written: `foo`, `N::foo`, `::foo`.
pub const Name = struct {
loc: Loc,
/// Components without separators; a leading empty component means
/// a global-scope `::` prefix.
parts: []const []const u8,
/// Template arguments per part (`S<T>::value`); empty when no part has
/// any, otherwise the same length as `parts`.
args: []const []const TemplateArg = &.{},
pub fn last(n: Name) []const u8 {
return n.parts[n.parts.len - 1];
}
pub fn isSimple(n: Name, s: []const u8) bool {
return n.parts.len == 1 and std.mem.eql(u8, n.parts[0], s);
}
};
pub const TemplateArg = union(enum) {
type: *TypeRef,
expr: *Expr,
};
/// A type as written: `float4`, `Texture2D<float4>`, `vector<float, 4>`,
/// `N::S<T>`. Resolution happens in Sema.
pub const TypeRef = struct {
loc: Loc,
name: Name,
args: []const TemplateArg = &.{},
/// Array dimensions on type arguments: `StructuredBuffer<float[3]>`.
array_dims: []const ?*Expr = &.{},
/// `[[...]]` attributes after the type (`__builtin_LinAlgMatrix [[...]]`).
attrs: []const Attribute = &.{},
/// `unorm` / `snorm` inside resource element types.
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 = &.{},
/// `#pragma pack_matrix` in effect where the type was written (true:
/// row_major): the orientation of a matrix declared without one.
pack_matrix: ?bool = null,
};
/// Storage classes, type qualifiers and parameter / interpolation
/// modifiers that may precede a declaration.
pub const Qualifiers = packed struct(u64) {
@"const": bool = false,
static: bool = false,
uniform: bool = false,
@"extern": bool = false,
@"volatile": bool = false,
precise: bool = false,
groupshared: bool = false,
shared: bool = false,
in: bool = false,
out: bool = false,
row_major: bool = false,
column_major: bool = false,
nointerpolation: bool = false,
linear: bool = false,
centroid: bool = false,
sample: bool = false,
noperspective: bool = false,
globallycoherent: bool = false,
reordercoherent: bool = false,
@"inline": bool = false,
@"export": bool = false,
// Geometry shader input primitive types.
point: bool = false,
line: bool = false,
triangle: bool = false,
lineadj: bool = false,
triangleadj: bool = false,
// Mesh shader output / payload modifiers.
vertices: bool = false,
indices: bool = false,
primitives: bool = false,
payload: bool = false,
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)]]`.
pub const Attribute = struct {
loc: Loc,
/// e.g. `numthreads`, `vk::binding`.
name: []const u8,
args: []const *Expr,
double_bracket: bool,
};
/// Text after `:` on a declarator.
pub const Semantic = struct {
loc: Loc,
/// `access` is a ray payload qualifier: `read(caller)`, `write(miss)`.
kind: enum { semantic, register, packoffset, access },
/// Semantic name (`SV_Target0`), or the comma-separated arguments of
/// register(...) / packoffset(...) with internal tokens joined
/// (`t0`, `space1`, `c0.x`).
values: []const []const u8,
};
pub const UnaryOp = enum { plus, minus, not, bit_not, pre_inc, pre_dec, post_inc, post_dec };
pub const BinaryOp = enum {
mul,
div,
rem,
add,
sub,
shl,
shr,
lt,
gt,
le,
ge,
eq,
ne,
bit_and,
bit_xor,
bit_or,
log_and,
log_or,
comma,
};
pub const AssignOp = enum { assign, mul, div, rem, add, sub, shl, shr, bit_and, bit_xor, bit_or };
pub const Expr = struct {
loc: Loc,
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) {
int_lit: []const u8,
float_lit: []const u8,
bool_lit: bool,
string_lit: []const u8,
name: Name,
this,
unary: struct { op: UnaryOp, operand: *Expr },
binary: struct { op: BinaryOp, lhs: *Expr, rhs: *Expr },
assign: struct { op: AssignOp, lhs: *Expr, rhs: *Expr },
conditional: struct { cond: *Expr, then: *Expr, @"else": *Expr },
/// Function or method call; `template_args` for `f<T>(...)`.
call: struct { callee: *Expr, args: []const *Expr, template_args: []const TemplateArg = &.{} },
/// Type used as a function: `float4(...)`, `vector<float, 2>(...)`.
construct: struct { type: *TypeRef, args: []const *Expr },
cast: struct { type: *TypeRef, array_dims: []const ?*Expr = &.{}, operand: *Expr },
/// `.name` (field, swizzle or method); `arrow` is accepted for
/// error reporting.
member: struct { base: *Expr, name: []const u8, name_loc: Loc },
index: struct { base: *Expr, index: *Expr },
init_list: []const *Expr,
sizeof_type: *TypeRef,
sizeof_expr: *Expr,
/// `std::is_same<A, B>::value` (a dxc builtin).
is_same: struct { a: *TypeRef, b: *TypeRef },
};
};
pub const Stmt = struct {
loc: Loc,
attrs: []const Attribute = &.{},
kind: Kind,
pub const Kind = union(enum) {
compound: []const *Stmt,
/// Local declarations: variables, typedefs, structs.
decl: []const *Decl,
expr: *Expr,
empty,
/// `cond_decl` is set for `if (T x = e)`; `cond` then names `x`.
@"if": struct { cond_decl: ?*Decl = null, cond: *Expr, then: *Stmt, @"else": ?*Stmt },
@"for": struct { init: ?*Stmt, cond: ?*Expr, inc: ?*Expr, body: *Stmt },
@"while": struct { cond_decl: ?*Decl = null, cond: *Expr, body: *Stmt },
do_while: struct { body: *Stmt, cond: *Expr },
@"switch": struct { cond_decl: ?*Decl = null, cond: *Expr, body: *Stmt },
case: struct { value: *Expr, stmt: *Stmt },
default: *Stmt,
@"break",
@"continue",
@"return": ?*Expr,
discard,
};
};
pub const VarDecl = struct {
attrs: []const Attribute,
/// Non-empty for variable templates.
template_params: []const TemplateParam = &.{},
/// Qualified out-of-line definitions (`int S::x = 1;`) keep the full
/// spelled name, e.g. `S::x`.
quals: Qualifiers,
/// The qualifiers in source order.
qual_words: []const QualWord = &.{},
type: *TypeRef,
name: []const u8,
name_loc: Loc,
array_dims: []const ?*Expr,
semantics: []const Semantic,
bitfield: ?*Expr = null,
init: ?*Expr = null,
/// Arguments of a variable template specialization: `v<T, T>`.
specialization_args: []const TemplateArg = &.{},
};
pub const TemplateParam = struct {
loc: Loc,
name: []const u8,
/// null for `typename T` / `class T`; the type for value parameters.
value_type: ?*TypeRef,
default: ?TemplateArg,
};
pub const FuncDecl = struct {
attrs: []const Attribute,
quals: Qualifiers,
qual_words: []const QualWord = &.{},
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,
/// Function name; for operators `operator+`, `operator[]`, `operator()`.
name: Name,
params: []const VarDecl,
ret_semantics: []const Semantic,
/// Array dimensions after the parameter list (`T f()[N]`).
ret_dims: []const ?*Expr = &.{},
/// Trailing `const` on methods.
is_const: bool,
body: ?*Stmt,
};
pub const StructDecl = struct {
attrs: []const Attribute,
keyword: enum { @"struct", class, interface },
template_params: []const TemplateParam,
name: ?[]const u8,
/// Arguments of a partial / explicit specialization: `S<true, T>`.
specialization_args: []const TemplateArg = &.{},
bases: []const *TypeRef,
/// Null for a forward declaration.
members: ?[]const *Decl,
};
pub const CBufferDecl = struct {
attrs: []const Attribute = &.{},
tbuffer: bool,
name: []const u8,
semantics: []const Semantic,
members: []const *Decl,
};
pub const EnumDecl = struct {
name: ?[]const u8,
scoped: bool,
underlying: ?*TypeRef,
values: []const struct { loc: Loc, name: []const u8, value: ?*Expr },
};
pub const Decl = struct {
loc: Loc,
kind: Kind,
pub const Kind = union(enum) {
@"var": VarDecl,
func: FuncDecl,
@"struct": StructDecl,
cbuffer: CBufferDecl,
/// `alias`: written `using name = type;`.
typedef: struct { name: []const u8, type: *TypeRef, array_dims: []const ?*Expr, template_params: []const TemplateParam = &.{}, qual_words: []const QualWord = &.{}, attrs: []const Attribute = &.{}, alias: bool = false },
@"enum": EnumDecl,
namespace: struct { name: []const u8, decls: []const *Decl },
/// `using namespace N;`
using_namespace: Name,
/// `using N::name;`
using_decl: Name,
pragma: []const u8,
static_assert: struct { cond: *Expr, message: ?[]const u8 },
};
};
pub const TranslationUnit = struct {
decls: []const *Decl,
};

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);
}

426
src/front/ast_dump.zig Normal file
View File

@ -0,0 +1,426 @@
//! Compact S-expression dump of the AST, for tests and debugging.
const std = @import("std");
const ast = @import("ast.zig");
const W = std.Io.Writer;
pub fn dumpUnit(w: *W, tu: ast.TranslationUnit) W.Error!void {
for (tu.decls) |d| {
try decl(w, d, 0);
try w.writeByte('\n');
}
}
fn indent(w: *W, n: usize) W.Error!void {
try w.splatByteAll(' ', n * 2);
}
fn name(w: *W, n: ast.Name) W.Error!void {
for (n.parts, 0..) |part, i| {
if (i > 0) try w.writeAll("::");
try w.writeAll(part);
if (n.args.len > 0 and n.args[i].len > 0) try templateArgs(w, n.args[i]);
}
}
fn templateArgs(w: *W, args: []const ast.TemplateArg) W.Error!void {
try w.writeByte('<');
for (args, 0..) |a, i| {
if (i > 0) try w.writeAll(", ");
switch (a) {
.type => |ty| try typeRef(w, ty),
.expr => |e| try expr(w, e),
}
}
try w.writeByte('>');
}
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.decltype) |e| {
try w.writeAll("__decltype(");
try expr(w, e);
return w.writeByte(')');
}
try name(w, t.name);
if (t.args.len > 0) try templateArgs(w, t.args);
try dims(w, t.array_dims);
}
fn quals(w: *W, q: ast.Qualifiers) W.Error!void {
const info = @typeInfo(ast.Qualifiers).@"struct";
inline for (info.field_names, info.field_types) |fname, ftype| {
if (ftype == bool and @field(q, fname)) try w.print("{s} ", .{fname});
}
}
fn attrs(w: *W, list: []const ast.Attribute) W.Error!void {
for (list) |a| {
try w.print("[{s}", .{a.name});
if (a.args.len > 0) {
try w.writeByte('(');
for (a.args, 0..) |e, i| {
if (i > 0) try w.writeAll(", ");
try expr(w, e);
}
try w.writeByte(')');
}
try w.writeAll("] ");
}
}
fn semantics(w: *W, list: []const ast.Semantic) W.Error!void {
for (list) |s| {
switch (s.kind) {
.semantic => try w.print(" : {s}", .{s.values[0]}),
.register, .packoffset, .access => {
try w.print(" : {s}(", .{@tagName(s.kind)});
for (s.values, 0..) |v, i| {
if (i > 0) try w.writeAll(", ");
try w.writeAll(v);
}
try w.writeByte(')');
},
}
}
}
fn dims(w: *W, list: []const ?*ast.Expr) W.Error!void {
for (list) |d| {
try w.writeByte('[');
if (d) |e| try expr(w, e);
try w.writeByte(']');
}
}
fn varDecl(w: *W, v: ast.VarDecl) W.Error!void {
try templateParams(w, v.template_params);
try attrs(w, v.attrs);
try quals(w, v.quals);
try typeRef(w, v.type);
try w.print(" {s}", .{v.name});
try dims(w, v.array_dims);
if (v.bitfield) |b| {
try w.writeAll(" : ");
try expr(w, b);
}
try semantics(w, v.semantics);
if (v.init) |e| {
try w.writeAll(" = ");
try expr(w, e);
}
}
fn templateParams(w: *W, params: []const ast.TemplateParam) W.Error!void {
if (params.len == 0) return;
try w.writeAll("template<");
for (params, 0..) |tp, i| {
if (i > 0) try w.writeAll(", ");
if (tp.value_type) |vt| {
try typeRef(w, vt);
try w.print(" {s}", .{tp.name});
} else try w.print("typename {s}", .{tp.name});
}
try w.writeAll("> ");
}
pub fn decl(w: *W, d: *const ast.Decl, depth: usize) W.Error!void {
try indent(w, depth);
switch (d.kind) {
.@"var" => |v| {
try w.writeAll("(var ");
try varDecl(w, v);
try w.writeByte(')');
},
.func => |f| {
try w.writeAll("(func ");
try templateParams(w, f.template_params);
try attrs(w, f.attrs);
try quals(w, f.quals);
try typeRef(w, f.ret);
try w.writeByte(' ');
try name(w, f.name);
try w.writeByte('(');
for (f.params, 0..) |prm, i| {
if (i > 0) try w.writeAll(", ");
try varDecl(w, prm);
}
try w.writeByte(')');
try dims(w, f.ret_dims);
if (f.is_const) try w.writeAll(" const");
try semantics(w, f.ret_semantics);
if (f.body) |b| {
try w.writeByte('\n');
try stmt(w, b, depth + 1);
}
try w.writeByte(')');
},
.@"struct" => |s| {
try w.print("({s} ", .{@tagName(s.keyword)});
try templateParams(w, s.template_params);
try attrs(w, s.attrs);
try w.writeAll(s.name orelse "<anon>");
if (s.specialization_args.len > 0) try templateArgs(w, s.specialization_args);
for (s.bases) |b| {
try w.writeAll(" : ");
try typeRef(w, b);
}
if (s.members) |members| {
for (members) |m| {
try w.writeByte('\n');
try decl(w, m, depth + 1);
}
} else try w.writeAll(" <fwd>");
try w.writeByte(')');
},
.cbuffer => |c| {
try w.print("({s} {s}", .{ if (c.tbuffer) "tbuffer" else "cbuffer", c.name });
try semantics(w, c.semantics);
for (c.members) |m| {
try w.writeByte('\n');
try decl(w, m, depth + 1);
}
try w.writeByte(')');
},
.typedef => |t| {
try w.writeAll("(typedef ");
try templateParams(w, t.template_params);
try typeRef(w, t.type);
try w.print(" {s}", .{t.name});
try dims(w, t.array_dims);
try w.writeByte(')');
},
.@"enum" => |e| {
try w.print("(enum{s} {s}", .{ if (e.scoped) " class" else "", e.name orelse "<anon>" });
for (e.values) |v| {
try w.print(" {s}", .{v.name});
if (v.value) |x| {
try w.writeByte('=');
try expr(w, x);
}
}
try w.writeByte(')');
},
.namespace => |n| {
try w.print("(namespace {s}", .{n.name});
for (n.decls) |m| {
try w.writeByte('\n');
try decl(w, m, depth + 1);
}
try w.writeByte(')');
},
.using_namespace => |n| {
try w.writeAll("(using namespace ");
try name(w, n);
try w.writeByte(')');
},
.using_decl => |n| {
try w.writeAll("(using ");
try name(w, n);
try w.writeByte(')');
},
.pragma => |p| try w.print("(pragma {s})", .{p}),
.static_assert => |s| {
try w.writeAll("(_Static_assert ");
try expr(w, s.cond);
try w.writeByte(')');
},
}
}
pub fn stmt(w: *W, s: *const ast.Stmt, depth: usize) W.Error!void {
try indent(w, depth);
try attrs(w, s.attrs);
switch (s.kind) {
.compound => |list| {
try w.writeAll("{");
for (list) |c| {
try w.writeByte('\n');
try stmt(w, c, depth + 1);
}
try w.writeAll("}");
},
.decl => |list| {
for (list, 0..) |d, i| {
if (i > 0) try w.writeByte('\n');
try decl(w, d, if (i == 0) 0 else depth);
}
},
.expr => |e| try expr(w, e),
.empty => try w.writeAll("(empty)"),
.@"if" => |x| {
try w.writeAll("(if ");
if (x.cond_decl) |d| {
try decl(w, d, 0);
try w.writeByte(' ');
}
try expr(w, x.cond);
try w.writeByte('\n');
try stmt(w, x.then, depth + 1);
if (x.@"else") |e| {
try w.writeByte('\n');
try stmt(w, e, depth + 1);
}
try w.writeByte(')');
},
.@"for" => |x| {
try w.writeAll("(for ");
if (x.init) |i| try stmt(w, i, 0) else try w.writeAll("-");
try w.writeAll("; ");
if (x.cond) |c| try expr(w, c) else try w.writeAll("-");
try w.writeAll("; ");
if (x.inc) |c| try expr(w, c) else try w.writeAll("-");
try w.writeByte('\n');
try stmt(w, x.body, depth + 1);
try w.writeByte(')');
},
.@"while" => |x| {
try w.writeAll("(while ");
try expr(w, x.cond);
try w.writeByte('\n');
try stmt(w, x.body, depth + 1);
try w.writeByte(')');
},
.do_while => |x| {
try w.writeAll("(do\n");
try stmt(w, x.body, depth + 1);
try w.writeAll(" while ");
try expr(w, x.cond);
try w.writeByte(')');
},
.@"switch" => |x| {
try w.writeAll("(switch ");
try expr(w, x.cond);
try w.writeByte('\n');
try stmt(w, x.body, depth + 1);
try w.writeByte(')');
},
.case => |x| {
try w.writeAll("(case ");
try expr(w, x.value);
try w.writeByte('\n');
try stmt(w, x.stmt, depth + 1);
try w.writeByte(')');
},
.default => |x| {
try w.writeAll("(default\n");
try stmt(w, x, depth + 1);
try w.writeByte(')');
},
.@"break" => try w.writeAll("(break)"),
.@"continue" => try w.writeAll("(continue)"),
.discard => try w.writeAll("(discard)"),
.@"return" => |v| {
try w.writeAll("(return");
if (v) |e| {
try w.writeByte(' ');
try expr(w, e);
}
try w.writeByte(')');
},
}
}
pub fn expr(w: *W, e: *const ast.Expr) W.Error!void {
switch (e.kind) {
.int_lit, .float_lit, .string_lit => |t| try w.writeAll(t),
.bool_lit => |b| try w.writeAll(if (b) "true" else "false"),
.name => |n| try name(w, n),
.this => try w.writeAll("this"),
.unary => |u| {
try w.print("({s} ", .{@tagName(u.op)});
try expr(w, u.operand);
try w.writeByte(')');
},
.binary => |b| {
try w.print("({s} ", .{@tagName(b.op)});
try expr(w, b.lhs);
try w.writeByte(' ');
try expr(w, b.rhs);
try w.writeByte(')');
},
.assign => |a| {
try w.print("({s}= ", .{if (a.op == .assign) "" else @tagName(a.op)});
try expr(w, a.lhs);
try w.writeByte(' ');
try expr(w, a.rhs);
try w.writeByte(')');
},
.conditional => |c| {
try w.writeAll("(? ");
try expr(w, c.cond);
try w.writeByte(' ');
try expr(w, c.then);
try w.writeByte(' ');
try expr(w, c.@"else");
try w.writeByte(')');
},
.call => |c| {
try w.writeAll("(call ");
try expr(w, c.callee);
if (c.template_args.len > 0) {
const tmp: ast.TypeRef = .{ .loc = e.loc, .name = .{ .loc = e.loc, .parts = &.{""} }, .args = c.template_args };
try typeRef(w, &tmp);
}
for (c.args) |a| {
try w.writeByte(' ');
try expr(w, a);
}
try w.writeByte(')');
},
.construct => |c| {
try w.writeAll("(construct ");
try typeRef(w, c.type);
for (c.args) |a| {
try w.writeByte(' ');
try expr(w, a);
}
try w.writeByte(')');
},
.cast => |c| {
try w.writeAll("(cast ");
try typeRef(w, c.type);
try dims(w, c.array_dims);
try w.writeByte(' ');
try expr(w, c.operand);
try w.writeByte(')');
},
.member => |m| {
try w.writeAll("(. ");
try expr(w, m.base);
try w.print(" {s})", .{m.name});
},
.index => |x| {
try w.writeAll("([] ");
try expr(w, x.base);
try w.writeByte(' ');
try expr(w, x.index);
try w.writeByte(')');
},
.init_list => |list| {
try w.writeByte('{');
for (list, 0..) |a, i| {
if (i > 0) try w.writeAll(", ");
try expr(w, a);
}
try w.writeByte('}');
},
.sizeof_type => |t| {
try w.writeAll("(sizeof ");
try typeRef(w, t);
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| {
try w.writeAll("(sizeof ");
try expr(w, x);
try w.writeByte(')');
},
}
}

366
src/front/lexer.zig Normal file
View File

@ -0,0 +1,366 @@
//! HLSL lexer producing preprocessing tokens. Keywords are not distinguished
//! here; the parser classifies identifiers.
const std = @import("std");
const source = @import("source.zig");
const scan = @import("scan.zig");
pub const Kind = enum(u8) {
eof,
/// Unlexable input (stray character, unterminated literal).
invalid,
identifier,
/// pp-number: integer and floating literals with suffixes.
number,
string,
char,
/// Produced by the preprocessor for `#pragma` lines; text holds the
/// pragma body.
pragma,
l_paren,
r_paren,
l_brace,
r_brace,
l_square,
r_square,
semi,
comma,
colon,
colon_colon,
question,
period,
ellipsis,
arrow,
plus,
plus_plus,
plus_equal,
minus,
minus_minus,
minus_equal,
star,
star_equal,
slash,
slash_equal,
percent,
percent_equal,
amp,
amp_amp,
amp_equal,
pipe,
pipe_pipe,
pipe_equal,
caret,
caret_equal,
tilde,
exclaim,
exclaim_equal,
equal,
equal_equal,
less,
less_equal,
less_less,
less_less_equal,
greater,
greater_equal,
greater_greater,
greater_greater_equal,
hash,
hash_hash,
pub fn isPunct(k: Kind) bool {
return @backingInt(k) >= @backingInt(Kind.l_paren);
}
};
pub const Flags = packed struct(u8) {
/// First token on its (physical) line.
bol: bool = false,
/// Preceded by whitespace or a comment.
space: bool = false,
/// Painted by the preprocessor: never macro-expand this identifier.
no_expand: bool = false,
/// Transient, during macro substitution: the token came from an argument.
from_arg: bool = false,
_: u4 = 0,
};
pub const Token = struct {
kind: Kind,
flags: Flags = .{},
/// Spelling. Points into the source text, or into preprocessor-owned
/// memory for tokens created by `#` and `##`.
text: []const u8,
loc: source.Loc,
pub fn is(t: Token, kind: Kind) bool {
return t.kind == kind;
}
pub inline fn isIdent(t: Token, name: []const u8) bool {
// Length first: most keyword checks fail on it without a call.
return t.kind == .identifier and t.text.len == name.len and std.mem.eql(u8, t.text, name);
}
};
pub const Lexer = struct {
text: []const u8,
file: source.FileId,
pos: u32 = 0,
at_bol: bool = true,
pub fn init(text: []const u8, file: source.FileId) Lexer {
return .{ .text = text, .file = file };
}
fn peekAt(l: *const Lexer, i: usize) u8 {
return if (i < l.text.len) l.text[i] else 0;
}
/// Skip whitespace and comments; report whether any was seen and whether
/// a newline was crossed.
fn skipTrivia(l: *Lexer) struct { space: bool, newline: bool } {
var space = false;
var newline = false;
while (l.pos < l.text.len) {
const c = l.text[l.pos];
switch (c) {
' ', '\t', '\r', 0x0b, 0x0c => {
space = true;
l.pos += 1;
},
'\n' => {
newline = true;
space = false;
l.pos += 1;
},
'/' => {
const n = l.peekAt(l.pos + 1);
if (n == '/') {
l.pos = @intCast(scan.findNewline(l.text, l.pos + 2));
space = true;
} else if (n == '*') {
// A newline inside a block comment does not start a
// new line for directive purposes (the comment is one
// space after translation phase 3). An unterminated
// comment runs to EOF.
l.pos = @intCast(scan.skipBlockComment(l.text, l.pos + 2));
space = true;
} else break;
},
else => break,
}
}
return .{ .space = space, .newline = newline };
}
pub fn next(l: *Lexer) Token {
const trivia = l.skipTrivia();
if (trivia.newline) l.at_bol = true;
var flags: Flags = .{ .bol = l.at_bol, .space = trivia.space };
if (l.at_bol) flags.space = false;
l.at_bol = false;
const start = l.pos;
const kind = l.lexToken();
return .{
.kind = kind,
.flags = flags,
.text = l.text[start..l.pos],
.loc = .{ .file = l.file, .offset = start },
};
}
/// Rest of the current line, used for `#error`, `#pragma` and similar.
/// Leaves the lexer at the newline.
pub fn restOfLine(l: *Lexer) []const u8 {
const start = l.pos;
while (l.pos < l.text.len and l.text[l.pos] != '\n') {
// Block comments may contain newlines; skip them as a unit.
if (l.text[l.pos] == '/' and l.peekAt(l.pos + 1) == '*') {
if (std.mem.indexOfPos(u8, l.text, l.pos + 2, "*/")) |end| {
l.pos = @intCast(end + 2);
continue;
}
}
if (l.text[l.pos] == '/' and l.peekAt(l.pos + 1) == '/') {
const s = l.text[start..l.pos];
while (l.pos < l.text.len and l.text[l.pos] != '\n') l.pos += 1;
return std.mem.trim(u8, s, " \t\r");
}
l.pos += 1;
}
return std.mem.trim(u8, l.text[start..l.pos], " \t\r");
}
/// After `#include`, lex `<...>` as a header name. Returns null if the
/// next token does not start with `<`.
pub fn headerName(l: *Lexer) ?Token {
const trivia = l.skipTrivia();
if (trivia.newline) {
l.at_bol = true;
return null;
}
if (l.peekAt(l.pos) != '<') return null;
const start = l.pos;
var i = l.pos + 1;
while (i < l.text.len and l.text[i] != '>' and l.text[i] != '\n') i += 1;
if (i >= l.text.len or l.text[i] != '>') return null;
l.pos = @intCast(i + 1);
return .{ .kind = .string, .flags = .{ .space = trivia.space }, .text = l.text[start..l.pos], .loc = .{ .file = l.file, .offset = start } };
}
/// Skip the rest of the current line (used for skipped conditional
/// blocks and after directives). Works token by token so that `/*` or
/// `//` inside string literals is not mistaken for a comment.
pub fn skipLine(l: *Lexer) void {
// At the start of a line, its first token is part of this line.
var line_start = l.at_bol;
while (true) {
const saved = l.*;
const t = l.next();
if (t.kind == .eof or (t.flags.bol and !line_start)) {
l.* = saved;
return;
}
line_start = false;
}
}
fn lexToken(l: *Lexer) Kind {
if (l.pos >= l.text.len) return .eof;
const c = l.text[l.pos];
l.pos += 1;
switch (c) {
'a'...'z', 'A'...'Z', '_' => {
l.pos = @intCast(scan.skipIdent(l.text, l.pos));
return .identifier;
},
'0'...'9' => {
l.lexPpNumber();
return .number;
},
'.' => {
if (std.ascii.isDigit(l.peekAt(l.pos))) {
l.lexPpNumber();
return .number;
}
if (l.peekAt(l.pos) == '.' and l.peekAt(l.pos + 1) == '.') {
l.pos += 2;
return .ellipsis;
}
return .period;
},
'"' => return l.lexQuoted('"', .string),
'\'' => return l.lexQuoted('\'', .char),
'(' => return .l_paren,
')' => return .r_paren,
'{' => return .l_brace,
'}' => return .r_brace,
'[' => return .l_square,
']' => return .r_square,
';' => return .semi,
',' => return .comma,
'?' => return .question,
'~' => return .tilde,
':' => return if (l.eat(':')) .colon_colon else .colon,
'+' => return if (l.eat('+')) .plus_plus else if (l.eat('=')) .plus_equal else .plus,
'-' => return if (l.eat('-')) .minus_minus else if (l.eat('=')) .minus_equal else if (l.eat('>')) .arrow else .minus,
'*' => return if (l.eat('=')) .star_equal else .star,
'/' => return if (l.eat('=')) .slash_equal else .slash,
'%' => return if (l.eat('=')) .percent_equal else .percent,
'&' => return if (l.eat('&')) .amp_amp else if (l.eat('=')) .amp_equal else .amp,
'|' => return if (l.eat('|')) .pipe_pipe else if (l.eat('=')) .pipe_equal else .pipe,
'^' => return if (l.eat('=')) .caret_equal else .caret,
'!' => return if (l.eat('=')) .exclaim_equal else .exclaim,
'=' => return if (l.eat('=')) .equal_equal else .equal,
'#' => return if (l.eat('#')) .hash_hash else .hash,
'<' => {
if (l.eat('<')) return if (l.eat('=')) .less_less_equal else .less_less;
return if (l.eat('=')) .less_equal else .less;
},
'>' => {
if (l.eat('>')) return if (l.eat('=')) .greater_greater_equal else .greater_greater;
return if (l.eat('=')) .greater_equal else .greater;
},
else => return .invalid,
}
}
fn eat(l: *Lexer, c: u8) bool {
if (l.peekAt(l.pos) == c) {
l.pos += 1;
return true;
}
return false;
}
fn lexPpNumber(l: *Lexer) void {
while (l.pos < l.text.len) {
const c = l.text[l.pos];
if ((c == '+' or c == '-') and l.pos > 0) {
const p = l.text[l.pos - 1];
if (p == 'e' or p == 'E' or p == 'p' or p == 'P') {
l.pos += 1;
continue;
}
break;
}
// dxc also takes '#' (for `1.#INF`).
if (isIdentChar(c) or c == '.' or c == '#') {
l.pos += 1;
continue;
}
break;
}
}
fn lexQuoted(l: *Lexer, quote: u8, kind: Kind) Kind {
while (l.pos < l.text.len) {
const c = l.text[l.pos];
if (c == '\n') return .invalid;
l.pos += 1;
if (c == '\\' and l.pos < l.text.len) {
l.pos += 1;
continue;
}
if (c == quote) return kind;
}
return .invalid;
}
};
pub fn isIdentChar(c: u8) bool {
return std.ascii.isAlphanumeric(c) or c == '_';
}
fn expectKinds(text: []const u8, kinds: []const Kind) !void {
var l = Lexer.init(text, 0);
for (kinds) |k| try std.testing.expectEqual(k, l.next().kind);
try std.testing.expectEqual(Kind.eof, l.next().kind);
}
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("x::y->z...", &.{ .identifier, .colon_colon, .identifier, .arrow, .identifier, .ellipsis });
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 });
}
test "skipLine ignores comment markers inside strings" {
var l = Lexer.init("x = \"/*\"; y\n#endif\n", 0);
l.skipLine();
const t = l.next();
try std.testing.expect(t.kind == .hash and t.flags.bol);
}
test "comments, flags and lines" {
var l = Lexer.init("a /* x\n y */ b // c\n c", 0);
const a = l.next();
try std.testing.expect(a.flags.bol);
const b = l.next();
try std.testing.expect(!b.flags.bol and b.flags.space);
const c = l.next();
try std.testing.expect(c.flags.bol);
try std.testing.expectEqualStrings("c", c.text);
}

2334
src/front/parser.zig Normal file

File diff suppressed because it is too large Load Diff

87
src/front/pp_print.zig Normal file
View File

@ -0,0 +1,87 @@
//! `-P` output: preprocessed text with `#line` markers, laid out like
//! clang's PrintPreprocessedOutput.
const std = @import("std");
const lexer = @import("lexer.zig");
const Preprocessor = @import("preproc.zig").Preprocessor;
const Token = lexer.Token;
pub fn print(pp: *Preprocessor, w: *std.Io.Writer) !void {
var cur_file: ?[]const u8 = null;
var cur_line: u32 = 0;
var prev: ?Token = null;
var line_has_tokens = false;
var cursor: Preprocessor.LineCursor = .{};
while (true) {
const t = try pp.next();
if (t.kind == .eof) break;
const p = pp.presumedLocCursor(t.loc, &cursor);
// Paths usually share storage, so compare pointers before bytes.
const same_file = if (cur_file) |cf| (cf.ptr == p.file.ptr and cf.len == p.file.len) or std.mem.eql(u8, cf, p.file) else false;
if (!same_file) {
if (line_has_tokens) try w.writeByte('\n');
try w.print("#line {d} \"", .{p.line});
try writeEscaped(w, p.file);
try w.writeAll("\"\n");
cur_file = p.file;
cur_line = p.line;
line_has_tokens = false;
prev = null;
} else if (p.line > cur_line) {
// Short gaps are reproduced with newlines; long ones get a marker.
const gap = p.line - cur_line;
if (gap < 8) {
try w.splatByteAll('\n', gap);
} else {
if (line_has_tokens) try w.writeByte('\n');
try w.print("#line {d} \"", .{p.line});
try writeEscaped(w, p.file);
try w.writeAll("\"\n");
}
cur_line = p.line;
line_has_tokens = false;
prev = null;
} else if (t.kind == .pragma and line_has_tokens) {
try w.writeByte('\n');
cur_line += 1;
line_has_tokens = false;
prev = null;
}
if (t.kind == .pragma) {
try w.print("#pragma {s}\n", .{t.text});
cur_line += 1;
line_has_tokens = false;
prev = null;
continue;
}
if (prev) |pv| {
if (t.flags.space or avoidConcat(pv, t)) try w.writeByte(' ');
} else if (t.flags.space and line_has_tokens) try w.writeByte(' ');
try w.writeAll(t.text);
prev = t;
line_has_tokens = true;
}
if (line_has_tokens) try w.writeByte('\n');
}
fn writeEscaped(w: *std.Io.Writer, s: []const u8) !void {
for (s) |c| {
if (c == '"' or c == '\\') try w.writeByte('\\');
try w.writeByte(c);
}
}
/// True when printing `b` directly after `a` would lex differently.
fn avoidConcat(a: Token, b: Token) bool {
if (a.text.len == 0 or b.text.len == 0) return false;
const last = a.text[a.text.len - 1];
const first = b.text[0];
if (lexer.isIdentChar(last) and (lexer.isIdentChar(first) or first == '.')) return true;
if (a.kind == .number and (first == '+' or first == '-' or first == '.')) return true;
var buf: [8]u8 = undefined;
if (a.text.len > 3 or b.text.len > 3 or !a.kind.isPunct() or !b.kind.isPunct()) return false;
const joined = std.fmt.bufPrint(&buf, "{s}{s}", .{ a.text, b.text }) catch return true;
var l = lexer.Lexer.init(joined, 0);
return l.next().text.len != a.text.len;
}

1633
src/front/preproc.zig Normal file

File diff suppressed because it is too large Load Diff

126
src/front/scan.zig Normal file
View File

@ -0,0 +1,126 @@
//! Byte-scanning primitives for the lexer and source manager, written with
//! portable `@Vector`s (the vector length comes from
//! std.simd.suggestVectorLength; no per-platform code).
const std = @import("std");
const vec_len = std.simd.suggestVectorLength(u8) orelse 16;
const V = @Vector(vec_len, u8);
const Mask = @Int(.unsigned, vec_len);
inline fn load(text: []const u8, i: usize) V {
return text[i..][0..vec_len].*;
}
inline fn bits(m: @Vector(vec_len, bool)) Mask {
return @bitCast(m);
}
/// Index of the first byte at or after `start` that is not ' ' or '\t',
/// or text.len.
pub fn skipBlanks(text: []const u8, start: usize) usize {
var i = start;
while (i + vec_len <= text.len) : (i += vec_len) {
const b = load(text, i);
const blank = bits(b == @as(V, @splat(' '))) | bits(b == @as(V, @splat('\t')));
if (blank != std.math.maxInt(Mask)) return i + @ctz(~blank);
}
while (i < text.len and (text[i] == ' ' or text[i] == '\t')) i += 1;
return i;
}
/// Index of the first '\n' at or after `start`, or text.len.
pub fn findNewline(text: []const u8, start: usize) usize {
return std.mem.indexOfScalarPos(u8, text, start, '\n') orelse text.len;
}
/// Index just past the `*/` closing a block comment whose body starts at
/// `start`, or text.len if it is unterminated.
pub fn skipBlockComment(text: []const u8, start: usize) usize {
var i = start;
while (std.mem.indexOfScalarPos(u8, text, i, '*')) |star| {
if (star + 1 < text.len and text[star + 1] == '/') return star + 2;
i = star + 1;
}
return text.len;
}
/// Append the offset of the byte after every '\n' in `text`.
pub fn appendLineStarts(gpa: std.mem.Allocator, list: *std.ArrayList(u32), text: []const u8) !void {
var i: usize = 0;
while (i + vec_len <= text.len) : (i += vec_len) {
var m = bits(load(text, i) == @as(V, @splat('\n')));
if (m == 0) continue;
try list.ensureUnusedCapacity(gpa, @popCount(m));
while (m != 0) : (m &= m - 1) {
list.appendAssumeCapacity(@intCast(i + @ctz(m) + 1));
}
}
while (i < text.len) : (i += 1) {
if (text[i] == '\n') try list.append(gpa, @intCast(i + 1));
}
}
/// Number of '\n' bytes in `text`.
pub fn countNewlines(text: []const u8) usize {
var n: usize = 0;
var i: usize = 0;
while (i + vec_len <= text.len) : (i += vec_len) {
n += @popCount(bits(load(text, i) == @as(V, @splat('\n'))));
}
while (i < text.len) : (i += 1) n += @intFromBool(text[i] == '\n');
return n;
}
/// Character classes for the scalar lexer paths (identifiers are usually
/// shorter than a vector, so a table lookup beats SIMD there).
pub const ident_char: [256]bool = blk: {
var t: [256]bool = @splat(false);
for ('a'..'z' + 1) |c| t[c] = true;
for ('A'..'Z' + 1) |c| t[c] = true;
for ('0'..'9' + 1) |c| t[c] = true;
t['_'] = true;
break :blk t;
};
/// Index of the first non-identifier byte at or after `start`.
pub fn skipIdent(text: []const u8, start: usize) usize {
var i = start;
while (i < text.len and ident_char[text[i]]) i += 1;
return i;
}
fn refLineStarts(gpa: std.mem.Allocator, text: []const u8) ![]u32 {
var l: std.ArrayList(u32) = .empty;
for (text, 0..) |c, i| if (c == '\n') try l.append(gpa, @intCast(i + 1));
return l.toOwnedSlice(gpa);
}
test "vector scans agree with scalar references" {
const gpa = std.testing.allocator;
var prng = std.Random.DefaultPrng.init(0x5eed);
const r = prng.random();
const alphabet = " \t\n/*ab_9\"\\";
for (0..300) |_| {
const len = r.uintLessThan(usize, 200);
const text = try gpa.alloc(u8, len);
defer gpa.free(text);
for (text) |*c| c.* = alphabet[r.uintLessThan(usize, alphabet.len)];
const start = if (len == 0) 0 else r.uintLessThan(usize, len);
var blanks = start;
while (blanks < len and (text[blanks] == ' ' or text[blanks] == '\t')) blanks += 1;
try std.testing.expectEqual(blanks, skipBlanks(text, start));
const ref_end = if (std.mem.indexOfPos(u8, text, start, "*/")) |e| e + 2 else len;
try std.testing.expectEqual(ref_end, skipBlockComment(text, start));
const ref = try refLineStarts(gpa, text);
defer gpa.free(ref);
var got: std.ArrayList(u32) = .empty;
defer got.deinit(gpa);
try appendLineStarts(gpa, &got, text);
try std.testing.expectEqualSlices(u32, ref, got.items);
try std.testing.expectEqual(ref.len, countNewlines(text));
}
}

385
src/front/source.zig Normal file
View File

@ -0,0 +1,385 @@
//! Source files and locations.
const std = @import("std");
const Allocator = std.mem.Allocator;
const scan = @import("scan.zig");
pub const FileId = u32;
/// A source location. Either a file location (`file` is a FileId,
/// `offset` a byte offset), or a macro location (`file` has the top bit set
/// and `offset` indexes SourceManager.expansions), as in clang.
pub const Loc = struct {
file: FileId,
/// Byte offset into the file's (line-spliced) text, or an expansion
/// index for macro locations.
offset: u32,
pub const none: Loc = .{ .file = std.math.maxInt(FileId), .offset = 0 };
const macro_bit: FileId = 1 << 31;
pub fn isNone(l: Loc) bool {
return l.file == none.file;
}
pub fn isMacro(l: Loc) bool {
return !l.isNone() and l.file & macro_bit != 0;
}
pub fn advance(l: Loc, n: u32) Loc {
if (l.isNone() or l.isMacro()) return l;
return .{ .file = l.file, .offset = l.offset + n };
}
};
/// One token produced by a macro expansion.
pub const Expansion = struct {
/// Where the token was spelled: in the macro definition, or for
/// argument tokens at the invocation. May itself be a macro location.
spelling: Loc,
/// Location of the macro name being expanded (may be a macro location
/// for nested expansions).
expansion: Loc,
macro_name: []const u8,
/// The token came from a macro argument: it is reported at its own
/// spelling rather than at the macro name.
is_arg: bool,
};
/// Reads files on behalf of the compiler (real filesystem, or in-memory for
/// tests and for in-process callers).
pub const FileSystem = struct {
ctx: *anyopaque,
readFn: *const fn (ctx: *anyopaque, gpa: Allocator, path: []const u8) ?[]const u8,
pub fn read(fs: FileSystem, gpa: Allocator, path: []const u8) ?[]const u8 {
return fs.readFn(fs.ctx, gpa, path);
}
};
/// In-memory file system: path -> contents.
pub const MemoryFs = struct {
files: std.StringHashMapUnmanaged([]const u8) = .empty,
pub fn put(m: *MemoryFs, gpa: Allocator, path: []const u8, text: []const u8) !void {
try m.files.put(gpa, path, text);
}
pub fn deinit(m: *MemoryFs, gpa: Allocator) void {
m.files.deinit(gpa);
}
pub fn fileSystem(m: *MemoryFs) FileSystem {
return .{ .ctx = m, .readFn = readImpl };
}
fn readImpl(ctx: *anyopaque, gpa: Allocator, path: []const u8) ?[]const u8 {
const m: *MemoryFs = @ptrCast(@alignCast(ctx));
const text = m.files.get(path) orelse return null;
return gpa.dupe(u8, text) catch null;
}
};
/// Real file system through std.Io.
pub const DiskFs = struct {
io: std.Io,
pub fn fileSystem(d: *DiskFs) FileSystem {
return .{ .ctx = d, .readFn = readImpl };
}
fn readImpl(ctx: *anyopaque, gpa: Allocator, path: []const u8) ?[]const u8 {
const d: *DiskFs = @ptrCast(@alignCast(ctx));
return std.Io.Dir.cwd().readFileAlloc(d.io, path, gpa, .limited(256 << 20)) catch null;
}
};
/// Text of a source file, shared by every inclusion of it.
pub const Content = struct {
text: []const u8,
/// Offsets of the first byte of each line.
line_starts: []const u32,
/// Include-guard macro, computed lazily by the preprocessor.
guard: Guard = .unknown,
pub const Guard = union(enum) {
unknown,
none,
macro: []const u8,
};
};
/// One inclusion of a file. Each `#include` gets its own FileId (so that
/// `#line` and other per-inclusion state stay separate) but shares Content.
pub const File = struct {
path: []const u8,
text: []const u8,
line_starts: []const u32,
content: *Content,
/// Location of the `#include` that entered this file (none for the
/// main file and pseudo-files).
included_from: Loc = .none,
};
pub const LineCol = struct { line: u32, col: u32 };
/// A `#line` directive: lines after `phys_line` are renumbered from `line`.
pub const LineOverride = struct {
phys_line: u32,
line: u32,
name: ?[]const u8,
};
/// File name and line as remapped by `#line`.
pub const PresumedLoc = struct { file: []const u8, line: u32 };
pub const SourceManager = struct {
arena: std.heap.ArenaAllocator,
files: std.ArrayList(File) = .empty,
fs: FileSystem,
/// path -> contents, or null if the path could not be read.
cache: std.StringHashMapUnmanaged(?*Content) = .empty,
expansions: std.ArrayList(Expansion) = .empty,
line_overrides: std.AutoHashMapUnmanaged(FileId, std.ArrayList(LineOverride)) = .empty,
pub fn init(gpa: Allocator, fs: FileSystem) SourceManager {
return .{ .arena = .init(gpa), .fs = fs };
}
pub fn deinit(sm: *SourceManager) void {
sm.arena.deinit();
}
pub fn allocator(sm: *SourceManager) Allocator {
return sm.arena.allocator();
}
/// Load a file through the cache; null if it cannot be read. Each call
/// returns a new FileId, but the file system is read once per path.
pub fn load(sm: *SourceManager, path: []const u8) !?FileId {
const a = sm.allocator();
const gop = try sm.cache.getOrPut(a, path);
if (!gop.found_existing) {
gop.key_ptr.* = try a.dupe(u8, path);
gop.value_ptr.* = if (sm.fs.read(a, path)) |raw| try sm.makeContent(raw) else null;
}
const content = gop.value_ptr.* orelse return null;
return try sm.addInclusion(path, content);
}
/// Register in-memory text under `path`, through the same cache as
/// `load` (used for compiled-in headers).
pub fn loadText(sm: *SourceManager, path: []const u8, raw: []const u8) !FileId {
const a = sm.allocator();
const gop = try sm.cache.getOrPut(a, path);
if (!gop.found_existing or gop.value_ptr.* == null) {
gop.key_ptr.* = try a.dupe(u8, path);
gop.value_ptr.* = try sm.makeContent(raw);
}
return sm.addInclusion(path, gop.value_ptr.*.?);
}
/// Register uncached text under `path` (main file text, predefines).
pub fn addFile(sm: *SourceManager, path: []const u8, raw: []const u8) !FileId {
return sm.addInclusion(path, try sm.makeContent(raw));
}
/// Backslash-newline sequences are removed (translation phase 2), so
/// offsets refer to the spliced text.
fn makeContent(sm: *SourceManager, raw: []const u8) !*Content {
const a = sm.allocator();
const utf8 = try decodeUtf16(a, raw) orelse raw;
const no_bom = if (std.mem.startsWith(u8, utf8, "\xEF\xBB\xBF")) utf8[3..] else utf8;
const text = try spliceLines(a, no_bom);
var starts: std.ArrayList(u32) = .empty;
try starts.ensureTotalCapacity(a, text.len / 32 + 16);
starts.appendAssumeCapacity(0);
try scan.appendLineStarts(a, &starts, text);
const content = try a.create(Content);
content.* = .{ .text = text, .line_starts = try starts.toOwnedSlice(a) };
return content;
}
fn addInclusion(sm: *SourceManager, path: []const u8, content: *Content) !FileId {
const a = sm.allocator();
try sm.files.append(a, .{
.path = try a.dupe(u8, path),
.text = content.text,
.line_starts = content.line_starts,
.content = content,
});
return @intCast(sm.files.items.len - 1);
}
pub fn file(sm: *const SourceManager, id: FileId) *const File {
return &sm.files.items[id];
}
pub fn addLineOverride(sm: *SourceManager, id: FileId, ov: LineOverride) !void {
const a = sm.allocator();
const gop = try sm.line_overrides.getOrPut(a, id);
if (!gop.found_existing) gop.value_ptr.* = .empty;
try gop.value_ptr.append(a, ov);
}
/// File name and line of `loc` after `#line` remapping.
pub fn presumedLoc(sm: *const SourceManager, loc: Loc) PresumedLoc {
if (loc.isNone()) return .{ .file = "<unknown>", .line = 0 };
const fl = sm.fileLoc(loc);
return sm.presumedLine(fl.file, sm.lineCol(fl).line);
}
pub fn presumedLine(sm: *const SourceManager, id: FileId, phys: u32) PresumedLoc {
var result: PresumedLoc = .{ .file = sm.file(id).path, .line = phys };
if (sm.line_overrides.count() == 0) return result;
if (sm.line_overrides.get(id)) |list| {
for (list.items) |ov| {
if (ov.phys_line >= phys) break;
result.line = ov.line + (phys - ov.phys_line - 1);
if (ov.name) |n| result.file = n;
}
}
return result;
}
pub fn setIncludedFrom(sm: *SourceManager, id: FileId, loc: Loc) void {
sm.files.items[id].included_from = loc;
}
/// Record a macro-expanded token and return its macro location.
pub fn addExpansion(sm: *SourceManager, e: Expansion) !Loc {
try sm.expansions.append(sm.allocator(), e);
return .{ .file = Loc.macro_bit, .offset = @intCast(sm.expansions.items.len - 1) };
}
pub fn expansion(sm: *const SourceManager, loc: Loc) *const Expansion {
std.debug.assert(loc.isMacro());
return &sm.expansions.items[loc.offset];
}
/// The file location a (possibly macro) location is reported at: the
/// outermost expansion point, or for argument tokens their own position.
pub fn fileLoc(sm: *const SourceManager, loc: Loc) Loc {
var l = loc;
while (l.isMacro()) {
const e = sm.expansion(l);
l = if (e.is_arg) e.spelling else e.expansion;
}
return l;
}
/// Where the token was actually written.
pub fn spellingLoc(sm: *const SourceManager, loc: Loc) Loc {
var l = loc;
while (l.isMacro()) l = sm.expansion(l).spelling;
return l;
}
/// 1-based line and column (macro locations are resolved to fileLoc).
pub fn lineCol(sm: *const SourceManager, loc_in: Loc) LineCol {
const loc = sm.fileLoc(loc_in);
const f = sm.file(loc.file);
const idx = std.sort.upperBound(u32, f.line_starts, loc.offset, struct {
fn cmp(target: u32, x: u32) std.math.Order {
return std.math.order(target, x);
}
}.cmp);
const line: u32 = @intCast(idx);
return .{ .line = line, .col = loc.offset - f.line_starts[line - 1] + 1 };
}
/// Text of the line containing `loc`, without the newline.
pub fn lineText(sm: *const SourceManager, loc_in: Loc) []const u8 {
const loc = sm.fileLoc(loc_in);
const f = sm.file(loc.file);
const lc = sm.lineCol(loc);
const start = f.line_starts[lc.line - 1];
var end = start;
while (end < f.text.len and f.text[end] != '\n' and f.text[end] != '\r') end += 1;
return f.text[start..end];
}
};
/// UTF-16 text with a byte-order mark is converted to UTF-8 (as dxc does);
/// returns null for anything else.
fn decodeUtf16(a: Allocator, raw: []const u8) !?[]const u8 {
if (raw.len < 2) return null;
const little = raw[0] == 0xFF and raw[1] == 0xFE;
const big = raw[0] == 0xFE and raw[1] == 0xFF;
if (!little and !big) return null;
const units = try a.alloc(u16, (raw.len - 2) / 2);
for (units, 0..) |*u, i| {
const b = raw[2 + 2 * i ..][0..2];
u.* = if (little) std.mem.readInt(u16, b, .little) else std.mem.readInt(u16, b, .big);
}
// Lone surrogates make the text invalid; fall back to the raw bytes.
return std.unicode.utf16LeToUtf8Alloc(a, units) catch null;
}
fn spliceLines(a: Allocator, raw: []const u8) ![]const u8 {
if (std.mem.indexOfScalar(u8, raw, '\\') == null) return raw;
var out: std.ArrayList(u8) = .empty;
try out.ensureTotalCapacity(a, raw.len);
var i: usize = 0;
while (i < raw.len) {
if (raw[i] == '\\') {
var j = i + 1;
// Clang tolerates whitespace between the backslash and newline.
while (j < raw.len and (raw[j] == ' ' or raw[j] == '\t')) j += 1;
if (j < raw.len and raw[j] == '\n') {
i = j + 1;
continue;
}
if (j + 1 < raw.len and raw[j] == '\r' and raw[j + 1] == '\n') {
i = j + 2;
continue;
}
}
out.appendAssumeCapacity(raw[i]);
i += 1;
}
return out.items;
}
test "line and column lookup" {
var mfs: MemoryFs = .{};
var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem());
defer sm.deinit();
const id = try sm.addFile("a.hlsl", "ab\ncd\n\nx");
try std.testing.expectEqual(LineCol{ .line = 1, .col = 1 }, sm.lineCol(.{ .file = id, .offset = 0 }));
try std.testing.expectEqual(LineCol{ .line = 2, .col = 2 }, sm.lineCol(.{ .file = id, .offset = 4 }));
try std.testing.expectEqual(LineCol{ .line = 4, .col = 1 }, sm.lineCol(.{ .file = id, .offset = 7 }));
try std.testing.expectEqualStrings("cd", sm.lineText(.{ .file = id, .offset = 3 }));
}
test "files are read once per path" {
var mfs: MemoryFs = .{};
defer mfs.deinit(std.testing.allocator);
try mfs.put(std.testing.allocator, "a.h", "x");
var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem());
defer sm.deinit();
const a = (try sm.load("a.h")).?;
const b = (try sm.load("a.h")).?;
try std.testing.expect(a != b);
try std.testing.expectEqual(sm.file(a).content, sm.file(b).content);
try std.testing.expect(try sm.load("missing.h") == null);
try std.testing.expect(try sm.load("missing.h") == null);
}
test "UTF-16 sources are decoded" {
var mfs: MemoryFs = .{};
var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem());
defer sm.deinit();
const id = try sm.addFile("le.hlsl", "\xFF\xFEi\x00n\x00t\x00");
try std.testing.expectEqualStrings("int", sm.file(id).text);
const id2 = try sm.addFile("be.hlsl", "\xFE\xFF\x00x");
try std.testing.expectEqualStrings("x", sm.file(id2).text);
}
test "line splicing" {
var mfs: MemoryFs = .{};
var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem());
defer sm.deinit();
const id = try sm.addFile("a.hlsl", "#define A 1 \\\n + 2\nx");
try std.testing.expectEqualStrings("#define A 1 + 2\nx", sm.file(id).text);
}

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

@ -0,0 +1,712 @@
//! 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,
/// `groupshared` parameters: a pointer to the caller's groupshared
/// variable (by_ref too).
groupshared: bool = false,
/// 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),
/// `[noinline]` (plain functions, not methods or template instances):
/// libraries keep it a function of its own.
no_inline: bool = false,
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).
/// A global struct of resources: its resources' globals (null:
/// unused) at offsets within the struct's bindings (`count` of them).
members: []const struct { global: ?u32, offset: u32 } = &.{},
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 = .{},
/// A global struct holds resources (dxc's SPIR-V then numbers array
/// elements' bindings separately, as with -fspv-flatten-resource-arrays).
resource_structs: bool = false,
/// -enable-16bit-types: half and 16-bit integers are native types.
native_16bit: bool = false,
/// -Zpr: matrices that are structured buffer elements themselves
/// (not fields, which carry their own orientation) are row_major.
/// DXIL only: dxc's SPIR-V keeps those column_major.
row_major: 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');
}

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

@ -0,0 +1,310 @@
//! 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| if (!isOpaque(t, f.type)) {
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| {
// (Resources in structs take no space in buffers.)
if (isOpaque(t, f.type)) {
o.* = off;
continue;
}
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,
}
}
/// Resources (and arrays of them): no data.
pub fn isOpaque(t: *const TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) {
.resource, .sampler => true,
.array => |a| isOpaque(t, a.elem),
else => false,
};
}
pub fn flatCount(t: *const TypeTable, ty: TypeId) Error!u32 {
return switch (t.get(ty)) {
.scalar, .@"enum" => 1,
.resource, .sampler => 0,
.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));
}

2819
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`.
pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
return switch (op) {
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant => 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);
}

500
src/ir/split_resources.zig Normal file
View File

@ -0,0 +1,500 @@
//! Resources inside structs, taken apart for SPIR-V (dxc gets there by
//! legalization: inlining and scalar replacement). After this pass no
//! struct value or local carries a resource: each resource member of a
//! local is a resource local of its own, each struct value has its
//! resources alongside, function parameters holding resources gain a
//! resource parameter per member, and functions returning resources
//! return the parameter or global they come from. The SPIR-V emitter
//! leaves resource members out of struct types.
const std = @import("std");
const Allocator = std.mem.Allocator;
const ir = @import("ir.zig");
const types = @import("../sema/types.zig");
const opt = @import("opt.zig");
const diag = @import("../diag.zig");
const Ref = ir.Ref;
const TypeId = types.TypeId;
const TypeTable = types.TypeTable;
pub const Error = Allocator.Error || error{Unsupported};
fn isOpaque(t: *const TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) {
.resource => |r| !std.mem.eql(u8, r.name, "RayQuery"),
.sampler => true,
.array => |a| isOpaque(t, a.elem),
else => false,
};
}
/// A struct (or array of structs) with a resource in it.
pub fn holdsResources(t: *const TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) {
.array => |a| holdsResources(t, a.elem),
.@"struct" => |st| for (st.fields.items) |f| {
if (isOpaque(t, f.type) or holdsResources(t, f.type)) break true;
} else false,
else => false,
};
}
/// The resource members (resources, or arrays of them) of `ty`, in order.
fn leafTypes(a: Allocator, t: *const TypeTable, ty: TypeId, out: *std.ArrayList(TypeId)) Allocator.Error!void {
if (isOpaque(t, ty)) return out.append(a, ty);
switch (t.get(ty)) {
.array => |arr| for (0..arr.len) |_| try leafTypes(a, t, arr.elem, out),
.@"struct" => |st| for (st.fields.items) |f| try leafTypes(a, t, f.type, out),
else => {},
}
}
/// An out / inout parameter of a resource (or array of them).
fn isRefResource(t: *const TypeTable, prm: ir.Param) bool {
return prm.by_ref and !prm.groupshared and prm.dir != .in and isOpaque(t, prm.ty);
}
fn leafCount(t: *const TypeTable, ty: TypeId) u32 {
if (isOpaque(t, ty)) return 1;
return switch (t.get(ty)) {
.array => |arr| arr.len * leafCount(t, arr.elem),
.@"struct" => |st| blk: {
var n: u32 = 0;
for (st.fields.items) |f| n += leafCount(t, f.type);
break :blk n;
},
else => 0,
};
}
/// Member / element `k`'s place among `ty`'s leaves, and its type.
fn member(t: *const TypeTable, ty: TypeId, k: u32) struct { start: u32, ty: TypeId } {
switch (t.get(ty)) {
.array => |arr| return .{ .start = k * leafCount(t, arr.elem), .ty = arr.elem },
.@"struct" => |st| {
var s: u32 = 0;
for (st.fields.items[0..k]) |f| s += leafCount(t, f.type);
return .{ .start = s, .ty = st.fields.items[k].type };
},
else => return .{ .start = 0, .ty = ty },
}
}
/// Where a returned resource comes from.
const Source = union(enum) { param: u32, global: u32 };
const FuncInfo = struct {
done: bool = false,
/// Original parameter index -> index of its first leaf parameter.
leaf_params: []?u32 = &.{},
/// Original parameter index -> new index (null: an out / inout
/// resource, now a local of the callee).
param_map: []?u32 = &.{},
/// Out / inout resources: the parameter bringing an inout one's value
/// in, and where the value going out comes from.
ref_in: []?u32 = &.{},
ref_out: []?Source = &.{},
/// The returned resources' origins (functions returning resources).
ret: ?[]const Source = null,
/// The function returned only resources and now returns nothing.
ret_void: bool = false,
};
const Pass = struct {
a: Allocator,
m: *ir.Module,
t: *TypeTable,
diags: *diag.Diagnostics,
infos: []FuncInfo,
/// The current function's parameter index map.
cur_map: []?u32 = &.{},
fn fail(p: *Pass, comptime fmt: []const u8, args: anytype) Error {
p.diags.err(.none, "SPIR-V code generation: " ++ fmt ++ " is not supported yet", args);
return error.Unsupported;
}
/// Adds a leaf parameter per resource member of each parameter that
/// holds resources (by value or by reference).
fn signature(p: *Pass, fi: u32) Allocator.Error!void {
const f = p.m.functions.items[fi];
const info = &p.infos[fi];
const np_old = f.params.len;
info.leaf_params = try p.a.alloc(?u32, np_old);
info.param_map = try p.a.alloc(?u32, np_old);
info.ref_in = try p.a.alloc(?u32, np_old);
info.ref_out = try p.a.alloc(?Source, np_old);
@memset(info.leaf_params, null);
@memset(info.ref_in, null);
@memset(info.ref_out, null);
var params: std.ArrayList(ir.Param) = .empty;
// Out / inout resources leave the parameter list (a pointer to a
// resource cannot be passed).
for (f.params, 0..) |prm, k| {
if (isRefResource(p.t, prm)) {
info.param_map[k] = null;
continue;
}
info.param_map[k] = @intCast(params.items.len);
try params.append(p.a, prm);
}
for (f.params, 0..) |prm, k| {
if (isRefResource(p.t, prm)) {
if (prm.dir == .inout) {
info.ref_in[k] = @intCast(params.items.len);
try params.append(p.a, .{ .name = prm.name, .ty = prm.ty, .by_ref = false, .sema_ty = prm.ty });
}
continue;
}
if (!holdsResources(p.t, prm.ty)) continue;
info.leaf_params[k] = @intCast(params.items.len);
var leaves: std.ArrayList(TypeId) = .empty;
try leafTypes(p.a, p.t, prm.ty, &leaves);
for (leaves.items, 0..) |lt, n| try params.append(p.a, .{ .name = try std.fmt.allocPrint(p.a, "{s}.{d}", .{ prm.name, n }), .ty = lt, .by_ref = false, .sema_ty = lt });
}
f.params = params.items;
}
fn add(f: *ir.Function, a: Allocator, inst: ir.Inst) Allocator.Error!Ref {
try f.insts.append(a, inst);
return @enumFromInt(f.insts.items.len - 1);
}
fn leafParam(p: *Pass, f: *ir.Function, r: Ref, old: ir.Inst, ty: TypeId, pi: u32, first: u32, out: *std.ArrayList(Ref), leaves: *std.AutoHashMapUnmanaged(Ref, []const Ref), pleaves: *std.AutoHashMapUnmanaged(Ref, []const Ref)) Error!void {
f.insts.items[r.index()].op = .{ .param = p.cur_map[pi].? };
try out.append(p.a, r);
var lts: std.ArrayList(TypeId) = .empty;
try leafTypes(p.a, p.t, ty, &lts);
const vals = try p.a.alloc(Ref, lts.items.len);
for (vals, lts.items, 0..) |*v, lt, n| {
v.* = try add(f, p.a, .{ .op = .{ .param = first + @as(u32, @intCast(n)) }, .ty = lt });
try out.append(p.a, v.*);
}
if (old.ptr != .none) {
// By reference (`this`, inout): locals of its own, initialized
// from the leaf parameters.
const ptrs = try p.a.alloc(Ref, vals.len);
for (ptrs, vals, lts.items) |*pp, v, lt| {
pp.* = try add(f, p.a, .{ .op = .local_var, .ty = lt, .ptr = .function });
try out.append(p.a, pp.*);
try out.append(p.a, try add(f, p.a, .{ .op = .{ .store = .{ .ptr = pp.*, .value = v } }, .ty = TypeTable.void_type }));
}
try pleaves.put(p.a, r, ptrs);
} else try leaves.put(p.a, r, vals);
}
fn function(p: *Pass, fi: u32) Error!void {
const info = &p.infos[fi];
if (info.done) return;
info.done = true;
const f = p.m.functions.items[fi];
// Callees first: their returns may be resources.
for (f.insts.items) |inst| if (inst.op == .call) try p.function(inst.op.call.func);
p.cur_map = info.param_map;
var leaves: std.AutoHashMapUnmanaged(Ref, []const Ref) = .empty;
var pleaves: std.AutoHashMapUnmanaged(Ref, []const Ref) = .empty;
var repl: std.AutoHashMapUnmanaged(Ref, Ref) = .empty;
const Map = struct {
r: *std.AutoHashMapUnmanaged(Ref, Ref),
pub fn map(c: @This(), x: Ref) Ref {
return c.r.get(x) orelse x;
}
};
const mp: Map = .{ .r = &repl };
var rets: std.ArrayList([]const Ref) = .empty;
var ref_locals: std.AutoHashMapUnmanaged(u32, Ref) = .empty;
var ref_init: std.AutoHashMapUnmanaged(Ref, void) = .empty;
const n_old = f.insts.items.len;
const ret_holds = holdsResources(p.t, f.ret) or isOpaque(p.t, f.ret);
for (f.blocks.items, 0..) |*blk, bi| {
var out: std.ArrayList(Ref) = .empty;
for (blk.insts.items) |r| {
const old = f.insts.items[r.index()];
const op = try opt.mapOp(p.a, old.op, mp);
f.insts.items[r.index()].op = op;
const ty = old.ty;
// Kept parameters move to their new index.
if (op == .param and op.param < info.param_map.len) if (info.param_map[op.param]) |np| if (info.leaf_params[op.param] == null) {
f.insts.items[r.index()].op = .{ .param = np };
};
switch (op) {
// An out / inout resource: a local of its own (an
// inout one starts as the value passed in).
.param => |pi| {
if (pi < info.leaf_params.len) if (info.leaf_params[pi]) |first| {
try p.leafParam(f, r, old, ty, pi, first, &out, &leaves, &pleaves);
continue;
};
if (!(pi < info.param_map.len and info.param_map[pi] == null)) {
try out.append(p.a, r);
continue;
}
f.insts.items[r.index()].op = .local_var;
f.insts.items[r.index()].ptr = .function;
try out.append(p.a, r);
try ref_locals.put(p.a, pi, r);
if (info.ref_in[pi]) |in| {
const v = try add(f, p.a, .{ .op = .{ .param = in }, .ty = ty });
try out.append(p.a, v);
const st = try add(f, p.a, .{ .op = .{ .store = .{ .ptr = r, .value = v } }, .ty = TypeTable.void_type });
try out.append(p.a, st);
try ref_init.put(p.a, st, {});
}
continue;
},
.local_var => if (holdsResources(p.t, ty)) {
try out.append(p.a, r);
var lts: std.ArrayList(TypeId) = .empty;
try leafTypes(p.a, p.t, ty, &lts);
const ptrs = try p.a.alloc(Ref, lts.items.len);
for (ptrs, lts.items) |*pp, lt| {
pp.* = try add(f, p.a, .{ .op = .local_var, .ty = lt, .ptr = .function });
try out.append(p.a, pp.*);
}
try pleaves.put(p.a, r, ptrs);
continue;
},
.access => |acc| if (pleaves.get(acc.base)) |base_leaves| {
var cur = f.insts.items[acc.base.index()].ty;
var start: u32 = 0;
for (acc.indices) |x| {
if (!holdsResources(p.t, cur)) break;
const xi = f.insts.items[x.index()];
if (xi.op != .constant) return p.fail("dynamically indexing an array of structs holding resources", .{});
const mb = member(p.t, cur, @intCast(xi.op.constant.int));
start += mb.start;
cur = mb.ty;
}
if (isOpaque(p.t, cur) and cur == ty) {
// A resource member: its own local.
try repl.put(p.a, r, base_leaves[start]);
continue;
}
try out.append(p.a, r);
if (holdsResources(p.t, ty)) try pleaves.put(p.a, r, base_leaves[start..][0..leafCount(p.t, ty)]);
continue;
},
.load => |ptr| if (pleaves.get(ptr)) |pl| {
try out.append(p.a, r);
const vals = try p.a.alloc(Ref, pl.len);
for (vals, pl) |*v, pp| {
v.* = try add(f, p.a, .{ .op = .{ .load = pp }, .ty = f.insts.items[pp.index()].ty });
try out.append(p.a, v.*);
}
try leaves.put(p.a, r, vals);
continue;
},
.store => |st| if (pleaves.get(st.ptr)) |pl| {
try out.append(p.a, r);
const vals = leaves.get(st.value) orelse return p.fail("storing this value holding resources", .{});
for (pl, vals) |pp, v| try out.append(p.a, try add(f, p.a, .{ .op = .{ .store = .{ .ptr = pp, .value = v } }, .ty = TypeTable.void_type }));
continue;
},
.construct => |parts| if (holdsResources(p.t, ty)) {
try out.append(p.a, r);
var vals: std.ArrayList(Ref) = .empty;
for (parts) |x| {
const xt = f.insts.items[x.index()].ty;
if (isOpaque(p.t, xt)) {
try vals.append(p.a, x);
} else if (holdsResources(p.t, xt)) {
try vals.appendSlice(p.a, leaves.get(x) orelse return p.fail("this value holding resources", .{}));
}
}
try leaves.put(p.a, r, vals.items);
continue;
},
.extract => |x| if (leaves.get(x.agg)) |vals| {
const mb = member(p.t, f.insts.items[x.agg.index()].ty, x.index);
if (isOpaque(p.t, ty)) {
try repl.put(p.a, r, vals[mb.start]);
continue;
}
try out.append(p.a, r);
if (holdsResources(p.t, ty)) try leaves.put(p.a, r, vals[mb.start..][0..leafCount(p.t, ty)]);
continue;
},
.insert => |x| if (holdsResources(p.t, ty)) {
try out.append(p.a, r);
const whole = leaves.get(x.agg) orelse return p.fail("this value holding resources", .{});
const vals = try p.a.dupe(Ref, whole);
const mb = member(p.t, ty, x.index);
const vt = f.insts.items[x.value.index()].ty;
if (isOpaque(p.t, vt)) {
vals[mb.start] = x.value;
} else if (holdsResources(p.t, vt)) {
const part = leaves.get(x.value) orelse return p.fail("this value holding resources", .{});
@memcpy(vals[mb.start..][0..part.len], part);
}
try leaves.put(p.a, r, vals);
continue;
},
.select => |x| if (holdsResources(p.t, ty) or isOpaque(p.t, ty)) {
_ = x;
return p.fail("selecting between values holding resources", .{});
},
.call => |c| {
const ci = &p.infos[c.func];
var args: std.ArrayList(Ref) = .empty;
for (c.args, 0..) |arg, k| if (k >= ci.param_map.len or ci.param_map[k] != null) try args.append(p.a, arg);
for (c.args, 0..) |arg, k| {
if (k < ci.ref_in.len) if (ci.ref_in[k] != null) {
// An inout resource's value goes in.
const v = try add(f, p.a, .{ .op = .{ .load = arg }, .ty = f.insts.items[arg.index()].ty });
try out.append(p.a, v);
try args.append(p.a, v);
continue;
};
if (k >= ci.leaf_params.len or ci.leaf_params[k] == null) continue;
if (leaves.get(arg)) |vals| {
try args.appendSlice(p.a, vals);
} else if (pleaves.get(arg)) |pl| {
for (pl) |pp| {
const v = try add(f, p.a, .{ .op = .{ .load = pp }, .ty = f.insts.items[pp.index()].ty });
try out.append(p.a, v);
try args.append(p.a, v);
}
} else return p.fail("passing this value holding resources to a function", .{});
}
f.insts.items[r.index()].op = .{ .call = .{ .func = c.func, .args = args.items } };
if (ci.ret_void) f.insts.items[r.index()].ty = TypeTable.void_type;
try out.append(p.a, r);
// Out / inout resources come back: the argument's
// storage gets the parameter or global they are.
for (c.args, 0..) |arg, k| {
if (k >= ci.ref_out.len) continue;
const src = ci.ref_out[k] orelse continue;
const at = f.insts.items[arg.index()].ty;
const v = switch (src) {
.param => |pi| args.items[pi],
.global => |g| blk: {
const gp = try add(f, p.a, .{ .op = .{ .global = g }, .ty = at, .ptr = .resource });
try out.append(p.a, gp);
const l = try add(f, p.a, .{ .op = .{ .load = gp }, .ty = at });
try out.append(p.a, l);
break :blk l;
},
};
try out.append(p.a, try add(f, p.a, .{ .op = .{ .store = .{ .ptr = arg, .value = v } }, .ty = TypeTable.void_type }));
}
// What the callee returns: its arguments or
// globals.
if (ci.ret) |srcs| {
const vals = try p.a.alloc(Ref, srcs.len);
var lts: std.ArrayList(TypeId) = .empty;
try leafTypes(p.a, p.t, ty, &lts);
for (vals, srcs, lts.items) |*v, src, lt| v.* = switch (src) {
.param => |pi| args.items[pi],
.global => |g| blk: {
const gp = try add(f, p.a, .{ .op = .{ .global = g }, .ty = lt, .ptr = .resource });
try out.append(p.a, gp);
const l = try add(f, p.a, .{ .op = .{ .load = gp }, .ty = lt });
try out.append(p.a, l);
break :blk l;
},
};
if (isOpaque(p.t, ty)) try repl.put(p.a, r, vals[0]) else try leaves.put(p.a, r, vals);
}
continue;
},
else => {},
}
try out.append(p.a, r);
}
blk.insts = out;
// The terminator's operand too.
switch (blk.term) {
.ret => |v| if (v != .none) {
const mv = mp.map(v);
blk.term = .{ .ret = mv };
if (ret_holds) {
if (isOpaque(p.t, f.ret)) {
try rets.append(p.a, try p.a.dupe(Ref, &.{mv}));
blk.term = .{ .ret = .none };
} else try rets.append(p.a, leaves.get(mv) orelse return p.fail("returning this value holding resources", .{}));
}
},
.cond_br => |cb| blk.term = .{ .cond_br = .{ .cond = mp.map(cb.cond), .then = cb.then, .@"else" = cb.@"else" } },
.@"switch" => |sw| blk.term = .{ .@"switch" = .{ .value = mp.map(sw.value), .default = sw.default, .cases = sw.cases } },
else => {},
}
_ = bi;
}
_ = n_old;
// What each out / inout resource holds when the function returns:
// every store into it (other than the incoming value) the same
// parameter or global.
var it = ref_locals.iterator();
while (it.next()) |kv| {
var src: ?Source = if (info.ref_in[kv.key_ptr.*]) |in| .{ .param = in } else null;
var seen = false;
for (f.insts.items, 0..) |inst, ii| {
if (inst.op != .store or inst.op.store.ptr != kv.value_ptr.*) continue;
if (ref_init.contains(@enumFromInt(ii))) continue;
const here = p.trace(f, inst.op.store.value) orelse return p.fail("passing out a resource that is not a parameter or global", .{});
if (seen and !std.meta.eql(src.?, here)) return p.fail("passing out different resources from one function", .{});
src = here;
seen = true;
}
info.ref_out[kv.key_ptr.*] = src;
}
if (ret_holds) {
var srcs: ?[]Source = null;
for (rets.items) |vals| {
const here = try p.a.alloc(Source, vals.len);
for (here, vals) |*s, v| s.* = p.trace(f, v) orelse return p.fail("returning a resource that is not a parameter or global", .{});
if (srcs) |prev| {
for (prev, here) |x, y| if (!std.meta.eql(x, y)) return p.fail("returning different resources from one function", .{});
} else srcs = here;
}
info.ret = srcs orelse return p.fail("a function returning resources with no return", .{});
if (isOpaque(p.t, f.ret)) {
info.ret_void = true;
f.ret = TypeTable.void_type;
}
}
}
/// The parameter or global a resource value comes from.
fn trace(p: *Pass, f: *const ir.Function, v0: Ref) ?Source {
var v = v0;
var steps: u32 = 0;
while (steps < 64) : (steps += 1) {
const inst = f.insts.items[v.index()];
switch (inst.op) {
.load => |x| v = x,
.param => |pi| return .{ .param = pi },
.global => |g| return .{ .global = g },
// A resource local: what is stored into it.
.local_var => v = for (f.insts.items) |i| {
if (i.op == .store and i.op.store.ptr == v) break i.op.store.value;
} else return null,
else => return null,
}
}
_ = p;
return null;
}
};
/// Splits every function's resource-holding aggregates (SPIR-V only).
pub fn run(a: Allocator, m: *ir.Module, diags: *diag.Diagnostics) Error!void {
var any = false;
for (m.functions.items) |f| {
for (f.params) |prm| if (holdsResources(m.types, prm.ty) or isRefResource(m.types, prm)) {
any = true;
};
if (holdsResources(m.types, f.ret) or isOpaque(m.types, f.ret)) any = true;
for (f.insts.items) |inst| if (holdsResources(m.types, inst.ty)) {
any = true;
};
}
if (!any) return;
var p: Pass = .{ .a = a, .m = m, .t = m.types, .diags = diags, .infos = try a.alloc(FuncInfo, m.functions.items.len) };
@memset(p.infos, .{});
for (0..m.functions.items.len) |fi| try p.signature(@intCast(fi));
for (0..m.functions.items.len) |fi| try p.function(@intCast(fi));
}

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);
}

156
src/job.zig Normal file
View File

@ -0,0 +1,156 @@
//! `--job=<job.json>`: compile every shader a job file lists in one
//! process, on several threads. Starting a process costs more than
//! compiling most shaders, so a build with many shaders is much faster
//! this way than with one zdxc run per shader.
//!
//! The job file:
//!
//! {
//! "threads": 8,
//! "args": ["-HV", "2021"],
//! "jobs": [
//! { "args": ["-T", "cs_6_0", "a.hlsl", "-Fo", "a.dxo"] },
//! { "args": ["-T", "ps_6_0", "-E", "PS", "b.hlsl", "-Fo", "b.dxo"] }
//! ]
//! }
//!
//! Each job is a dxc command line. The top-level `args`, then any other
//! options given next to `--job`, come before every job's own. `threads`
//! defaults to the number of CPUs. Paths are relative to the current
//! directory, as on the command line. Each job's output and diagnostics
//! are printed in job order; the exit code is 0 when every job succeeds,
//! else 1 if any job failed on its command line or I/O, else 5.
const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;
/// Compiles one job: `args` is a full command line (argv[0] first). It
/// writes to `stdout` / `stderr` and returns the exit code.
pub const CompileFn = *const fn (io: Io, arena: Allocator, args: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) u8;
const JobFile = struct {
threads: ?u32 = null,
args: []const []const u8 = &.{},
jobs: []const struct { args: []const []const u8 },
};
/// The index of `--job=<file>` in `argv`, if any.
pub fn find(argv: []const [:0]const u8) ?usize {
for (argv[1..], 1..) |a, i| if (std.mem.startsWith(u8, a, "--job=")) return i;
return null;
}
/// Runs the job file `argv[at]` names; the other arguments apply to every
/// job. Returns the process exit code.
pub fn run(io: Io, arena: Allocator, argv: []const [:0]const u8, at: usize, compile: CompileFn, stdout: *Io.Writer, stderr: *Io.Writer) !u8 {
const path = argv[at]["--job=".len..];
const text = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 30)) catch |e| {
try stderr.print("zdxc: error: cannot read job file '{s}': {s}\n", .{ path, @errorName(e) });
return 1;
};
var scanner = std.json.Scanner.initCompleteInput(arena, text);
var diag: std.json.Diagnostics = .{};
scanner.enableDiagnostics(&diag);
const file = std.json.parseFromTokenSourceLeaky(JobFile, arena, &scanner, .{}) catch |e| {
try stderr.print("zdxc: error: {s}:{d}:{d}: invalid job file: {s}\n", .{ path, diag.getLine(), diag.getColumn(), @errorName(e) });
return 1;
};
// argv[0], the file's common args, the command line's, then the job's.
var common: std.ArrayList([:0]const u8) = .empty;
try common.append(arena, argv[0]);
for (file.args) |a| try common.append(arena, try arena.dupeSentinel(u8, a, 0));
for (argv[1..], 1..) |a, i| if (i != at) try common.append(arena, a);
const jobs = try arena.alloc([]const [:0]const u8, file.jobs.len);
for (jobs, file.jobs) |*j, fj| {
const full = try arena.alloc([:0]const u8, common.items.len + fj.args.len);
@memcpy(full[0..common.items.len], common.items);
for (full[common.items.len..], fj.args) |*d, a| d.* = try arena.dupeSentinel(u8, a, 0);
j.* = full;
}
var b: Batch = .{ .io = io, .jobs = jobs, .results = try arena.alloc(Result, jobs.len), .compile = compile, .stdout = stdout, .stderr = stderr };
@memset(b.results, .{});
const cpus: u32 = @intCast(std.Thread.getCpuCount() catch 1);
const nthreads = @max(1, @min(file.threads orelse cpus, jobs.len));
// The calling thread is one of the workers.
const threads = try arena.alloc(std.Thread, nthreads - 1);
var spawned: usize = 0;
for (threads) |*t| {
t.* = std.Thread.spawn(.{}, Batch.work, .{&b}) catch break;
spawned += 1;
}
b.work();
for (threads[0..spawned]) |t| t.join();
var failed: usize = 0;
var code: u8 = 0;
for (b.results) |r| if (r.code != 0) {
failed += 1;
if (code != 1) code = r.code;
};
if (failed > 0) try stderr.print("zdxc: {d} of {d} jobs failed\n", .{ failed, jobs.len });
return code;
}
const Result = struct {
done: bool = false,
code: u8 = 0,
out: []u8 = &.{},
err: []u8 = &.{},
};
const Batch = struct {
io: Io,
jobs: []const []const [:0]const u8,
results: []Result,
compile: CompileFn,
stdout: *Io.Writer,
stderr: *Io.Writer,
next: std.atomic.Value(usize) = .init(0),
/// Guards `results` and the writers; jobs are printed in order.
mutex: Io.Mutex = .init,
printed: usize = 0,
fn work(b: *Batch) void {
const gpa = std.heap.smp_allocator;
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
while (true) {
const i = b.next.fetchAdd(1, .monotonic);
if (i >= b.jobs.len) return;
_ = arena.reset(.retain_capacity);
const a = arena.allocator();
var out: Io.Writer.Allocating = .init(a);
var err: Io.Writer.Allocating = .init(a);
const code = b.compile(b.io, a, b.jobs[i], &out.writer, &err.writer);
// The arena is reused for the next job: keep the output.
b.finish(i, .{
.done = true,
.code = code,
.out = gpa.dupe(u8, out.written()) catch &.{},
.err = gpa.dupe(u8, err.written()) catch &.{},
});
}
}
/// Records job `i` and prints every finished job not yet printed, in
/// order.
fn finish(b: *Batch, i: usize, r: Result) void {
b.mutex.lockUncancelable(b.io);
defer b.mutex.unlock(b.io);
b.results[i] = r;
while (b.printed < b.results.len and b.results[b.printed].done) : (b.printed += 1) {
const p = &b.results[b.printed];
b.stdout.writeAll(p.out) catch {};
b.stderr.writeAll(p.err) catch {};
std.heap.smp_allocator.free(p.out);
std.heap.smp_allocator.free(p.err);
p.out = &.{};
p.err = &.{};
}
b.stdout.flush() catch {};
b.stderr.flush() catch {};
}
};

View File

@ -1,71 +1,524 @@
const std = @import("std");
const Io = std.Io;
const zdxc = @import("zdxc");
const shader = zdxc.dxil.shader;
const container = zdxc.dxil.container;
const front = zdxc.front;
pub fn main(init: std.process.Init) !void {
// Prints to stderr, unbuffered, ignoring potential errors.
std.debug.print("All your {s} are belong to us.\n", .{"codebase"});
const options = zdxc.options;
const job = @import("job.zig");
// This is appropriate for anything that lives as long as the process.
const arena: std.mem.Allocator = init.arena.allocator();
const Options = struct {
profile: ?[]const u8 = null,
entry: []const u8 = "main",
output: ?[]const u8 = null,
input: ?[]const u8 = null,
spirv: bool = false,
/// -fspv-target-env (vulkan1.0 by default).
target_env: []const u8 = "vulkan1.0",
preprocess: bool = false,
pp_output: ?[]const u8 = null,
enable_16bit: bool = false,
row_major: bool = false,
col_major: 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,
include_dirs: std.ArrayList([]const u8) = .empty,
empty: bool = false,
check_hash: bool = false,
lex: bool = false,
warnings_as_errors: bool = false,
no_warnings: bool = false,
disabled_warnings: std.ArrayList([]const u8) = .empty,
diag_format: zdxc.diag.Format = .clang,
color: ?bool = null,
error_limit: u32 = 20,
parse: bool = false,
dump_ast: bool = false,
sema: bool = false,
dump_ir: bool = false,
/// -O0..-O3 / -Od (default -O3, as in dxc).
opt_level: enum { od, o0, o1, o2, o3 } = .o3,
/// Accepted options with no effect yet, reported once each.
ignored: std.ArrayList([]const u8) = .empty,
/// `--job=<file>` (handled before run; here only inside a job file).
job: ?[]const u8 = null,
};
// Accessing command line arguments:
const args = try init.minimal.args.toSlice(arena);
for (args) |arg| {
std.log.info("arg: {s}", .{arg});
const Cli = struct {
io: Io,
stderr: *Io.Writer,
fn fail(cli: Cli, comptime fmt: []const u8, args: anytype) error{Fatal} {
cli.stderr.print("zdxc: error: " ++ fmt ++ "\n", args) catch {};
cli.stderr.flush() catch {};
return error.Fatal;
}
};
// In order to do I/O operations need an `Io` instance.
pub fn main(init: std.process.Init) !u8 {
const arena = init.arena.allocator();
const io = init.io;
var stderr_buf: [1024]u8 = undefined;
// Streaming, not positional: `2>> log` must append.
var stderr_writer: Io.File.Writer = .initStreaming(.stderr(), io, &stderr_buf);
var stdout_buf: [4096]u8 = undefined;
var stdout_writer: Io.File.Writer = .initStreaming(.stdout(), io, &stdout_buf);
const cli: Cli = .{ .io = io, .stderr = &stderr_writer.interface };
defer stderr_writer.interface.flush() catch {};
// Stdout is for the actual output of your application, for example if you
// are implementing gzip, then only the compressed bytes should be sent to
// stdout, not any debugging messages.
var stdout_buffer: [1024]u8 = undefined;
var stdout_file_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buffer);
const stdout_writer = &stdout_file_writer.interface;
try zdxc.printAnotherMessage(stdout_writer);
try stdout_writer.flush(); // Don't forget to flush!
const args = try init.minimal.args.toSlice(arena);
if (job.find(args)) |at| {
const code = try job.run(io, arena, args, at, compileJob, &stdout_writer.interface, &stderr_writer.interface);
try stdout_writer.interface.flush();
return code;
}
// Exit codes follow dxc: 1 for command-line and I/O errors, 5 when the
// compilation reports errors.
run(cli, arena, args, &stdout_writer.interface) catch |err| switch (err) {
error.Fatal => return 1,
error.CompileFailed => return 5,
else => return err,
};
try stdout_writer.interface.flush();
return 0;
}
test "simple test" {
const gpa = std.testing.allocator;
var list: std.ArrayList(i32) = .empty;
defer list.deinit(gpa); // Try commenting this out and see if zig detects the memory leak!
try list.append(gpa, 42);
try std.testing.expectEqual(@as(i32, 42), list.pop());
}
test "fuzz example" {
try std.testing.fuzz({}, testOne, .{});
}
fn testOne(context: void, smith: *std.testing.Smith) !void {
_ = context;
// Try command `zig build test --fuzz -Doptimize=ReleaseFast` to see if it manages to fail this test case!
const gpa = std.testing.allocator;
var list: std.ArrayList(u8) = .empty;
defer list.deinit(gpa);
while (!smith.eos()) switch (smith.value(enum { add_data, dup_data })) {
.add_data => {
const slice = try list.addManyAsSlice(gpa, smith.value(u4));
smith.bytes(slice);
},
.dup_data => {
if (list.items.len == 0) continue;
if (list.items.len > std.math.maxInt(u32)) return error.SkipZigTest;
const len = smith.valueRangeAtMost(u32, 1, @min(32, list.items.len));
const off = smith.valueRangeAtMost(u32, 0, @intCast(list.items.len - len));
try list.appendSlice(gpa, list.items[off..][0..len]);
try std.testing.expectEqualSlices(
u8,
list.items[off..][0..len],
list.items[list.items.len - len ..],
);
/// One job of a `--job` file: `run`, with its exit code.
fn compileJob(io: Io, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) u8 {
const cli: Cli = .{ .io = io, .stderr = stderr };
run(cli, arena, args, stdout) catch |err| switch (err) {
error.Fatal => return 1,
error.CompileFailed => return 5,
else => {
stderr.print("zdxc: error: {s}\n", .{@errorName(err)}) catch {};
return 1;
},
};
return 0;
}
/// Parse a dxc-style command line. Returns null when the command is
/// complete (`-help`, `--version`).
fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, stdout: *Io.Writer) !?Options {
var failure: options.Failure = .{};
const plain = try arena.alloc([]const u8, argv.len -| 1);
for (plain, 0..) |*a, i| a.* = argv[i + 1];
const parsed = options.parse(arena, plain, &failure) catch |e| switch (e) {
error.UnknownArgument => return cli.fail("unknown argument: '{s}'", .{failure.arg}),
error.MissingArgument => return cli.fail("argument to '{s}' is missing", .{failure.arg}),
error.OutOfMemory => return error.OutOfMemory,
};
var opts: Options = .{};
for (parsed.args) |a| {
switch (a.which) {
.extra => |x| switch (x) {
.zdxc_empty => opts.empty = true,
.zdxc_check_hash => opts.check_hash = true,
.zdxc_lex => opts.lex = true,
.zdxc_parse => opts.parse = true,
.zdxc_ast => {
opts.parse = true;
opts.dump_ast = true;
},
.zdxc_sema => opts.sema = true,
.zdxc_ir => opts.dump_ir = true,
.job => opts.job = a.value(),
.fcolor_diagnostics => opts.color = true,
.fno_color_diagnostics => opts.color = false,
},
.dxc => |id| {
switch (options.support(id)) {
.implemented => {},
.ignored => {
try opts.ignored.append(arena, a.spelling);
continue;
},
.unsupported => |why| return cli.fail("'{s}' is not supported: {s}", .{ a.spelling, why }),
}
const v = a.value();
switch (id) {
.target_profile => opts.profile = v,
.entrypoint => opts.entry = v,
.Fo => opts.output = v,
.Fi => opts.pp_output = v,
.D => if (std.mem.indexOfScalar(u8, v, '=')) |eq| {
try opts.defines.append(arena, .{ .name = v[0..eq], .value = v[eq + 1 ..] });
} else try opts.defines.append(arena, .{ .name = v }),
.I => try opts.include_dirs.append(arena, v),
.hlsl_version => if (!std.mem.eql(u8, v, "2021")) {
return cli.fail("HLSL version {s} is not supported; zdxc implements HLSL 2021 only", .{v});
},
.P => opts.preprocess = true,
.spirv => opts.spirv = true,
.fspv_target_env_EQ => opts.target_env = v,
.enable_16bit_types => opts.enable_16bit = true,
.Zpr => opts.row_major = true,
.Zpc => opts.col_major = 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,
.no_warnings => opts.no_warnings = true,
.W_Joined => {
// -Wno-<group>, -Werror; enabling groups is a no-op.
if (std.mem.startsWith(u8, v, "no-")) {
try opts.disabled_warnings.append(arena, v[3..]);
} else if (std.mem.eql(u8, v, "error")) opts.warnings_as_errors = true;
},
.Wno_vk_ignored_features => try opts.disabled_warnings.append(arena, "vk-ignored-features"),
.Wno_vk_emulated_features => try opts.disabled_warnings.append(arena, "vk-emulated-features"),
.fdiagnostics_format_EQ => {
// dxc also accepts msvc-fallback.
const name = if (std.mem.eql(u8, v, "msvc-fallback")) "msvc" else v;
opts.diag_format = std.meta.stringToEnum(zdxc.diag.Format, name) orelse
return cli.fail("unknown diagnostics format '{s}' (expected clang, msvc or vi)", .{v});
},
.ferror_limit_EQ => opts.error_limit = std.fmt.parseInt(u32, v, 10) catch
return cli.fail("invalid -ferror-limit value '{s}'", .{v}),
.fdiagnostics_color => opts.color = true,
.fdiagnostics_color_EQ => opts.color = if (std.mem.eql(u8, v, "always"))
true
else if (std.mem.eql(u8, v, "never"))
false
else
null,
.help, ._help_question, ._help_hidden => {
try options.printHelp(stdout, id == ._help_hidden);
return null;
},
._version => {
try stdout.print("zdxc {s} (dxc-compatible command line, HLSL 2021)\n", .{zdxc.version});
return null;
},
.O0 => opts.opt_level = .o0,
.O1 => opts.opt_level = .o1,
.O2 => opts.opt_level = .o2,
.O3 => opts.opt_level = .o3,
.Od => opts.opt_level = .od,
else => {}, // implemented as a no-op (e.g. -Vd, -nologo)
}
},
}
}
if (opts.row_major and opts.col_major) return cli.fail("Cannot specify /Zpr and /Zpc together, use /? to get usage information", .{});
// Like dxc, the last input wins (dxc reads getLastArgValue(OPT_INPUT)).
if (parsed.inputs.len > 0) opts.input = parsed.inputs[parsed.inputs.len - 1];
if (opts.ignored.items.len > 0 and !opts.no_warnings) {
try cli.stderr.writeAll("zdxc: note: accepted for compatibility, no effect yet:");
for (opts.ignored.items) |sp| try cli.stderr.print(" {s}", .{sp});
try cli.stderr.writeByte('\n');
}
return opts;
}
fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *Io.Writer) !void {
const opts = try parseArgs(cli, arena, args, stdout) orelse return;
if (opts.job != null) return cli.fail("--job cannot be used inside a job file", .{});
if (opts.check_hash) {
const path = opts.input orelse return cli.fail("no input file", .{});
const bytes = try Io.Dir.cwd().readFileAlloc(cli.io, path, arena, .limited(1 << 30));
const view = container.parse(arena, bytes) catch return cli.fail("{s}: not a DXIL container", .{path});
if (!container.hashMatches(view.bytes)) return cli.fail("{s}: hash mismatch", .{path});
try stdout.print("{s}: hash ok ({d} parts)\n", .{ path, view.parts.items.len });
return;
}
if (opts.lex) {
const path = opts.input orelse return cli.fail("no input file", .{});
const text = try Io.Dir.cwd().readFileAlloc(cli.io, path, arena, .limited(256 << 20));
var lx = front.lexer.Lexer.init(text, 0);
while (true) {
const t = lx.next();
if (t.kind == .eof) break;
if (t.kind == .hash and t.flags.bol) {
const save = lx;
const d = lx.next();
if (d.isIdent("line")) {
lx.skipLine();
continue;
}
lx = save;
}
try stdout.print("{s}\n", .{t.text});
}
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|
shader.Profile.parse(p) orelse return cli.fail("unknown profile '{s}'", .{p})
else
null;
// 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", .{});
var disk: front.source.DiskFs = .{ .io = cli.io };
var sm = front.source.SourceManager.init(arena, disk.fileSystem());
var diags = zdxc.Diagnostics.init(arena);
diags.warnings_as_errors = opts.warnings_as_errors;
diags.suppress_warnings = opts.no_warnings;
diags.error_limit = opts.error_limit;
for (opts.disabled_warnings.items) |g| try diags.disableGroup(g);
var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{
.defines = opts.defines.items,
.include_dirs = opts.include_dirs.items,
.stage = if (profile) |p| @backingInt(p.kind) else 5,
.major = if (profile) |p| p.major else 6,
.minor = if (profile) |p| p.minor else 0,
.spirv = opts.spirv,
.spirv_minor = if (zdxc.spirv.emit.TargetEnv.parse(opts.target_env)) |t| t.minor else 0,
.enable_16bit = opts.enable_16bit,
});
var out: Io.Writer.Allocating = .init(arena);
var module: ?zdxc.ir.ir.Module = null;
const opened = try pp.enterMainFile(input);
if (opened) {
if (opts.preprocess) {
try front.pp_print.print(&pp, &out.writer);
} else {
var parser = try front.parser.Parser.fromPreprocessor(arena, &diags, &pp);
const tu = try parser.parseTranslationUnit();
if (opts.dump_ast) try front.ast_dump.dumpUnit(stdout, tu);
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,
.row_major = opts.row_major,
});
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.row_major = opts.row_major;
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);
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = color });
try cli.stderr.flush();
// An unreadable input is an I/O error, as in dxc.
if (!opened) return error.Fatal;
if (diags.hasErrors()) return error.CompileFailed;
if (opts.preprocess) {
if (opts.pp_output) |path| {
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = out.written() });
} 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) {
zdxc.ir.split_resources.run(arena, m, &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 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>", .{});
if (!opts.empty) return cli.fail("compiling HLSL is not implemented yet (use -P or -zdxc-empty)", .{});
if (prof.kind != .compute) return cli.fail("-zdxc-empty supports compute profiles only", .{});
const bytes = if (opts.spirv)
try zdxc.spirv.builder.buildEmptyCompute(arena, .{ .entry = opts.entry, .num_threads = .{ 1, 1, 1 } })
else
try shader.buildEmptyCompute(arena, .{ .entry = opts.entry, .profile = prof, .num_threads = .{ 1, 1, 1 } });
const out = opts.output orelse return cli.fail("missing -Fo <file>", .{});
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 }});
}

354
src/options.zig Normal file
View File

@ -0,0 +1,354 @@
//! dxc-compatible command-line parsing.
//!
//! The option table is generated from dxc's own definitions
//! (vendor/dxc/HLSLOptions.td) and matched with the same rules as LLVM's
//! OptTable, which dxc uses: `-`, `/` and `--` prefixes, longest spelling
//! first, flags must match exactly, joined / separate / joined-or-separate
//! values, and `/`-prefixed arguments that match nothing are input paths.
//! A few zdxc-only options (`-zdxc-*`, color control) are added on top under
//! names dxc does not use.
//!
//! Every dxc option has a support level: implemented, accepted with no
//! effect yet, or unsupported (with a reason), so that a dxc command line
//! either works or fails with a clear message.
const std = @import("std");
const Allocator = std.mem.Allocator;
const table = @import("options_table");
pub const Id = table.Id;
pub const Kind = table.Kind;
pub const Option = table.Option;
/// zdxc-only options. They use the same matching rules.
pub const Extra = enum {
zdxc_empty,
zdxc_check_hash,
zdxc_lex,
zdxc_parse,
zdxc_ast,
zdxc_sema,
zdxc_ir,
job,
fcolor_diagnostics,
fno_color_diagnostics,
};
const extra_options = [_]struct { id: Extra, spelling: []const u8, help: []const u8, kind: Kind = .flag, meta: []const u8 = "" }{
.{ .id = .zdxc_empty, .spelling = "zdxc-empty", .help = "Emit an empty shader for -T instead of compiling the input (development)" },
.{ .id = .zdxc_check_hash, .spelling = "zdxc-check-hash", .help = "Verify the container hash of the input (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_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 = .job, .spelling = "-job=", .kind = .joined, .meta = "<job.json>", .help = "Compile every shader a JSON job file lists, in one process, on all cores (see docs/batch.md)" },
.{ .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" },
};
pub const Arg = struct {
which: union(enum) { dxc: Id, extra: Extra },
/// The argument as written, for messages (`-T`, `/Fo`).
spelling: []const u8,
values: []const []const u8,
pub fn is(a: Arg, id: Id) bool {
return a.which == .dxc and a.which.dxc == id;
}
pub fn value(a: Arg) []const u8 {
return if (a.values.len > 0) a.values[0] else "";
}
};
pub const Parsed = struct {
args: []const Arg,
inputs: []const []const u8,
};
pub const ParseError = error{ UnknownArgument, MissingArgument } || Allocator.Error;
/// Details of the last ParseError, for the error message.
pub const Failure = struct { arg: []const u8 = "" };
/// Parse `argv` (without the program name).
pub fn parse(arena: Allocator, argv: []const []const u8, failure: *Failure) ParseError!Parsed {
var args: std.ArrayList(Arg) = .empty;
var inputs: std.ArrayList([]const u8) = .empty;
var i: usize = 0;
while (i < argv.len) {
const str = argv[i];
if (!isOptionLike(str)) {
try inputs.append(arena, str);
i += 1;
continue;
}
const r = try parseOne(arena, argv, &i, failure);
if (r) |a| {
try args.append(arena, a);
} else if (str[0] == '/') {
// Not an option: a path such as /Users/me/shader.hlsl.
try inputs.append(arena, str);
i += 1;
} else {
failure.arg = str;
return error.UnknownArgument;
}
}
return .{ .args = args.items, .inputs = inputs.items };
}
fn isOptionLike(s: []const u8) bool {
if (s.len < 2) return false; // "-" alone is an input (stdin)
return s[0] == '-' or s[0] == '/';
}
/// Candidate match: an option (dxc or extra) whose prefix + spelling
/// starts `str`.
const Candidate = struct {
which: @FieldType(Arg, "which"),
kind: Kind,
count: u8,
prefix_len: usize,
spelling_len: usize,
};
fn prefixFits(str: []const u8, pre: []const u8, spelling: []const u8) bool {
return std.mem.startsWith(u8, str, pre) and std.mem.startsWith(u8, str[pre.len..], spelling);
}
fn parseOne(arena: Allocator, argv: []const []const u8, index: *usize, failure: *Failure) ParseError!?Arg {
const str = argv[index.*];
var cands: [16]Candidate = undefined;
var n: usize = 0;
for (table.options) |o| {
const prefixes = [_]struct { bool, []const u8 }{ .{ o.dash_dash, "--" }, .{ o.dash, "-" }, .{ o.slash, "/" } };
for (prefixes) |pp| {
if (!pp[0] or !prefixFits(str, pp[1], o.spelling)) continue;
if (n < cands.len) {
cands[n] = .{ .which = .{ .dxc = o.alias orelse o.id }, .kind = o.kind, .count = o.count, .prefix_len = pp[1].len, .spelling_len = o.spelling.len };
n += 1;
}
break;
}
}
for (extra_options) |o| {
if (prefixFits(str, "-", o.spelling) and n < cands.len) {
cands[n] = .{ .which = .{ .extra = o.id }, .kind = o.kind, .count = 0, .prefix_len = 1, .spelling_len = o.spelling.len };
n += 1;
}
}
// Longest spelling first, as OptTable's sorted search does.
std.mem.sort(Candidate, cands[0..n], {}, struct {
fn gt(_: void, a: Candidate, b: Candidate) bool {
return a.spelling_len > b.spelling_len;
}
}.gt);
for (cands[0..n]) |c| {
const name_end = c.prefix_len + c.spelling_len;
const rest = str[name_end..];
const spelling = str[0..name_end];
switch (c.kind) {
.flag => {
if (rest.len != 0) continue;
index.* += 1;
return .{ .which = c.which, .spelling = spelling, .values = &.{} };
},
.joined => {
index.* += 1;
return .{ .which = c.which, .spelling = spelling, .values = try dupeOne(arena, rest) };
},
.comma_joined => {
index.* += 1;
var vals: std.ArrayList([]const u8) = .empty;
var it = std.mem.splitScalar(u8, rest, ',');
while (it.next()) |v| try vals.append(arena, v);
return .{ .which = c.which, .spelling = spelling, .values = vals.items };
},
.separate, .joined_or_separate => {
if (rest.len != 0) {
if (c.kind == .separate) continue;
index.* += 1;
return .{ .which = c.which, .spelling = spelling, .values = try dupeOne(arena, rest) };
}
if (index.* + 1 >= argv.len) {
failure.arg = spelling;
return error.MissingArgument;
}
index.* += 2;
return .{ .which = c.which, .spelling = spelling, .values = try dupeOne(arena, argv[index.* - 1]) };
},
.multi_arg => {
if (rest.len != 0) continue;
if (index.* + c.count >= argv.len) {
failure.arg = spelling;
return error.MissingArgument;
}
const vals = try arena.dupe([]const u8, argv[index.* + 1 ..][0..c.count]);
index.* += 1 + c.count;
return .{ .which = c.which, .spelling = spelling, .values = vals };
},
}
}
return null;
}
fn dupeOne(arena: Allocator, v: []const u8) Allocator.Error![]const []const u8 {
const vals = try arena.alloc([]const u8, 1);
vals[0] = v;
return vals;
}
// -------------------------------------------------------------------------
// Support levels
pub const Support = union(enum) {
implemented,
/// Accepted for compatibility; has no effect (yet).
ignored,
/// Rejected with this reason.
unsupported: []const u8,
};
const dropped_debug = "debug information and PDBs are not supported by zdxc";
const dropped_disasm = "disassembly is not part of zdxc; use dxc -dumpbin to inspect output";
const dropped_tooling = "this dxc tooling option is not part of zdxc";
const dropped_internal = "dxc-internal (LLVM pass / codegen debugging) options are not supported";
const not_yet = "not supported by zdxc yet";
/// The support level of each dxc option. Options not listed are
/// unsupported ("not supported by zdxc yet").
pub fn support(id: Id) Support {
return switch (id) {
// Core compilation.
.target_profile, .entrypoint, .Fo, .D, .I, .P, .Fi, .hlsl_version, .spirv, .enable_16bit_types, .fspv_target_env_EQ, .Zpr, .Zpc => .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.
._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,
// Information.
.help, ._help_question, ._help_hidden, ._version, .nologo => .implemented,
// Optimization levels: recorded; zdxc's optimizer is simpler.
.O0, .O1, .O2, .O3, .Od => .implemented,
// zdxc signs its own output and has no separate validation step.
.VD, .validator_version => .implemented,
// Accepted for build-script compatibility; no effect yet.
.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).
._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 },
.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, .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 },
};
}
/// The definition of `id` in the generated table.
pub fn info(id: Id) *const Option {
for (&table.options) |*o| if (o.id == id) return o;
unreachable;
}
pub fn extraHelp(id: Extra) []const u8 {
for (extra_options) |o| if (o.id == id) return o.help;
unreachable;
}
/// `-help`: dxc's option groups, listing implemented and accepted options
/// with dxc's help text, then zdxc's own options.
pub fn printHelp(w: *std.Io.Writer, show_hidden: bool) !void {
try w.writeAll(
\\OVERVIEW: zdxc - HLSL 2021 to DXIL / SPIR-V compiler (dxc-compatible command line)
\\
\\USAGE: zdxc [options] <input>
\\
\\Options are spelled as in dxc (-T, /T, -Tcs_6_0 ...). Options dxc accepts
\\but zdxc does not implement yet are accepted with a note; dropped dxc
\\features (debug info, disassembly, linking, ...) are reported as errors.
\\
);
for (table.groups) |g| {
var printed_title = false;
for (table.options) |o| {
if (!std.mem.eql(u8, o.group, g.name) or o.alias != null) continue;
if (o.hidden and !show_hidden) continue;
if (support(o.id) == .unsupported) continue;
if (!printed_title) {
try w.print("\n{s}:\n", .{if (g.help.len > 0) g.help else g.title});
printed_title = true;
}
try printOption(w, o.spelling, o.kind, o.meta, o.help, support(o.id) == .ignored);
}
}
try w.writeAll("\nzdxc options:\n");
for (extra_options) |o| try printOption(w, o.spelling, o.kind, o.meta, o.help, false);
}
fn printOption(w: *std.Io.Writer, spelling: []const u8, kind: Kind, meta: []const u8, help: []const u8, ignored: bool) !void {
var buf: [64]u8 = undefined;
const sep: []const u8 = if (kind == .separate or kind == .multi_arg) " " else "";
const left = std.fmt.bufPrint(&buf, "-{s}{s}{s}", .{ spelling, sep, meta }) catch spelling;
try w.print(" {s}", .{left});
if (left.len < 26) try w.splatByteAll(' ', 26 - left.len) else try w.writeAll("\n ");
// dxc help text can contain newlines and tabs; keep it on one line.
for (help) |c| try w.writeByte(if (c == '\n' or c == '\t') ' ' else c);
if (ignored) try w.writeAll(" [accepted, no effect yet]");
try w.writeByte('\n');
}
// -------------------------------------------------------------------------
// Tests
test "dxc spellings: dash, slash, joined and separate" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
var f: Failure = .{};
const p = try parse(a, &.{ "-T", "cs_6_0", "/Emain2", "-Foout.dxo", "/Fi", "x.i", "-DA=1", "-D", "B", "-Iinc", "-WX", "/O3", "-Wno-macro-redefined", "-fvk-b-shift", "1", "0", "/Users/me/s.hlsl", "-", "-zdxc-ast" }, &f);
try std.testing.expectEqual(@as(usize, 2), p.inputs.len);
try std.testing.expectEqualStrings("/Users/me/s.hlsl", p.inputs[0]);
try std.testing.expectEqualStrings("-", p.inputs[1]);
const expect = [_]struct { Id, []const u8 }{
.{ .target_profile, "cs_6_0" }, .{ .entrypoint, "main2" }, .{ .Fo, "out.dxo" }, .{ .Fi, "x.i" },
.{ .D, "A=1" }, .{ .D, "B" }, .{ .I, "inc" }, .{ ._SLASH_WX, "" },
.{ .O3, "" }, .{ .W_Joined, "no-macro-redefined" },
};
for (expect, 0..) |e, i| {
try std.testing.expect(p.args[i].is(e[0]));
try std.testing.expectEqualStrings(e[1], p.args[i].value());
}
try std.testing.expect(p.args[10].is(.fvk_b_shift));
try std.testing.expectEqual(@as(usize, 2), p.args[10].values.len);
try std.testing.expect(p.args[11].which == .extra and p.args[11].which.extra == .zdxc_ast);
}
test "unknown and missing arguments, flags need exact matches" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
var f: Failure = .{};
try std.testing.expectError(error.UnknownArgument, parse(a, &.{"-bogus"}, &f));
try std.testing.expectEqualStrings("-bogus", f.arg);
try std.testing.expectError(error.MissingArgument, parse(a, &.{"-T"}, &f));
try std.testing.expectEqualStrings("-T", f.arg);
// `-tcs_6_0`: options are case-sensitive, as in dxc.
try std.testing.expectError(error.UnknownArgument, parse(a, &.{"-tcs_6_0"}, &f));
// `-WXy` is not the -WX flag; it is the joined -W<warning> option.
const p = try parse(a, &.{"-WXy"}, &f);
try std.testing.expect(p.args[0].is(.W_Joined));
}
test "every option has a support level and a table entry" {
for (table.options) |o| {
_ = support(o.id);
try std.testing.expect(info(o.id).id == o.id);
}
}

View File

@ -1,18 +1,62 @@
//! By convention, root.zig is the root source file when making a package.
//! zdxc: an HLSL 2021 compiler targeting DXIL and SPIR-V.
pub const diag = @import("diag.zig");
pub const options = @import("options.zig");
pub const Diagnostics = diag.Diagnostics;
pub const front = struct {
pub const source = @import("front/source.zig");
pub const lexer = @import("front/lexer.zig");
pub const scan = @import("front/scan.zig");
pub const preproc = @import("front/preproc.zig");
pub const pp_print = @import("front/pp_print.zig");
pub const ast = @import("front/ast.zig");
pub const parser = @import("front/parser.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 bitstream = @import("dxil/bitstream.zig");
pub const container = @import("dxil/container.zig");
pub const hash = @import("dxil/hash.zig");
pub const module = @import("dxil/module.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 split_resources = @import("ir/split_resources.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 builder = @import("spirv/builder.zig");
pub const emit = @import("spirv/emit.zig");
};
pub const version = "0.0.0";
test {
const std = @import("std");
const Io = std.Io;
/// This is a documentation comment to explain the `printAnotherMessage` function below.
///
/// Accepting an `Io.Writer` instance is a handy way to write reusable code.
pub fn printAnotherMessage(writer: *Io.Writer) Io.Writer.Error!void {
try writer.print("Run `zig build test` to run the tests.\n", .{});
}
pub fn add(a: i32, b: i32) i32 {
return a + b;
}
test "basic add functionality" {
try std.testing.expect(add(3, 7) == 10);
std.testing.refAllDecls(front);
std.testing.refAllDecls(dxil);
std.testing.refAllDecls(ir);
_ = @import("sema/types.zig");
_ = @import("sema/sema.zig");
std.testing.refAllDecls(spirv);
_ = @import("diag.zig");
_ = @import("options.zig");
}

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

@ -0,0 +1,394 @@
//! 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]u16 = 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) ?u16 {
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: u16) 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;
// (Long vectors, SM 6.9: only arguments can make them.)
if (len < 1 or len > 1024) 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, @intCast(rows), @intCast(cols));
}
/// A layout dimension: a number, or a symbol bound from the argument.
fn dimValue(dim: []const u8, b: *Bindings, from_arg: ?u16) ?u16 {
if (std.fmt.parseInt(u16, 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;
}

4394
src/sema/sema.zig Normal file

File diff suppressed because it is too large Load Diff

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

@ -0,0 +1,756 @@
//! 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.
/// A template argument: a type or an integral value.
pub const TemplateArg = union(enum) { type: TypeId, value: i64 };
/// A scope enclosing a declaration (for mangled names): a namespace or a
/// struct.
pub const ScopeName = union(enum) { name: []const u8, strct: *const StructInfo };
pub const StructInfo = struct {
name: []const u8,
/// For mangled names: the name without template arguments, the
/// arguments of a template instance, the enclosing scopes (innermost
/// first) and whether it was declared `class`.
base_name: ?[]const u8 = null,
template_args: []const TemplateArg = &.{},
scopes: []const ScopeName = &.{},
is_class: bool = false,
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,
/// Enclosing scopes, innermost first (mangled names).
scopes: []const ScopeName = &.{},
};
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: u16 },
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).
/// `row_major`: a structured buffer's matrix elements are (as written,
/// by `#pragma pack_matrix` or -Zpr; dxc's SPIR-V honors it).
resource: struct { kind: ResourceKind, elem: TypeId, name: []const u8, flags: u32 = 0, flags2: u32 = 0, row_major: bool = false },
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,
/// `__builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(c, m, n, use,
/// scope)]]` (SM 6.10): an opaque matrix handle.
linalg: LinAlgMatrix,
};
pub const LinAlgMatrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u32 };
/// 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, @intFromBool(r.row_major)) << 48) | (@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) },
.linalg => |x| .{ .tag = 16, .a = (@as(u64, x.comp) << 32) | x.m, .b = (@as(u64, x.n) << 32) | (@as(u64, x.use) << 16) | x.scope },
.spirv => |x| .{ .tag = 15, .a = (@as(u64, x.opcode) << 32) | x.size, .b = std.hash.Wyhash.hash(x.alignment, std.mem.sliceAsBytes(x.operands)) },
};
}
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: u16) !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: u16,
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, @intCast(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",
.linalg => "__builtin_LinAlgMatrix",
};
}
};
/// `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);
}

375
src/spirv/builder.zig Normal file
View File

@ -0,0 +1,375 @@
//! SPIR-V module builder. Instructions go into per-section buffers that are
//! concatenated in the order required by the SPIR-V logical layout.
const std = @import("std");
const Allocator = std.mem.Allocator;
pub const Id = u32;
/// SPIR-V opcodes (unified1 core grammar numbering).
pub const Op = enum(u16) {
undef = 1,
source = 3,
name = 5,
member_name = 6,
extension = 10,
ext_inst_import = 11,
ext_inst = 12,
memory_model = 14,
entry_point = 15,
execution_mode = 16,
capability = 17,
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,
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_parameter = 55,
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,
branch = 249,
branch_conditional = 250,
@"switch" = 251,
kill = 252,
@"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 {
capabilities,
extensions,
ext_inst_imports,
memory_model,
entry_points,
execution_modes,
debug_names,
annotations,
types_globals,
functions,
};
pub const Builder = struct {
gpa: Allocator,
sections: std.EnumArray(Section, std.ArrayList(u32)) = .initFill(.empty),
next_id: Id = 1,
pub fn init(gpa: Allocator) Builder {
return .{ .gpa = gpa };
}
pub fn deinit(b: *Builder) void {
for (&b.sections.values) |*s| s.deinit(b.gpa);
}
pub fn newId(b: *Builder) Id {
defer b.next_id += 1;
return b.next_id;
}
/// Emit an instruction; `operands` are raw words.
pub fn emit(b: *Builder, section: Section, op: Op, operands: []const u32) !void {
const s = b.sections.getPtr(section);
const count: u32 = @intCast(operands.len + 1);
try s.append(b.gpa, (count << 16) | @backingInt(op));
try s.appendSlice(b.gpa, operands);
}
/// Emit an instruction with a literal string operand placed after `pre`
/// and followed by `post`.
pub fn emitWithString(b: *Builder, section: Section, op: Op, pre: []const u32, str: []const u8, post: []const u32) !void {
const str_words = str.len / 4 + 1;
const s = b.sections.getPtr(section);
const count: u32 = @intCast(1 + pre.len + str_words + post.len);
try s.append(b.gpa, (count << 16) | @backingInt(op));
try s.appendSlice(b.gpa, pre);
for (0..str_words) |wi| {
var word: [4]u8 = @splat(0);
for (0..4) |ci| {
const idx = wi * 4 + ci;
if (idx < str.len) word[ci] = str[idx];
}
try s.append(b.gpa, std.mem.readInt(u32, &word, .little));
}
try s.appendSlice(b.gpa, post);
}
/// Serialize as little-endian bytes.
pub fn finish(b: *Builder, version: u32) ![]u8 {
var total: usize = 5;
for (b.sections.values) |s| total += s.items.len;
const out = try b.gpa.alloc(u8, total * 4);
const header = [5]u32{ 0x07230203, version, generator_magic, b.next_id, 0 };
var off: usize = 0;
for (header) |word| {
std.mem.writeInt(u32, out[off..][0..4], word, .little);
off += 4;
}
for (b.sections.values) |s| {
for (s.items) |word| {
std.mem.writeInt(u32, out[off..][0..4], word, .little);
off += 4;
}
}
return out;
}
};
/// Unregistered generator ID (tool 0), version 0.
const generator_magic = 0;
pub const spv_1_0: u32 = 0x00010000;
pub const ComputeInfo = struct {
entry: []const u8 = "main",
num_threads: [3]u32,
};
pub fn buildEmptyCompute(gpa: Allocator, info: ComputeInfo) ![]u8 {
var b = Builder.init(gpa);
defer b.deinit();
const void_ty = b.newId();
const fn_ty = b.newId();
const main_fn = b.newId();
const entry_label = b.newId();
try b.emit(.capabilities, .capability, &.{1}); // Shader
try b.emit(.memory_model, .memory_model, &.{ 0, 1 }); // Logical GLSL450
try b.emitWithString(.entry_points, .entry_point, &.{ 5, main_fn }, info.entry, &.{}); // GLCompute
try b.emit(.execution_modes, .execution_mode, &.{ main_fn, 17, info.num_threads[0], info.num_threads[1], info.num_threads[2] }); // LocalSize
try b.emitWithString(.debug_names, .name, &.{main_fn}, info.entry, &.{});
try b.emit(.types_globals, .type_void, &.{void_ty});
try b.emit(.types_globals, .type_function, &.{ fn_ty, void_ty });
try b.emit(.functions, .function, &.{ void_ty, main_fn, 0, fn_ty });
try b.emit(.functions, .label, &.{entry_label});
try b.emit(.functions, .@"return", &.{});
try b.emit(.functions, .function_end, &.{});
return b.finish(spv_1_0);
}
test "string operands are NUL-terminated and padded" {
var b = Builder.init(std.testing.allocator);
defer b.deinit();
try b.emitWithString(.debug_names, .name, &.{7}, "main", &.{});
const words = b.sections.get(.debug_names).items;
try std.testing.expectEqual(@as(usize, 4), words.len); // opcode, id, "main", "\0\0\0\0"
try std.testing.expectEqual(@as(u32, 0), words[3]);
}

4780
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

233
tools/gen_intrinsics.zig Normal file
View File

@ -0,0 +1,233 @@
//! Build-time generator: reads dxc's intrinsic declarations
//! (vendor/dxc/gen_intrin_main.txt) and writes a Zig table that Sema uses
//! for intrinsic and builtin-method overload resolution.
//!
//! Usage: gen_intrinsics <gen_intrin_main.txt> <out.zig>
//!
//! Declaration syntax (see the header of gen_intrin_main.txt):
//! <type> [[attrs]] <name>(<qual> <type> <name>, ...) [: <op>];
//! grouped into `namespace X { ... } namespace` blocks.
const std = @import("std");
const Allocator = std.mem.Allocator;
const Spec = struct {
qual: []const u8 = "in",
match_layout: i32 = std.math.minInt(i32),
match_comp: i32 = std.math.minInt(i32),
special: []const u8 = "none",
type_n: u32 = 0,
base: []const u8 = "",
any_layout: bool = false,
dims: std.ArrayList([]const u8) = .empty,
name: []const u8 = "",
};
const Decl = struct {
ns: []const u8,
name: []const u8,
ret: Spec,
params: std.ArrayList(Spec) = .empty,
varargs: bool = false,
attrs: []const u8,
op: []const u8,
};
pub fn main(init: std.process.Init) !void {
const a = init.arena.allocator();
const io = init.io;
const args = try init.minimal.args.toSlice(a);
if (args.len != 3) return error.Usage;
const text = try std.Io.Dir.cwd().readFileAlloc(io, args[1], a, .limited(1 << 20));
var decls: std.ArrayList(Decl) = .empty;
var ns: []const u8 = "";
var lines = std.mem.splitScalar(u8, text, '\n');
var lineno: usize = 0;
while (lines.next()) |raw| {
lineno += 1;
const line = std.mem.trim(u8, raw, " \t\r");
if (line.len == 0 or std.mem.startsWith(u8, line, "//") or line[0] == '#') continue;
if (std.mem.startsWith(u8, line, "namespace ")) {
ns = std.mem.trim(u8, line["namespace ".len..], " {");
continue;
}
if (line[0] == '}') continue;
const d = parseDecl(a, ns, line) catch |e| {
std.debug.print("gen_intrinsics: line {d}: {s}: {s}\n", .{ lineno, @errorName(e), line });
return e;
};
try decls.append(a, d);
}
var out: std.Io.Writer.Allocating = .init(a);
try emit(&out.writer, decls.items);
try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = args[2], .data = out.written() });
}
fn parseDecl(a: Allocator, ns: []const u8, line_in: []const u8) !Decl {
var line = std.mem.trimEnd(u8, line_in, ";");
// Optional `: op` after the closing parenthesis.
var op: []const u8 = "";
const close = std.mem.lastIndexOfScalar(u8, line, ')') orelse return error.NoParen;
if (std.mem.indexOfScalarPos(u8, line, close, ':')) |colon| {
op = std.mem.trim(u8, line[colon + 1 ..], " ");
line = line[0..colon];
}
const open_attr = std.mem.indexOf(u8, line, "[[") orelse return error.NoAttrs;
const close_attr = std.mem.indexOfPos(u8, line, open_attr, "]]") orelse return error.NoAttrs;
const ret_text = std.mem.trim(u8, line[0..open_attr], " ");
const attrs = line[open_attr + 2 .. close_attr];
const rest = std.mem.trim(u8, line[close_attr + 2 ..], " ");
const lp = std.mem.indexOfScalar(u8, rest, '(') orelse return error.NoParen;
const rp = std.mem.lastIndexOfScalar(u8, rest, ')') orelse return error.NoParen;
var d: Decl = .{
.ns = ns,
.name = std.mem.trim(u8, rest[0..lp], " "),
.ret = try parseSpec(a, ret_text, false),
.attrs = attrs,
.op = op,
};
const params_text = std.mem.trim(u8, rest[lp + 1 .. rp], " ");
if (params_text.len > 0) {
var depth: u32 = 0;
var start: usize = 0;
for (params_text, 0..) |c, i| {
if (c == '<') depth += 1;
if (c == '>') depth -= 1;
if ((c == ',' and depth == 0) or i == params_text.len - 1) {
const end = if (c == ',' and depth == 0) i else i + 1;
const p = std.mem.trim(u8, params_text[start..end], " ");
start = i + 1;
if (std.mem.eql(u8, p, "...")) {
d.varargs = true;
continue;
}
try d.params.append(a, try parseSpec(a, p, true));
}
}
}
return d;
}
/// `[qual...] type [name]`, where type is `$classT`, `$funcT`, `$typeN`,
/// or `[$match<X, Y>] base[<dims>]`.
fn parseSpec(a: Allocator, text: []const u8, is_param: bool) !Spec {
var s: Spec = .{};
var t = text;
// Qualifiers.
while (true) {
t = std.mem.trimStart(u8, t, " ");
const quals = [_][]const u8{ "inout ", "in ", "out ", "ref ", "row_major ", "col_major " };
var matched = false;
for (quals) |q| {
if (std.mem.startsWith(u8, t, q)) {
const word = q[0 .. q.len - 1];
if (!std.mem.eql(u8, word, "row_major") and !std.mem.eql(u8, word, "col_major")) s.qual = word;
t = t[q.len..];
matched = true;
}
}
if (!matched) break;
}
if (std.mem.startsWith(u8, t, "$match<")) {
const end = std.mem.indexOfScalar(u8, t, '>') orelse return error.BadMatch;
var it = std.mem.splitScalar(u8, t["$match<".len..end], ',');
s.match_layout = try std.fmt.parseInt(i32, std.mem.trim(u8, it.next().?, " "), 10);
s.match_comp = try std.fmt.parseInt(i32, std.mem.trim(u8, it.next() orelse return error.BadMatch, " "), 10);
t = std.mem.trimStart(u8, t[end + 1 ..], " ");
}
if (std.mem.startsWith(u8, t, "$classT")) {
s.special = "class_t";
t = t["$classT".len..];
} else if (std.mem.startsWith(u8, t, "$funcT")) {
s.special = "func_t";
t = t["$funcT".len..];
} else if (std.mem.startsWith(u8, t, "$type")) {
var i: usize = "$type".len;
while (i < t.len and std.ascii.isDigit(t[i])) i += 1;
s.special = "type_n";
s.type_n = try std.fmt.parseInt(u32, t["$type".len..i], 10);
t = t[i..];
} else {
var i: usize = 0;
while (i < t.len and (std.ascii.isAlphanumeric(t[i]) or t[i] == '_')) i += 1;
s.base = t[0..i];
t = t[i..];
if (t.len > 0 and t[0] == '<') {
const end = std.mem.indexOfScalar(u8, t, '>') orelse return error.BadLayout;
const inner = std.mem.trim(u8, t[1..end], " ");
if (inner.len == 0) {
s.any_layout = true;
} else {
var it = std.mem.splitScalar(u8, inner, ',');
while (it.next()) |dim| try s.dims.append(a, std.mem.trim(u8, dim, " "));
}
t = t[end + 1 ..];
}
}
if (is_param) s.name = std.mem.trim(u8, t, " ");
return s;
}
fn emitSpec(w: *std.Io.Writer, s: Spec) !void {
try w.print(".{{ .qual = .{s}, .special = .{s}, .type_n = {d}, .base = \"{s}\", .any_layout = {}, .dims = &.{{", .{ if (std.mem.eql(u8, s.qual, "inout")) "inout" else if (std.mem.eql(u8, s.qual, "out")) "out" else if (std.mem.eql(u8, s.qual, "ref")) "ref" else "in", s.special, s.type_n, s.base, s.any_layout });
for (s.dims.items, 0..) |d, i| {
if (i > 0) try w.writeAll(", ");
try w.print("\"{s}\"", .{d});
}
try w.writeAll("}, .match_layout = ");
if (s.match_layout == std.math.minInt(i32)) try w.writeAll("null") else try w.print("{d}", .{s.match_layout});
try w.writeAll(", .match_comp = ");
if (s.match_comp == std.math.minInt(i32)) try w.writeAll("null") else try w.print("{d}", .{s.match_comp});
try w.print(", .name = \"{s}\" }}", .{s.name});
}
fn emit(w: *std.Io.Writer, decls: []const Decl) !void {
try w.writeAll(
\\//! Generated by tools/gen_intrinsics.zig from vendor/dxc/gen_intrin_main.txt.
\\//! Do not edit.
\\
\\pub const Qual = enum { in, out, inout, ref };
\\pub const Special = enum { none, class_t, func_t, type_n };
\\
\\pub const Spec = struct {
\\ qual: Qual,
\\ special: Special,
\\ type_n: u32,
\\ /// Component class: `float_like`, `numeric`, `uint`, `sampler`, ...
\\ base: []const u8,
\\ /// `<>`: any scalar / vector / matrix layout.
\\ any_layout: bool,
\\ /// Layout dimensions: none (scalar), `{"4"}`, `{"c"}`, `{"r", "c"}` ...
\\ dims: []const []const u8,
\\ match_layout: ?i32,
\\ match_comp: ?i32,
\\ name: []const u8,
\\};
\\
\\pub const Intrinsic = struct {
\\ namespace: []const u8,
\\ name: []const u8,
\\ ret: Spec,
\\ params: []const Spec,
\\ varargs: bool,
\\ attrs: []const u8,
\\ op: []const u8,
\\};
\\
\\pub const intrinsics = [_]Intrinsic{
\\
);
for (decls) |d| {
try w.print(" .{{ .namespace = \"{s}\", .name = \"{s}\", .ret = ", .{ d.ns, d.name });
try emitSpec(w, d.ret);
try w.writeAll(", .params = &.{");
for (d.params.items, 0..) |p, i| {
if (i > 0) try w.writeAll(", ");
try emitSpec(w, p);
}
try w.print("}}, .varargs = {}, .attrs = \"{s}\", .op = \"{s}\" }},\n", .{ d.varargs, d.attrs, d.op });
}
try w.writeAll("};\n");
}

270
tools/gen_options.zig Normal file
View File

@ -0,0 +1,270 @@
//! Build-time generator: reads dxc's option definitions
//! (vendor/dxc/HLSLOptions.td, LLVM OptParser tablegen syntax) and writes a
//! Zig table used by the dxc-compatible command-line parser.
//!
//! Usage: gen_options <HLSLOptions.td> <out.zig>
//!
//! Only the subset of tablegen used by that file is understood:
//! def NAME : Kind<[prefixes], "spelling"[, N]>, Attr<...>, ...;
//! with Group<>, Flags<[...]>, HelpText<"">, MetaVarName<"">, Alias<>.
const std = @import("std");
const Allocator = std.mem.Allocator;
const Def = struct {
name: []const u8,
kind: []const u8,
prefixes: std.ArrayList([]const u8) = .empty,
spelling: []const u8 = "",
count: u32 = 0,
group: []const u8 = "",
help: []const u8 = "",
meta: []const u8 = "",
alias: []const u8 = "",
hidden: bool = false,
};
pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator();
const io = init.io;
const args = try init.minimal.args.toSlice(arena);
if (args.len != 3) return error.Usage;
const text = try std.Io.Dir.cwd().readFileAlloc(io, args[1], arena, .limited(1 << 20));
var p: Parser = .{ .text = text, .a = arena };
var defs: std.ArrayList(Def) = .empty;
while (try p.nextDef()) |d| try defs.append(arena, d);
var out: std.Io.Writer.Allocating = .init(arena);
try emit(&out.writer, defs.items);
try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = args[2], .data = out.written() });
}
const Parser = struct {
text: []const u8,
a: Allocator,
pos: usize = 0,
fn skipSpace(p: *Parser) void {
while (p.pos < p.text.len) {
const c = p.text[p.pos];
if (std.ascii.isWhitespace(c)) {
p.pos += 1;
} else if (std.mem.startsWith(u8, p.text[p.pos..], "//")) {
while (p.pos < p.text.len and p.text[p.pos] != '\n') p.pos += 1;
} else if (std.mem.startsWith(u8, p.text[p.pos..], "/*")) {
const end = std.mem.indexOfPos(u8, p.text, p.pos + 2, "*/") orelse p.text.len - 2;
p.pos = end + 2;
} else break;
}
}
fn ident(p: *Parser) []const u8 {
p.skipSpace();
const start = p.pos;
while (p.pos < p.text.len and (std.ascii.isAlphanumeric(p.text[p.pos]) or p.text[p.pos] == '_')) p.pos += 1;
return p.text[start..p.pos];
}
fn expect(p: *Parser, c: u8) !void {
p.skipSpace();
if (p.pos >= p.text.len or p.text[p.pos] != c) {
std.debug.print("gen_options: expected '{c}' at offset {d}\n", .{ c, p.pos });
return error.Syntax;
}
p.pos += 1;
}
fn peekIs(p: *Parser, c: u8) bool {
p.skipSpace();
return p.pos < p.text.len and p.text[p.pos] == c;
}
/// A double-quoted string with `\` escapes, returned unescaped.
fn string(p: *Parser) ![]const u8 {
try p.expect('"');
var buf: std.ArrayList(u8) = .empty;
while (p.pos < p.text.len and p.text[p.pos] != '"') {
var c = p.text[p.pos];
if (c == '\\' and p.pos + 1 < p.text.len) {
p.pos += 1;
c = switch (p.text[p.pos]) {
'n' => '\n',
't' => '\t',
else => p.text[p.pos],
};
}
try buf.append(p.a, c);
p.pos += 1;
}
try p.expect('"');
return buf.items;
}
/// Skip a balanced `<...>` group we do not interpret.
fn skipAngles(p: *Parser) !void {
try p.expect('<');
var depth: u32 = 1;
while (p.pos < p.text.len and depth > 0) : (p.pos += 1) {
switch (p.text[p.pos]) {
'<' => depth += 1,
'>' => depth -= 1,
'"' => {
_ = try p.string();
p.pos -= 1;
},
else => {},
}
}
}
fn nextDef(p: *Parser) !?Def {
while (true) {
p.skipSpace();
if (p.pos >= p.text.len) return null;
const word = p.ident();
if (word.len == 0) {
p.pos += 1;
continue;
}
if (std.mem.eql(u8, word, "include")) {
_ = try p.string();
continue;
}
if (!std.mem.eql(u8, word, "def")) continue;
var d: Def = .{ .name = p.ident(), .kind = "" };
try p.expect(':');
d.kind = p.ident();
if (p.peekIs('<')) try p.kindArgs(&d);
while (p.peekIs(',')) {
p.pos += 1;
const attr = p.ident();
try p.attribute(&d, attr);
}
try p.expect(';');
return d;
}
}
fn kindArgs(p: *Parser, d: *Def) !void {
try p.expect('<');
if (std.mem.eql(u8, d.kind, "OptionGroup")) {
d.spelling = try p.string();
try p.expect('>');
return;
}
try p.expect('[');
while (!p.peekIs(']')) {
try d.prefixes.append(p.a, try p.string());
if (p.peekIs(',')) p.pos += 1;
}
try p.expect(']');
try p.expect(',');
d.spelling = try p.string();
if (p.peekIs(',')) {
p.pos += 1;
p.skipSpace();
const start = p.pos;
while (p.pos < p.text.len and std.ascii.isDigit(p.text[p.pos])) p.pos += 1;
d.count = try std.fmt.parseInt(u32, p.text[start..p.pos], 10);
}
try p.expect('>');
}
fn attribute(p: *Parser, d: *Def, attr: []const u8) !void {
if (std.mem.eql(u8, attr, "HelpText")) {
try p.expect('<');
d.help = try p.string();
try p.expect('>');
} else if (std.mem.eql(u8, attr, "MetaVarName")) {
try p.expect('<');
d.meta = try p.string();
try p.expect('>');
} else if (std.mem.eql(u8, attr, "Group")) {
try p.expect('<');
d.group = p.ident();
try p.expect('>');
} else if (std.mem.eql(u8, attr, "Alias")) {
try p.expect('<');
d.alias = p.ident();
try p.expect('>');
} else if (std.mem.eql(u8, attr, "Flags")) {
const start = p.pos;
try p.skipAngles();
d.hidden = std.mem.indexOf(u8, p.text[start..p.pos], "HelpHidden") != null;
} else {
try p.skipAngles();
}
}
};
fn kindTag(kind: []const u8) ?[]const u8 {
const map = [_][2][]const u8{
.{ "Flag", "flag" },
.{ "Joined", "joined" },
.{ "JoinedOrSeparate", "joined_or_separate" },
.{ "Separate", "separate" },
.{ "MultiArg", "multi_arg" },
.{ "CommaJoined", "comma_joined" },
};
for (map) |m| if (std.mem.eql(u8, m[0], kind)) return m[1];
return null;
}
fn emit(w: *std.Io.Writer, defs: []const Def) !void {
try w.writeAll(
\\//! Generated by tools/gen_options.zig from vendor/dxc/HLSLOptions.td.
\\//! Do not edit.
\\
\\pub const Kind = enum { flag, joined, joined_or_separate, separate, multi_arg, comma_joined };
\\
\\pub const Group = struct { name: []const u8, title: []const u8, help: []const u8 };
\\
\\pub const Option = struct {
\\ /// Name of the tablegen def (dxc's OPT_<id>).
\\ id: Id,
\\ kind: Kind,
\\ spelling: []const u8,
\\ dash: bool,
\\ slash: bool,
\\ dash_dash: bool,
\\ /// Number of following arguments for multi_arg options.
\\ count: u8,
\\ group: []const u8,
\\ help: []const u8,
\\ meta: []const u8,
\\ hidden: bool,
\\ alias: ?Id,
\\};
\\
\\pub const groups = [_]Group{
\\
);
for (defs) |d| {
if (!std.mem.eql(u8, d.kind, "OptionGroup")) continue;
try w.print(" .{{ .name = \"{s}\", .title = \"{f}\", .help = \"{f}\" }},\n", .{ d.name, std.zig.fmtString(d.spelling), std.zig.fmtString(d.help) });
}
try w.writeAll("};\n\npub const Id = enum {\n");
for (defs) |d| {
if (kindTag(d.kind) == null) continue;
try w.print(" {f},\n", .{std.zig.fmtId(d.name)});
}
try w.writeAll("};\n\npub const options = [_]Option{\n");
for (defs) |d| {
const tag = kindTag(d.kind) orelse continue;
var dash = false;
var slash = false;
var dash_dash = false;
for (d.prefixes.items) |pre| {
if (std.mem.eql(u8, pre, "-")) dash = true;
if (std.mem.eql(u8, pre, "/")) slash = true;
if (std.mem.eql(u8, pre, "--")) dash_dash = true;
}
try w.print(" .{{ .id = .{f}, .kind = .{s}, .spelling = \"{f}\", .dash = {}, .slash = {}, .dash_dash = {}, .count = {d}, .group = \"{s}\", .help = \"{f}\", .meta = \"{f}\", .hidden = {}, .alias = ", .{
std.zig.fmtId(d.name), tag, std.zig.fmtString(d.spelling), dash, slash, dash_dash, d.count, d.group, std.zig.fmtString(d.help), std.zig.fmtString(d.meta), d.hidden,
});
if (d.alias.len > 0) try w.print(".{f}", .{std.zig.fmtId(d.alias)}) else try w.writeAll("null");
try w.writeAll(" },\n");
}
try w.writeAll("};\n");
}

13
vendor/PROVENANCE.md vendored Normal file
View File

@ -0,0 +1,13 @@
# Vendored data
zdxc vendors **data files only** from the DXC tree (never C++ sources).
Each entry records the source path and the DXC commit it was copied from.
| File | Source in DXC | DXC commit | License |
|---|---|---|---|
| `dxc/gen_intrin_main.txt` | `utils/hct/gen_intrin_main.txt` | 55a61aa79 | University of Illinois/NCSA (DXC) |
| `dxc/HLSLOptions.td` | `include/dxc/Support/HLSLOptions.td` | d02056da2 | University of Illinois/NCSA (DXC) |
| `hlsl-headers/` (all files) | `tools/clang/lib/Headers/hlsl/` | ecb18fb18 | Apache-2.0 WITH LLVM-exception (`hlsl-headers/LICENSE.txt`) |
DXC is distributed under the University of Illinois/NCSA license (LICENSE.TXT
in the DXC tree); SPIRV-Headers files are under the Khronos MIT-style license.

616
vendor/dxc/HLSLOptions.td vendored Normal file
View File

@ -0,0 +1,616 @@
//===--- HLSLOptions.td - Options for HLSL --------------------------------===//
///////////////////////////////////////////////////////////////////////////////
// //
// HLSLOptions.td //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// This file defines the options accepted by HLSL. //
// //
///////////////////////////////////////////////////////////////////////////////
// Include the common option parsing interfaces. //
include "llvm/Option/OptParser.td"
//////////////////////////////////////////////////////////////////////////////
// Flags
// DriverOption - The option is a "driver" option, and should not be forwarded
// to other tools.
def DriverOption : OptionFlag;
// CoreOption - This is considered a "core" HLSL option.
def CoreOption : OptionFlag;
// ISenseOption - This option is only supported for IntelliSense.
def ISenseOption : OptionFlag;
// RewriteOption - This is considered a "rewriter" HLSL option.
def RewriteOption : OptionFlag;
//////////////////////////////////////////////////////////////////////////////
// Groups
// Meta-group for options which are only used for compilation,
// and not linking etc.
def CompileOnly_Group : OptionGroup<"<CompileOnly group>">;
def Action_Group : OptionGroup<"<action group>">;
def I_Group : OptionGroup<"<I group>">, Group<CompileOnly_Group>;
def M_Group : OptionGroup<"<M group>">, Group<CompileOnly_Group>;
def T_Group : OptionGroup<"<T group>">;
def O_Group : OptionGroup<"<O group>">, Group<CompileOnly_Group>;
def R_Group : OptionGroup<"<R group>">, Group<CompileOnly_Group>;
def R_value_Group : OptionGroup<"<R (with value) group>">, Group<R_Group>;
def W_Group : OptionGroup<"<W group>">, Group<CompileOnly_Group>, HelpText<"Warning Options">;
def W_value_Group : OptionGroup<"<W (with value) group>">, Group<W_Group>, HelpText<"Warning Options">;
def d_Group : OptionGroup<"<d group>">;
def f_Group : OptionGroup<"<f group>">, Group<CompileOnly_Group>;
def f_clang_Group : OptionGroup<"<f (clang-only) group>">, Group<CompileOnly_Group>;
def g_Group : OptionGroup<"<g group>">;
def g_flags_Group : OptionGroup<"<g flags group>">;
def i_Group : OptionGroup<"<i group>">, Group<CompileOnly_Group>;
def clang_i_Group : OptionGroup<"<clang i group>">, Group<i_Group>;
def m_Group : OptionGroup<"<m group>">, Group<CompileOnly_Group>;
def u_Group : OptionGroup<"<u group>">;
// Developer Driver Options
def internal_Group : OptionGroup<"<clang internal options>">;
def internal_driver_Group : OptionGroup<"<clang driver internal options>">,
Group<internal_Group>, HelpText<"DRIVER OPTIONS">;
def internal_debug_Group :
OptionGroup<"<clang debug/development internal options>">,
Group<internal_Group>, HelpText<"DEBUG/DEVELOPMENT OPTIONS">;
def hlslcomp_Group : OptionGroup<"HLSL Compilation">, HelpText<"Compilation Options">;
def hlsloptz_Group : OptionGroup<"HLSL Optimization">, HelpText<"Optimization Options">;
def hlslutil_Group : OptionGroup<"HLSL Utility">, HelpText<"Utility Options">;
def hlslcore_Group : OptionGroup<"HLSL Core">, HelpText<"Common Options">;
def hlslrewrite_Group : OptionGroup<"HLSL Rewriter">, HelpText<"Rewriter Options">;
def spirv_Group : OptionGroup<"SPIR-V CodeGen">, HelpText<"SPIR-V CodeGen Options">; // SPIRV Change
//////////////////////////////////////////////////////////////////////////////
// Options
// The internal option ID must be a valid C++ identifier and results in a
// hlsl::options::OPT_XX enum constant for XX.
//
// See tools/clang/include/clang/Driver/Options.td for more notes.
// These options are based on those used by clang.
// fxc-based options kept for compatiblity are below.
//
// The general approach is to include only things that are in use, in the
// same order as in Options.td.
def D : JoinedOrSeparate<["-", "/"], "D">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption]>,
HelpText<"Define macro">;
def H : Flag<["-"], "H">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"Show header includes and nesting depth">;
def I : JoinedOrSeparate<["-", "/"], "I">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption]>,
HelpText<"Add directory to include search path">;
def O0 : Flag<["-", "/"], "O0">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
HelpText<"Optimization Level 0">;
def O1 : Flag<["-", "/"], "O1">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
HelpText<"Optimization Level 1">;
def O2 : Flag<["-", "/"], "O2">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
HelpText<"Optimization Level 2">;
def O3 : Flag<["-", "/"], "O3">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
HelpText<"Optimization Level 3 (Default)">;
def Odump : Flag<["-", "/"], "Odump">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"Print the optimizer commands.">;
def Qunused_arguments : Flag<["-"], "Qunused-arguments">, Group<hlslcore_Group>, Flags<[CoreOption]>,
HelpText<"Don't emit warning for unused driver arguments">;
def Wall : Flag<["-"], "Wall">, Group<W_Group>, Flags<[CoreOption]>;
def Wdeprecated : Flag<["-"], "Wdeprecated">, Group<W_Group>, Flags<[CoreOption]>;
def W_Joined : Joined<["-"], "W">, Group<W_Group>, Flags<[CoreOption]>,
MetaVarName<"[no-]<warning>">, HelpText<"Enable/Disable the specified warning">;
def d_Flag : Flag<["-"], "d">, Group<d_Group>;
def d_Joined : Joined<["-"], "d">, Group<d_Group>;
//def fcolor_diagnostics : Flag<["-"], "fcolor-diagnostics">, Group<hlslcomp_Group>,
// Flags<[CoreOption, DriverOption]>, HelpText<"Use colors in diagnostics">;
def fdiagnostics_color : Flag<["-"], "fdiagnostics-color">, Group<hlslcomp_Group>,
Flags<[CoreOption, DriverOption]>;
def fdiagnostics_color_EQ : Joined<["-"], "fdiagnostics-color=">, Group<hlslcomp_Group>;
//def fansi_escape_codes : Flag<["-"], "fansi-escape-codes">, Group<f_Group>, // HLSL Change: disable ANSI escape codes
// Flags<[CoreOption, CC1Option]>, HelpText<"Use ANSI escape codes for diagnostics">;
def fconstexpr_depth_EQ : Joined<["-"], "fconstexpr-depth=">, Group<f_Group>;
def fconstexpr_steps_EQ : Joined<["-"], "fconstexpr-steps=">, Group<f_Group>;
def fconstexpr_backtrace_limit_EQ : Joined<["-"], "fconstexpr-backtrace-limit=">,
Group<f_Group>;
def fdiagnostics_format_EQ : Joined<["-"], "fdiagnostics-format=">, Group<hlslcomp_Group>,
Flags<[CoreOption]>,
HelpText<"Select diagnostic message format. Supported values: clang, msvc, mdvc-fallback, vi">;
def fdiagnostics_show_option : Flag<["-"], "fdiagnostics-show-option">, Group<hlslcomp_Group>,
Flags<[CoreOption]>, HelpText<"Print option name with mappable diagnostics">;
def fno_diagnostics_show_option : Flag<["-"], "fno-diagnostics-show-option">, Group<hlslcomp_Group>,
Flags<[CoreOption]>, HelpText<"Do not print option name with mappable diagnostics">;
def fdiagnostics_show_category_EQ : Joined<["-"], "fdiagnostics-show-category=">, Group<hlslcomp_Group>;
def ferror_limit_EQ : Joined<["-"], "ferror-limit=">, Group<hlslcomp_Group>, Flags<[CoreOption]>;
def import_binding_table : JoinedOrSeparate<["-", "/"], "import-binding-table">, Group<hlsloptz_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
HelpText<"Import a binding table to specify resource bindings.">;
def binding_table_define : Separate<["-", "/"], "binding-table-define">, Group<hlsloptz_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
HelpText<"Import a binding table from a define to specify resource bindings.">;
def funsafe_math_optimizations : Flag<["-"], "funsafe-math-optimizations">,
Group<hlsloptz_Group>;
def fno_unsafe_math_optimizations : Flag<["-"], "fno-unsafe-math-optimizations">,
Group<hlsloptz_Group>;
def fassociative_math : Flag<["-"], "fassociative-math">, Group<hlsloptz_Group>;
def fno_associative_math : Flag<["-"], "fno-associative-math">, Group<hlsloptz_Group>;
//def freciprocal_math :
// Flag<["-"], "freciprocal-math">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
// HelpText<"Allow division operations to be reassociated">;
def fno_reciprocal_math : Flag<["-"], "fno-reciprocal-math">, Group<hlsloptz_Group>;
def ffinite_math_only: Flag<["-"], "ffinite-math-only">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
HelpText<"Allow optimizations for floating-point arithmetic that assume that arguments and results are not NaNs or +-Infs.">;
def fno_finite_math_only: Flag<["-"], "fno-finite-math-only">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
HelpText<"Disallow optimizations for floating-point arithmetic that assume that arguments and results are not NaNs or +-Infs.">;
def fsigned_zeros : Flag<["-"], "fsigned-zeros">, Group<hlsloptz_Group>;
//def fno_signed_zeros :
// Flag<["-"], "fno-signed-zeros">, Group<hlsloptz_Group>, Flags<[CoreOption]>,
// HelpText<"Allow optimizations that ignore the sign of floating point zeros">;
def fhonor_nans : Flag<["-"], "fhonor-nans">, Group<hlsloptz_Group>;
def fno_honor_nans : Flag<["-"], "fno-honor-nans">, Group<hlsloptz_Group>;
def fhonor_infinities : Flag<["-"], "fhonor-infinities">, Group<hlsloptz_Group>;
def fno_honor_infinities : Flag<["-"], "fno-honor-infinities">, Group<hlsloptz_Group>;
//def ftrapping_math : Flag<["-"], "ftrapping-math">, Group<f_Group>;
//def fno_trapping_math : Flag<["-"], "fno-trapping-math">, Group<f_Group>;
//def ffp_contract : Joined<["-"], "ffp-contract=">, Group<hlsloptz_Group>,
// Flags<[CoreOption]>, HelpText<"Form fused FP ops (e.g. FMAs): fast (everywhere)"
// " | on (according to FP_CONTRACT pragma, default) | off (never fuse)">;
def flimited_precision_EQ : Joined<["-"], "flimited-precision=">, Group<hlsloptz_Group>;
def memdep_block_scan_limit : Separate<["-", "/"], "memdep-block-scan-limit">, Group<hlsloptz_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
HelpText<"The number of instructions to scan in a block in memory dependency analysis.">;
def opt_disable : Separate<["-", "/"], "opt-disable">, Group<hlsloptz_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
HelpText<"Disable this optimization.">;
def opt_enable : Separate<["-", "/"], "opt-enable">, Group<hlsloptz_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
HelpText<"Enable this optimization.">;
def opt_select : MultiArg<["-", "/"], "opt-select", 2>, MetaVarName<"<opt> <variant>">, Group<hlsloptz_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
HelpText<"Select this optimization variant.">;
def fdisable_loc_tracking : Flag<["-"], "fdisable-loc-tracking">,
Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"Disable source location tracking in IR. This will break diagnostic generation for late validation. (Ignored if /Zi is passed)">;
def fnew_inlining_behavior : Flag<["-"], "fnew-inlining-behavior">,
Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"Experimental option to use heuristics-driven late inlining and disable alwaysinline annotation for library shaders">;
def ftime_report : Flag<["-"], "ftime-report">, Group<hlslcomp_Group>, Flags<[CoreOption]>, HelpText<"Print time report">;
def ftime_trace : Flag<["-"], "ftime-trace">,
Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"Print hierchial time tracing to stdout">;
def ftime_trace_EQ : Joined<["-"], "ftime-trace=">,
Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"Print hierchial time tracing to file">;
def ftime_trace_granularity_EQ : Joined<["-"], "ftime-trace-granularity=">,
Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"Minimum time granularity (in microseconds) traced by time profiler">;
def verify : Joined<["-"], "verify">,
Group<hlslcomp_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Verify diagnostic output using comment directives">;
def verbose : Flag<["-"], "verbose">,
Group<hlslcomp_Group>,
Flags<[DriverOption]>,
HelpText<"Allow emission of verbose compiler information">;
// Short alias '-v' for the verbose option
def v : Flag<["-"], "v">,
Alias<verbose>,
Group<hlslcomp_Group>,
Flags<[DriverOption]>,
HelpText<"Alias for -verbose">;
/*
def fno_caret_diagnostics : Flag<["-"], "fno-caret-diagnostics">, Group<hlslcomp_Group>,
Flags<[CoreOption]>;
def fno_color_diagnostics : Flag<["-"], "fno-color-diagnostics">, Group<hlslcomp_Group>,
Flags<[CoreOption]>;
def fno_diagnostics_color : Flag<["-"], "fno-diagnostics-color">, Group<hlslcomp_Group>,
Flags<[CoreOption, DriverOption]>;
def fno_show_column : Flag<["-"], "fno-show-column">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"Do not include column number on diagnostics">;
def fno_spell_checking : Flag<["-"], "fno-spell-checking">, Group<hlslcomp_Group>,
Flags<[CoreOption]>, HelpText<"Disable spell-checking">;
def fshow_column : Flag<["-"], "fshow-column">, Group<hlslcomp_Group>, Flags<[CoreOption]>;
def fshow_source_location : Flag<["-"], "fshow-source-location">, Group<hlslcomp_Group>;
def fspell_checking : Flag<["-"], "fspell-checking">, Group<hlslcomp_Group>;
def fspell_checking_limit_EQ : Joined<["-"], "fspell-checking-limit=">, Group<hlslcomp_Group>;
def funroll_loops : Flag<["-"], "funroll-loops">, Group<hlsloptz_Group>,
HelpText<"Turn on loop unroller">, Flags<[CoreOption]>;
def fno_unroll_loops : Flag<["-"], "fno-unroll-loops">, Group<hlsloptz_Group>,
HelpText<"Turn off loop unroller">, Flags<[CoreOption]>;
def freroll_loops : Flag<["-"], "freroll-loops">, Group<hlsloptz_Group>,
HelpText<"Turn on loop reroller">, Flags<[CoreOption]>;
def fno_reroll_loops : Flag<["-"], "fno-reroll-loops">, Group<hlsloptz_Group>,
HelpText<"Turn off loop reroller">;
*/
def help : Flag<["-", "--", "/"], "help">, Flags<[DriverOption]>, Group<hlslcore_Group>,
HelpText<"Display available options">;
/*
def imacros : JoinedOrSeparate<["-", "--"], "imacros">, Group<clang_i_Group>, Flags<[CoreOption]>,
HelpText<"Include macros from file before parsing">, MetaVarName<"<file>">;
def include_ : JoinedOrSeparate<["-", "--"], "include">, Group<clang_i_Group>, EnumName<"include">,
MetaVarName<"<file>">, HelpText<"Include file before parsing">, Flags<[CoreOption]>;
def mllvm : Separate<["-"], "mllvm">, Flags<[CoreOption]>,
HelpText<"Additional arguments to forward to LLVM's option processing">;
def mms_bitfields : Flag<["-"], "mms-bitfields">, Group<m_Group>, Flags<[CoreOption]>,
HelpText<"Set the default structure layout to be compatible with the Microsoft compiler standard">;
def o : JoinedOrSeparate<["-"], "o">, Flags<[DriverOption, RenderAsInput, CoreOption]>,
HelpText<"Write output to <file>">, MetaVarName<"<file>">;
def time : Flag<["-"], "time">,
HelpText<"Time individual commands">;
// def U : JoinedOrSeparate<["-"], "U">, Group<CompileOnly_Group>, Flags<[CoreOption]>;
def w : Flag<["-"], "w">, HelpText<"Suppress all warnings">, Flags<[CoreOption]>;
def working_directory : JoinedOrSeparate<["-"], "working-directory">, Flags<[CoreOption]>,
MetaVarName<"<dir>">, HelpText<"Resolve file paths relative to the specified directory">;
def working_directory_EQ : Joined<["-"], "working-directory=">, Flags<[CoreOption]>,
MetaVarName<"<dir>">, Alias<working_directory>;
*/
// Double dash options, which are usually an alias for one of the previous
// options.
def _all_warnings : Flag<["--"], "all-warnings">, Flags<[CoreOption]>, Alias<Wall>;
def _help_hidden : Flag<["--"], "help-hidden">, Flags<[DriverOption]>;
def _help_question : Flag<["-", "/"], "?">, Flags<[DriverOption]>, Alias<help>;
def _version : Flag<["--"], "version">, Group<hlslcore_Group>, Flags<[DriverOption]>,
HelpText<"Display compiler version information">;
//////////////////////////////////////////////////////////////////////////////
// New HLSL-specific flags.
def ast_dump : Flag<["-", "/"], "ast-dump">, Flags<[CoreOption, DriverOption, HelpHidden]>,
HelpText<"Dumps the parsed Abstract Syntax Tree.">; // should not be core, but handy workaround until explicit API written
def ast_dump_implicit : Flag<["-", "/"], "ast-dump-implicit">, Flags<[CoreOption, DriverOption, HelpHidden]>,
HelpText<"Dumps the parsed Abstract Syntax Tree, including implicit top-level decls.">;
def dump_dependencies : Flag<["-", "/"], "M">, Flags<[CoreOption, DriverOption]>,
HelpText<"Dumps the list of the compilation target dependencies.">;
def write_dependencies : Flag<["-", "/"], "MD">, Flags<[CoreOption, DriverOption]>,
HelpText<"Write a file with .d extension that will contain the list of the compilation target dependencies.">;
def write_dependencies_to : JoinedOrSeparate<["-", "/"], "MF">, MetaVarName<"<file>">, Flags<[CoreOption, DriverOption]>,
HelpText<"Write the specified file that will contain the list of the compilation target dependencies.">;
def external_lib : Separate<["-", "/"], "external">, Group<hlslcore_Group>, Flags<[DriverOption, RewriteOption, HelpHidden]>,
HelpText<"External DLL name to load for compiler support">;
def external_fn : Separate<["-", "/"], "external-fn">, Group<hlslcore_Group>, Flags<[DriverOption, RewriteOption, HelpHidden]>,
HelpText<"External function name to load for compiler support">;
def fcgl : Flag<["-", "/"], "fcgl">, Group<hlslcore_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Generate high-level code only">;
def preserve_intermediate_values : Flag<["-", "/"], "preserve-intermediate-values">, Group<hlslcore_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Preserve intermediate values to help shader debugging">;
def flegacy_macro_expansion : Flag<["-", "/"], "flegacy-macro-expansion">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption, DriverOption]>,
HelpText<"Expand the operands before performing token-pasting operation (fxc behavior)">;
def flegacy_resource_reservation : Flag<["-", "/"], "flegacy-resource-reservation">, Group<hlslcomp_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Reserve unused explicit register assignments for compatibility with shader model 5.0 and below">;
def no_legacy_cbuf_layout : Flag<["-", "/"], "no-legacy-cbuf-layout">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Do not use legacy cbuffer load">;
def not_use_legacy_cbuf_load_ : Flag<["-", "/"], "not_use_legacy_cbuf_load">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Do not use legacy cbuffer load">;
def pack_prefix_stable : Flag<["-", "/"], "pack-prefix-stable">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"(default) Pack signatures preserving prefix-stable property - appended elements will not disturb placement of prior elements">;
def pack_prefix_stable_ : Flag<["-", "/"], "pack_prefix_stable">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"(default) Pack signatures preserving prefix-stable property - appended elements will not disturb placement of prior elements">;
def pack_optimized : Flag<["-", "/"], "pack-optimized">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"Optimize signature packing assuming identical signature provided for each connecting stage">;
def pack_optimized_ : Flag<["-", "/"], "pack_optimized">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Optimize signature packing assuming identical signature provided for each connecting stage">;
def hlsl_version : Separate<["-", "/"], "HV">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption]>,
HelpText<"HLSL version (2016, 2017, 2018, 2021). Default is 2021">;
def no_warnings : Flag<["-", "/"], "no-warnings">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption]>,
HelpText<"Suppress warnings">;
def rootsig_define : Separate<["-", "/"], "rootsig-define">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"Read root signature from a #define">;
def enable_16bit_types: Flag<["-", "/"], "enable-16bit-types">, Flags<[CoreOption, RewriteOption, DriverOption]>, Group<hlslcomp_Group>,
HelpText<"Enable 16bit types and disable min precision types. Available in HLSL 2018 and shader model 6.2">;
def ignore_line_directives : Flag<["-", "/"], "ignore-line-directives">, HelpText<"Ignore line directives">, Flags<[CoreOption]>, Group<hlslcomp_Group>;
def auto_binding_space : Separate<["-", "/"], "auto-binding-space">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"Set auto binding space - enables auto resource binding in libraries">;
def exports : Separate<["-", "/"], "exports">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"Specify exports when compiling a library: export1[[,export1_clone,...]=internal_name][;...]">;
def export_shaders_only : Flag<["-", "/"], "export-shaders-only">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"Only export shaders when compiling a library">;
def default_linkage : Separate<["-", "/"], "default-linkage">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"Set default linkage for non-shader functions when compiling or linking to a library target (internal, external)">;
def precise_output : Separate<["-", "/"], "precise-output">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Mark output semantic as precise">;
def encoding : Separate<["-", "/"], "encoding">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption, DriverOption]>,
HelpText<"Set default encoding for source inputs and text outputs (utf8|utf16(win)|utf32(*nix)|wide) default=utf8">;
def validator_version : Separate<["-", "/"], "validator-version">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Override validator version for module. Format: <major.minor> ; Default: DXIL.dll version or current internal version.">;
def print_before_all : Flag<["-", "/"], "print-before-all">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Print LLVM IR before each pass.">;
def print_before : Separate<["-", "/"], "print-before">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Print LLVM IR before a specific pass. May be specificied multiple times.">;
def print_after_all : Flag<["-", "/"], "print-after-all">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Print LLVM IR after each pass.">;
def print_after : Separate<["-", "/"], "print-after">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Print LLVM IR after a specific pass. May be specificied multiple times.">;
def ignore_opt_semdefs : Flag<["-", "/"], "ignore-opt-semdefs">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Ignore optional semantic defines which are not required to ensure program correctness.">;
def ignore_semdef : Separate<["-", "/"], "ignore-semdef">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Ignore the semantic define passed as a value to this flag.">;
def override_semdef : Separate<["-", "/"], "override-semdef">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Override the value of semantic define with the one passed with this flag.">;
def force_zero_store_lifetimes : Flag<["-", "/"], "force-zero-store-lifetimes">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Instead of generating lifetime intrinsics (SM >= 6.6) or storing undef (SM < 6.6), force fall back to storing zeroinitializer.">;
def enable_lifetime_markers : Flag<["-", "/"], "enable-lifetime-markers">, Group<hlslcomp_Group>, Flags<[CoreOption]>,
HelpText<"Enable generation of lifetime markers">;
def disable_lifetime_markers : Flag<["-", "/"], "disable-lifetime-markers">, Group<hlslcomp_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Disable generation of lifetime markers where they would be otherwise (6.6+)">;
def enable_payload_qualifiers : Flag<["-", "/"], "enable-payload-qualifiers">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption, DriverOption]>,
HelpText<"Enables support for payload access qualifiers for raytracing payloads in SM 6.6.">;
def disable_payload_qualifiers : Flag<["-", "/"], "disable-payload-qualifiers">, Group<hlslcomp_Group>, Flags<[CoreOption, RewriteOption, DriverOption]>,
HelpText<"Disables support for payload access qualifiers for raytracing payloads in SM 6.7.">;
def disable_exception_handling : Flag<["-", "/"], "disable-exception-handling">, Group<hlslcomp_Group>, Flags<[DriverOption, HelpHidden]>,
HelpText<"Disable dxc handling of exceptions">;
// Used with API only
def skip_serialization : Flag<["-", "/"], "skip-serialization">, Group<hlslcore_Group>, Flags<[CoreOption, HelpHidden]>,
HelpText<"Return a module interface instead of serialized output">;
def metal : Flag<["-"], "metal">,
Group<spirv_Group>,
Flags<[CoreOption, DriverOption]>,
HelpText<"Generate Metal code">;
// SPIRV Change Starts
def spirv : Flag<["-"], "spirv">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Generate SPIR-V code">;
def fvk_stage_io_order_EQ : Joined<["-"], "fvk-stage-io-order=">, Group<spirv_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
HelpText<"Specify Vulkan stage I/O location assignment order">;
def fvk_b_shift : MultiArg<["-"], "fvk-b-shift", 2>, MetaVarName<"<shift> <space>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Specify Vulkan binding number shift for b-type register">;
def fvk_t_shift : MultiArg<["-"], "fvk-t-shift", 2>, MetaVarName<"<shift> <space>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Specify Vulkan binding number shift for t-type register">;
def fvk_s_shift : MultiArg<["-"], "fvk-s-shift", 2>, MetaVarName<"<shift> <space>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Specify Vulkan binding number shift for s-type register">;
def fvk_u_shift : MultiArg<["-"], "fvk-u-shift", 2>, MetaVarName<"<shift> <space>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Specify Vulkan binding number shift for u-type register">;
def fvk_bind_globals : MultiArg<["-"], "fvk-bind-globals", 2>, MetaVarName<"<binding> <set>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Specify Vulkan binding number and set number for the $Globals cbuffer">;
def fvk_bind_register : MultiArg<["-"], "fvk-bind-register", 4>, MetaVarName<"<type-number> <space> <binding> <set>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Specify Vulkan descriptor set and binding for a specific register">;
def vkbr : MultiArg<["-"], "vkbr", 4>, Flags<[CoreOption, DriverOption]>, Alias<fvk_bind_register>;
def fvk_invert_y: Flag<["-"], "fvk-invert-y">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Negate SV_Position.y before writing to stage output in VS/DS/GS/MS/Lib to accommodate Vulkan's coordinate system">;
def fvk_use_dx_position_w: Flag<["-"], "fvk-use-dx-position-w">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Reciprocate SV_Position.w after reading from stage input in PS to accommodate the difference between Vulkan and DirectX">;
def fvk_support_nonzero_base_instance: Flag<["-"], "fvk-support-nonzero-base-instance">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Follow Vulkan spec to use gl_BaseInstance as the first vertex instance, which makes SV_InstanceID = gl_InstanceIndex - gl_BaseInstance (without this option, SV_InstanceID = gl_InstanceIndex)">;
def fvk_support_nonzero_base_vertex: Flag<["-"], "fvk-support-nonzero-base-vertex">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Follow Vulkan spec to use gl_BaseVertex as the first vertex, which makes SV_VertexID = gl_VertexIndex - gl_BaseVertex (without this option, SV_VertexID = gl_VertexIndex)">;
def fvk_use_gl_layout: Flag<["-"], "fvk-use-gl-layout">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Use strict OpenGL std140/std430 memory layout for Vulkan resources">;
def fvk_use_dx_layout: Flag<["-"], "fvk-use-dx-layout">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Use DirectX memory layout for Vulkan resources">;
def fvk_use_scalar_layout: Flag<["-"], "fvk-use-scalar-layout">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Use scalar memory layout for Vulkan resources">;
def fspv_use_legacy_buffer_matrix_order: Flag<["-"], "fspv-use-legacy-buffer-matrix-order">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Assume the legacy matrix order (row major) when accessing raw buffers (e.g., ByteAdddressBuffer)">;
def fspv_reflect: Flag<["-"], "fspv-reflect">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Emit additional SPIR-V instructions to aid reflection">;
def fspv_debug_EQ : Joined<["-"], "fspv-debug=">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Specify whitelist of debug info category (file -> source -> line, tool, vulkan-with-source)">;
def fspv_extension_EQ : Joined<["-"], "fspv-extension=">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Specify SPIR-V extension permitted to use">;
def fspv_target_env_EQ : Joined<["-"], "fspv-target-env=">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Specify the target environment: vulkan1.0 (default), vulkan1.1, vulkan1.1spirv1.4, vulkan1.2, vulkan1.3, or universal1.5">;
def fspv_flatten_resource_arrays: Flag<["-"], "fspv-flatten-resource-arrays">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Flatten arrays of resources so each array element takes one binding number">;
def fspv_reduce_load_size: Flag<["-"], "fspv-reduce-load-size">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Replaces loads of composite objects to reduce memory pressure for the loads">;
def fspv_fix_func_call_arguments: Flag<["-"], "fspv-fix-func-call-arguments">, Group<spirv_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
HelpText<"Fix function call arguments which are not memory objects">;
def fspv_entrypoint_name_EQ : Joined<["-"], "fspv-entrypoint-name=">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Specify the SPIR-V entry point name. Defaults to the HLSL entry point name.">;
def fspv_enable_maximal_reconvergence: Flag<["-"], "fspv-enable-maximal-reconvergence">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Enables the MaximallyReconvergesKHR execution mode for this module.">;
def fspv_use_vulkan_memory_model: Flag<["-"], "fspv-use-vulkan-memory-model">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Generates SPIR-V modules that use the Vulkan memory model instead of GLSL450.">;
def fspv_use_unknown_image_format
: Flag<["-"], "fspv-use-unknown-image-format">,
Group<spirv_Group>,
Flags<[CoreOption, DriverOption]>,
HelpText<"For storage images and texel buffers, sets the default format to 'Unknown' when not specified via the `vk::image_format` attribute. If this option is not used, the format is inferred from the resource's data type.">;
def fvk_auto_shift_bindings: Flag<["-"], "fvk-auto-shift-bindings">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Apply fvk-*-shift to resources without an explicit register assignment.">;
def Wno_vk_ignored_features : Joined<["-"], "Wno-vk-ignored-features">, Group<spirv_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
HelpText<"Do not emit warnings for ignored features resulting from no Vulkan support">;
def Wno_vk_emulated_features : Joined<["-"], "Wno-vk-emulated-features">, Group<spirv_Group>, Flags<[CoreOption, DriverOption, HelpHidden]>,
HelpText<"Do not emit warnings for emulated features resulting from no direct mapping">;
def fspv_print_all: Flag<["-"], "fspv-print-all">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Print the SPIR-V module before each pass and after the last one. Useful for debugging SPIR-V legalization and optimization passes.">;
def fspv_use_emulated_heap
: Flag<["-"], "fspv-use-emulated-heap">,
Group<spirv_Group>,
Flags<[CoreOption, DriverOption]>,
HelpText<
"Use emulated descriptor heap using descriptor indexing (default).">;
def fspv_use_descriptor_heap
: Flag<["-"], "fspv-use-descriptor-heap">,
Group<spirv_Group>,
Flags<[CoreOption, DriverOption]>,
HelpText<"Use SPV_EXT_descriptor_heap for HLSL descriptor heaps.">;
def Oconfig : CommaJoined<["-"], "Oconfig=">, Group<spirv_Group>, Flags<[CoreOption]>,
HelpText<"Specify a comma-separated list of SPIRV-Tools passes to customize optimization configuration (see http://khr.io/hlsl2spirv#optimization)">;
def fspv_preserve_bindings : Flag<["-"], "fspv-preserve-bindings">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Preserves all bindings declared within the module, even when those bindings are unused">;
def fspv_preserve_interface : Flag<["-"], "fspv-preserve-interface">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Preserves all interface variables in the entry point, even when those variables are unused">;
def fspv_max_id : MultiArg<["-"], "fspv-max-id", 1>, MetaVarName<"<shift> <space>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Set the maximum value for an id in the SPIR-V binary. Default is 0x3FFFFF, which is the largest value all drivers must support.">;
def fvk_bind_resource_heap : MultiArg<["-"], "fvk-bind-resource-heap", 2>, MetaVarName<"<binding> <set>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Specify Vulkan binding number and set number for the resource heap.">;
def fvk_bind_sampler_heap : MultiArg<["-"], "fvk-bind-sampler-heap", 2>, MetaVarName<"<binding> <set>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Specify Vulkan binding number and set number for the sampler heap.">;
def fvk_bind_counter_heap : MultiArg<["-"], "fvk-bind-counter-heap", 2>, MetaVarName<"<binding> <set>">, Group<spirv_Group>, Flags<[CoreOption, DriverOption]>,
HelpText<"Specify Vulkan binding number and set number for the counter heap.">;
// SPIRV Change Ends
//////////////////////////////////////////////////////////////////////////////
// fxc-based flags that don't match those previously defined.
def target_profile : JoinedOrSeparate<["-", "/"], "T">, Flags<[CoreOption]>, Group<hlslcomp_Group>, MetaVarName<"<profile>">,
/* <py::lines('VALRULE-TEXT')>hctdb_instrhelp.get_target_profiles()</py>*/
// VALRULE-TEXT:BEGIN
HelpText<"Set target profile. \n\t<profile>: ps_6_0, ps_6_1, ps_6_2, ps_6_3, ps_6_4, ps_6_5, ps_6_6, ps_6_7, ps_6_8, ps_6_9, ps_6_10, ps_6_11, \n\t\t vs_6_0, vs_6_1, vs_6_2, vs_6_3, vs_6_4, vs_6_5, vs_6_6, vs_6_7, vs_6_8, vs_6_9, vs_6_10, vs_6_11, \n\t\t gs_6_0, gs_6_1, gs_6_2, gs_6_3, gs_6_4, gs_6_5, gs_6_6, gs_6_7, gs_6_8, gs_6_9, gs_6_10, gs_6_11, \n\t\t hs_6_0, hs_6_1, hs_6_2, hs_6_3, hs_6_4, hs_6_5, hs_6_6, hs_6_7, hs_6_8, hs_6_9, hs_6_10, hs_6_11, \n\t\t ds_6_0, ds_6_1, ds_6_2, ds_6_3, ds_6_4, ds_6_5, ds_6_6, ds_6_7, ds_6_8, ds_6_9, ds_6_10, ds_6_11, \n\t\t cs_6_0, cs_6_1, cs_6_2, cs_6_3, cs_6_4, cs_6_5, cs_6_6, cs_6_7, cs_6_8, cs_6_9, cs_6_10, cs_6_11, \n\t\t lib_6_1, lib_6_2, lib_6_3, lib_6_4, lib_6_5, lib_6_6, lib_6_7, lib_6_8, lib_6_9, lib_6_10, lib_6_11, \n\t\t ms_6_5, ms_6_6, ms_6_7, ms_6_8, ms_6_9, ms_6_10, ms_6_11, \n\t\t as_6_5, as_6_6, as_6_7, as_6_8, as_6_9, as_6_10, as_6_11, \n\t\t ">;
// VALRULE-TEXT:END
def entrypoint : JoinedOrSeparate<["-", "/"], "E">, Flags<[CoreOption, RewriteOption]>, Group<hlslcomp_Group>,
HelpText<"Entry point name">;
// /I <include> - already defined above
def _vi : Flag<["-", "/"], "Vi">, Alias<H>, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"Display details about the include process.">;
def Od : Flag<["-", "/"], "Od">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"Disable optimizations">;
def _SLASH_WX : Flag<["-", "/"], "WX">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"Treat warnings as errors">;
def VD : Flag<["-", "/"], "Vd">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"Disable validation">;
def _SLASH_Zi : Flag<["-", "/"], "Zi">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"Enable debug information. Cannot be used together with -Zs">;
def Zs : Flag<["-", "/"], "Zs">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"Generate small PDB with just sources and compile options. Cannot be used together with -Zi">;
def recompile : Flag<["-", "/"], "recompile">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"recompile from DXIL container with Debug Info or Debug Info bitcode file">;
def Zpr : Flag<["-", "/"], "Zpr">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"Pack matrices in row-major order">;
def Zpc : Flag<["-", "/"], "Zpc">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"Pack matrices in column-major order">;
def Zss : Flag<["-", "/"], "Zss">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"Compute Shader Hash considering source information">;
def Zsb : Flag<["-", "/"], "Zsb">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"Compute Shader Hash considering only output binary">;
// deprecated /Gpp def Gpp : Flag<["-", "/"], "Gpp">, HelpText<"Force partial precision">;
def Gfa : Flag<["-", "/"], "Gfa">, HelpText<"Avoid flow control constructs">, Flags<[CoreOption]>, Group<hlslcomp_Group>;
def Gfp : Flag<["-", "/"], "Gfp">, HelpText<"Prefer flow control constructs">, Flags<[CoreOption]>, Group<hlslcomp_Group>;
// /Gdp - disable effect performance mode - unsupported
def Gec : Flag<["-", "/"], "Gec">, HelpText<"Enable backward compatibility mode">, Flags<[CoreOption]>, Group<hlslcomp_Group>;
def Ges : Flag<["-", "/"], "Ges">, HelpText<"Enable strict mode">, Flags<[CoreOption]>, Group<hlslcomp_Group>;
def Gis : Flag<["-", "/"], "Gis">, HelpText<"Force IEEE strictness">, Flags<[CoreOption]>, Group<hlslcomp_Group>;
def denorm : JoinedOrSeparate<["-", "/"], "denorm">, HelpText<"select denormal value options (any, preserve, ftz). any is the default.">, Flags<[CoreOption]>, Group<hlslcomp_Group>;
def Fo : JoinedOrSeparate<["-", "/"], "Fo">, MetaVarName<"<file>">, HelpText<"Output object file">, Flags<[CoreOption, RewriteOption, DriverOption]>, Group<hlslcomp_Group>;
// def Fl : JoinedOrSeparate<["-", "/"], "Fl">, MetaVarName<"<file>">, HelpText<"Output a library">;
def Fc : JoinedOrSeparate<["-", "/"], "Fc">, MetaVarName<"<file>">, HelpText<"Output assembly code listing file">, Flags<[DriverOption]>, Group<hlslcomp_Group>;
//def Fx : JoinedOrSeparate<["-", "/"], "Fx">, MetaVarName<"<file>">, HelpText<"Output assembly code and hex listing file">;
def Fh : JoinedOrSeparate<["-", "/"], "Fh">, MetaVarName<"<file>">, HelpText<"Output header file containing object code">, Flags<[DriverOption]>, Group<hlslcomp_Group>;
def Fe : JoinedOrSeparate<["-", "/"], "Fe">, MetaVarName<"<file>">, HelpText<"Output warnings and errors to the given file">, Flags<[CoreOption, DriverOption]>, Group<hlslcomp_Group>;
def Fd : JoinedOrSeparate<["-", "/"], "Fd">, MetaVarName<"<file>">,
HelpText<"Write debug information to the given file, or automatically named file in directory when ending in '\\'">,
Flags<[CoreOption, DriverOption]>, Group<hlslcomp_Group>;
def Fre : Separate<["-", "/"], "Fre">, MetaVarName<"<file>">, HelpText<"Output reflection to the given file">, Flags<[CoreOption, DriverOption]>, Group<hlslcomp_Group>;
def Frs : Separate<["-", "/"], "Frs">, MetaVarName<"<file>">, HelpText<"Output root signature to the given file">, Flags<[CoreOption, DriverOption]>, Group<hlslcomp_Group>;
def Fsh : Separate<["-", "/"], "Fsh">, MetaVarName<"<file>">, HelpText<"Output shader hash to the given file">, Flags<[CoreOption, DriverOption]>, Group<hlslcomp_Group>;
def Fi : JoinedOrSeparate<["-", "/"], "Fi">, MetaVarName<"<file>">,
HelpText<"Set preprocess output file name (with /P)">,
Flags<[CoreOption, DriverOption]>, Group<hlslcomp_Group>;
def Vn : JoinedOrSeparate<["-", "/"], "Vn">, MetaVarName<"<name>">, HelpText<"Use <name> as variable name in header file">, Flags<[DriverOption]>, Group<hlslcomp_Group>;
def Cc : Flag<["-", "/"], "Cc">, HelpText<"Output color coded assembly listings">, Group<hlslcomp_Group>, Flags<[DriverOption]>;
def Ni : Flag<["-", "/"], "Ni">, HelpText<"Output instruction numbers in assembly listings">, Group<hlslcomp_Group>, Flags<[DriverOption]>;
def No : Flag<["-", "/"], "No">, HelpText<"Output instruction byte offsets in assembly listings">, Group<hlslcomp_Group>, Flags<[DriverOption]>;
def Lx : Flag<["-", "/"], "Lx">, HelpText<"Output hexadecimal literals">, Group<hlslcomp_Group>, Flags<[DriverOption]>;
// In place of 'E' for clang; fxc uses 'E' for entry point.
def P : Flag<["-", "/"], "P">, Flags<[CoreOption, DriverOption]>, Group<hlslutil_Group>,
HelpText<"Preprocess to file">;
def Po : Flag<["-", "/"], "Po">, Flags<[CoreOption, DriverOption]>, Group<hlslutil_Group>,
HelpText<"Preprocess to file (deprecated, use /P /Fi instead)">;
// @<file> - options response file
def dumpbin : Flag<["-", "/"], "dumpbin">, Flags<[DriverOption]>, Group<hlslutil_Group>,
HelpText<"Load a binary file rather than compiling">;
def link : Flag<["-", "/"], "link">, Flags<[DriverOption]>, Group<hlslutil_Group>,
HelpText<"Link list of libraries provided in <inputs> argument separated by ';'">;
def Qstrip_reflect : Flag<["-", "/"], "Qstrip_reflect">, Flags<[CoreOption, DriverOption]>, Group<hlslutil_Group>,
HelpText<"Strip reflection data from shader bytecode (must be used with /Fo <file>)">;
def Qstrip_debug : Flag<["-", "/"], "Qstrip_debug">, Flags<[CoreOption, DriverOption]>, Group<hlslutil_Group>,
HelpText<"Strip debug information from 4_0+ shader bytecode (must be used with /Fo <file>)">;
def Qembed_debug : Flag<["-", "/"], "Qembed_debug">, Flags<[CoreOption]>, Group<hlslutil_Group>,
HelpText<"Embed PDB in shader container (must be used with /Zi)">;
def Qstrip_priv : Flag<["-", "/"], "Qstrip_priv">, Flags<[CoreOption, DriverOption]>, Group<hlslutil_Group>,
HelpText<"Strip private data from shader bytecode (must be used with /Fo <file>)">;
def Qsource_in_debug_module : Flag<["-", "/"], "Qsource_in_debug_module">, Flags<[CoreOption]>, Group<hlslutil_Group>,
HelpText<"Embed source code in PDB">;
def Qpdb_in_private : Flag<["-", "/"], "Qpdb_in_private">, Flags<[CoreOption, HelpHidden]>, Group<hlslutil_Group>,
HelpText<"Store PDB in private user data.">;
def Qstrip_rootsignature : Flag<["-", "/"], "Qstrip_rootsignature">, Flags<[CoreOption, DriverOption]>, Group<hlslutil_Group>, HelpText<"Strip root signature data from shader bytecode (must be used with /Fo <file>)">;
def setrootsignature : JoinedOrSeparate<["-", "/"], "setrootsignature">, MetaVarName<"<file>">, Flags<[CoreOption, DriverOption]>, Group<hlslutil_Group>, HelpText<"Attach root signature to shader bytecode">;
def extractrootsignature : Flag<["-", "/"], "extractrootsignature">, Flags<[DriverOption]>, Group<hlslutil_Group>, HelpText<"Extract root signature from shader bytecode (must be used with /Fo <file>)">;
def verifyrootsignature : JoinedOrSeparate<["-", "/"], "verifyrootsignature">, MetaVarName<"<file>">, Flags<[DriverOption]>, Group<hlslutil_Group>, HelpText<"Verify shader bytecode with root signature">;
def force_rootsig_ver : JoinedOrSeparate<["-", "/"], "force-rootsig-ver">, Flags<[CoreOption]>, MetaVarName<"<profile>">, Group<hlslcomp_Group>, HelpText<"force root signature version (rootsig_1_1 if omitted)">;
def force_rootsig_ver_ : JoinedOrSeparate<["-", "/"], "force_rootsig_ver">, Flags<[CoreOption, HelpHidden]>, MetaVarName<"<profile>">, Group<hlslcomp_Group>, HelpText<"force root signature version (rootsig_1_1 if omitted)">;
// Temporary TEST options, until reflection inside DXIL part can always be stripped
def Qkeep_reflect_in_dxil : Flag<["-", "/"], "Qkeep_reflect_in_dxil">,
Flags<[CoreOption, HelpHidden]>, Group<hlslutil_Group>,
HelpText<"Keep reflection data in shader bytecode">;
def Qstrip_reflect_from_dxil : Flag<["-", "/"], "Qstrip_reflect_from_dxil">,
Flags<[CoreOption, HelpHidden]>, Group<hlslutil_Group>,
HelpText<"Strip reflection data from shader bytecode (must be used with /Fo <file>)">;
/*
def shtemplate : JoinedOrSeparate<["-", "/"], "shtemplate">, MetaVarName<"<file>">, Group<hlslcomp_Group>,
HelpText<"Template shader file for merging/matching resources">;
def mergeUAVs : JoinedOrSeparate<["-", "/"], "mergeUAVs">, MetaVarName<"<file>">, Group<hlslcomp_Group>,
HelpText<"Merge UAV slots of template shader and current shader">;
def matchUAVs : JoinedOrSeparate<["-", "/"], "matchUAVs">, MetaVarName<"<file>">, Group<hlslcomp_Group>,
HelpText<"Match template shader UAV slots in current shader">;
def enable_unbounded_descriptor_tables : Flag<["-", "/"], "enable_unbounded_descriptor_tables">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"Enables unbounded descriptor tables">;
*/
def res_may_alias : Flag<["-", "/"], "res-may-alias">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"Assume that UAVs/SRVs may alias">;
def res_may_alias_ : Flag<["-", "/"], "res_may_alias">, Flags<[CoreOption, HelpHidden]>, Group<hlslcomp_Group>,
HelpText<"Assume that UAVs/SRVs may alias">;
def all_resources_bound : Flag<["-", "/"], "all-resources-bound">, Flags<[CoreOption]>, Group<hlslcomp_Group>,
HelpText<"Enables aggressive flattening">;
def all_resources_bound_ : Flag<["-", "/"], "all_resources_bound">, Flags<[CoreOption, HelpHidden]>, Group<hlslcomp_Group>,
HelpText<"Enables aggressive flattening">;
def setprivate : JoinedOrSeparate<["-", "/"], "setprivate">, Flags<[CoreOption, DriverOption]>, MetaVarName<"<file>">, Group<hlslutil_Group>,
HelpText<"Private data to add to compiled shader blob">;
def getprivate : JoinedOrSeparate<["-", "/"], "getprivate">, Flags<[DriverOption]>, MetaVarName<"<file>">, Group<hlslutil_Group>,
HelpText<"Save private data from shader blob">;
def nologo : Flag<["-", "/"], "nologo">, Group<hlslcore_Group>, Flags<[DriverOption, HelpHidden]>,
HelpText<"Suppress copyright message">;
//////////////////////////////////////////////////////////////////////////////
// Rewriter Options
def rw_unchanged : Flag<["-", "/"], "unchanged">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
HelpText<"Rewrite HLSL, without changes.">;
def rw_skip_function_body : Flag<["-", "/"], "skip-fn-body">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
HelpText<"Translate function definitions to declarations">;
def rw_skip_static : Flag<["-", "/"], "skip-static">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
HelpText<"Remove static functions and globals when used with -skip-fn-body">;
def rw_global_extern_by_default : Flag<["-", "/"], "global-extern-by-default">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
HelpText<"Set extern on non-static globals">;
def rw_keep_user_macro : Flag<["-", "/"], "keep-user-macro">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
HelpText<"Write out user defines after rewritten HLSL">;
def rw_extract_entry_uniforms : Flag<["-", "/"], "extract-entry-uniforms">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
HelpText<"Move uniform parameters from entry point to global scope">;
def rw_remove_unused_globals : Flag<["-", "/"], "remove-unused-globals">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
HelpText<"Remove unused static globals and functions">;
def rw_remove_unused_functions : Flag<["-", "/"], "remove-unused-functions">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
HelpText<"Remove unused functions and types">;
def rw_line_directive : Flag<["-", "/"], "line-directive">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
HelpText<"Add line directive">;
def rw_decl_global_cb : Flag<["-", "/"], "decl-global-cb">, Group<hlslrewrite_Group>, Flags<[RewriteOption]>,
HelpText<"Collect all global constants outside cbuffer declarations into cbuffer GlobalCB { ... }. Still experimental, not all dependency scenarios handled.">;
// Also removed: compress, decompress, /Gch (child effect), /Gpp (partial precision)
// /Op - no support for preshaders.

1651
vendor/dxc/gen_intrin_main.txt vendored Normal file

File diff suppressed because it is too large Load Diff

222
vendor/hlsl-headers/LICENSE.txt vendored Normal file
View File

@ -0,0 +1,222 @@
==============================================================================
The LLVM Project is under the Apache License v2.0 with LLVM Exceptions:
==============================================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
---- LLVM Exceptions to the Apache 2.0 License ----
As an exception, if, as a result of your compiling your source code, portions
of this Software are embedded into an Object form of such source code, you
may redistribute such embedded portions in such Object form without complying
with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
In addition, if you combine or link compiled forms of this Software with
software that is licensed under the GPLv2 ("Combined Software") and if a
court of competent jurisdiction determines that the patent provision (Section
3), the indemnity provision (Section 9) or other Section of the License
conflicts with the conditions of the GPLv2, you may retroactively and
prospectively choose to deem waived or otherwise exclude such Section(s) of
the License, but only in their entirety and only with respect to the Combined
Software.

7
vendor/hlsl-headers/README.txt vendored Normal file
View File

@ -0,0 +1,7 @@
HLSL Standard Header Library
============================
The contents of this directory and subdirectories are the HLSL Standard Header
library. These headers are open source software. You may freely distribute all
or parts of these headers under the terms of the license agreement found in
LICENSE.txt.

727
vendor/hlsl-headers/dx/linalg.h vendored Normal file
View File

@ -0,0 +1,727 @@
//===----------------------------------------------------------------------===//
//
// Part of the DirectXShaderCompiler, under the Apache License v2.0 with LLVM
// Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// DirectX Shader Model 6.10 Linear Algebra objects and APIs.
//===----------------------------------------------------------------------===//
#ifndef _HLSL_DX_LINALG_H_
#define _HLSL_DX_LINALG_H_
#include <enable_if>
#include <type_traits>
#if ((__SHADER_TARGET_MAJOR > 6) || \
(__SHADER_TARGET_MAJOR == 6 && __SHADER_TARGET_MINOR >= 10)) && \
(__HLSL_VERSION >= 2021)
#pragma dxc diagnostic push
#pragma dxc diagnostic ignored "-Whlsl-groupshared-202x"
namespace dxil {
// This enum must _exactly_ match the DXIL constants.
enum class ComponentType : uint32_t {
Invalid = 0,
I1 = 1,
I16 = 2,
U16 = 3,
I32 = 4,
U32 = 5,
I64 = 6,
U64 = 7,
F16 = 8,
F32 = 9,
F64 = 10,
SNormF16 = 11,
UNormF16 = 12,
SNormF32 = 13,
UNormF32 = 14,
SNormF64 = 15,
UNormF64 = 16,
PackedS8x32 = 17,
PackedU8x32 = 18,
// BEGIN NEW FOR SM 6.9
I8 = 19,
U8 = 20,
F8_E4M3FN = 21,
F8_E5M2 = 22,
// END
// BEGIN NEW FOR SM 6.10
BFloat16 = 23,
// END
LastEntry
};
} // namespace dxil
namespace dx {
namespace linalg {
#define __COMPONENT_TYPE(type) type = (uint)dxil::ComponentType::type
// This enum only defines values that are valid for Matrix component types.
// Each enumeration's value matches the cooresponding DXIL constant.
struct ComponentType {
enum ComponentEnum {
// Signed integers.
__COMPONENT_TYPE(I8),
__COMPONENT_TYPE(I16),
__COMPONENT_TYPE(I32),
__COMPONENT_TYPE(I64),
// Unsigned integers.
__COMPONENT_TYPE(U8),
__COMPONENT_TYPE(U16),
__COMPONENT_TYPE(U32),
__COMPONENT_TYPE(U64),
// Floating point types.
__COMPONENT_TYPE(F8_E4M3FN),
__COMPONENT_TYPE(F8_E5M2),
__COMPONENT_TYPE(F16),
__COMPONENT_TYPE(F32),
__COMPONENT_TYPE(F64),
__COMPONENT_TYPE(BFloat16),
};
};
#undef __COMPONENT_TYPE
using ComponentEnum = ComponentType::ComponentEnum;
struct MatrixUse {
enum MatrixUseEnum {
A = 0,
B = 1,
Accumulator = 2,
};
};
using MatrixUseEnum = MatrixUse::MatrixUseEnum;
struct MatrixScope {
enum MatrixScopeEnum {
Thread = 0,
Wave = 1,
ThreadGroup = 2,
};
};
using MatrixScopeEnum = MatrixScope::MatrixScopeEnum;
struct MatrixLayout {
enum MatrixLayoutEnum {
RowMajor = 0,
ColMajor = 1,
MulOptimal = 2,
MulOptimalTranspose = 3,
OuterProductOptimal = 4,
OuterProductOptimalTranspose = 5,
};
};
using MatrixLayoutEnum = MatrixLayout::MatrixLayoutEnum;
namespace __detail {
template <ComponentEnum> struct ComponentTypeTraits {
using Type = uint;
static const bool IsNativeScalar = false;
static const uint ElementsPerScalar = 4;
};
template <typename> struct TypeTraits {
static const ComponentEnum CompType =
(ComponentEnum)dxil::ComponentType::Invalid;
};
template <ComponentEnum> struct IsComponentTypeAvailable {
static const bool value = true;
};
#if !__HLSL_ENABLE_16_BIT
template <> struct IsComponentTypeAvailable<ComponentType::I16> {
static const bool value = false;
};
template <> struct IsComponentTypeAvailable<ComponentType::U16> {
static const bool value = false;
};
template <> struct IsComponentTypeAvailable<ComponentType::F16> {
static const bool value = false;
};
#endif
template <ComponentEnum CT, typename Ty> struct IsCompatibleVectorElement {
static const bool IsPackedCarrier =
hlsl::is_same<Ty, uint8_t4_packed>::value ||
hlsl::is_same<Ty, int8_t4_packed>::value;
static const bool value =
IsComponentTypeAvailable<CT>::value &&
(hlsl::is_same<Ty, typename ComponentTypeTraits<CT>::Type>::value ||
(!ComponentTypeTraits<CT>::IsNativeScalar && IsPackedCarrier));
};
template <> struct ComponentTypeTraits<ComponentType::BFloat16> {
using Type = uint;
static const bool IsNativeScalar = false;
static const uint ElementsPerScalar = 2;
};
#define __MATRIX_SCALAR_COMPONENT_MAPPING(enum_val, type) \
template <> struct ComponentTypeTraits<enum_val> { \
using Type = type; \
static const bool IsNativeScalar = true; \
static const uint ElementsPerScalar = 1; \
}; \
template <> struct TypeTraits<type> { \
static const ComponentEnum CompType = enum_val; \
};
#if __HLSL_ENABLE_16_BIT
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::I16, int16_t)
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::U16, uint16_t)
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::F16, float16_t)
#endif
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::I32, int32_t)
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::U32, uint32_t)
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::F32, float)
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::I64, int64_t)
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::U64, uint64_t)
__MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::F64, double)
template <ComponentEnum DstCT, ComponentEnum SrcCT, int SrcN> struct DstN {
// Make sure to round up in case SrcN isn't an even multiple of the number of
// elements per scalar
static const int Value =
(SrcN * ComponentTypeTraits<SrcCT>::ElementsPerScalar +
ComponentTypeTraits<DstCT>::ElementsPerScalar - 1) /
ComponentTypeTraits<DstCT>::ElementsPerScalar;
};
template <SIZE_TYPE MVal, SIZE_TYPE NVal, bool Transposed> struct DimMN {
static const SIZE_TYPE M = MVal;
static const SIZE_TYPE N = NVal;
};
template <SIZE_TYPE MVal, SIZE_TYPE NVal> struct DimMN<MVal, NVal, true> {
static const SIZE_TYPE M = NVal;
static const SIZE_TYPE N = MVal;
};
template <ComponentEnum CT, SIZE_TYPE PackedComponentCount>
struct ScalarCountFromPackedComponents {
static const SIZE_TYPE ElementsPerScalar =
ComponentTypeTraits<CT>::ElementsPerScalar;
static const SIZE_TYPE Value =
(PackedComponentCount + ElementsPerScalar - 1) / ElementsPerScalar;
};
template <ComponentEnum CT, SIZE_TYPE M, SIZE_TYPE N> struct DefaultAlign {
enum {
MinDim = M < N ? M : N,
ScalarCount = ScalarCountFromPackedComponents<CT, MinDim>::Value,
ByteAlign = ScalarCount * 4,
MinByteAlign = ByteAlign < 4 ? 4 : ByteAlign,
Value = MinByteAlign < 16 ? MinByteAlign : 16
};
};
} // namespace __detail
template <ComponentEnum CT, uint DimA> struct VectorRef {
ByteAddressBuffer Buf;
uint Offset;
};
template <typename Ty, int N, ComponentEnum CT> struct InterpretedVector {
vector<Ty, N> Data;
static const ComponentEnum Interpretation = CT;
static const SIZE_TYPE Size =
__detail::ComponentTypeTraits<CT>::ElementsPerScalar * N;
};
template <ComponentEnum CT, typename Ty, int N>
typename hlsl::enable_if< __detail::IsCompatibleVectorElement<CT, Ty>::value,
InterpretedVector<Ty, N, CT> >::type
MakeInterpretedVector(vector<Ty, N> Vec) {
InterpretedVector<Ty, N, CT> IV = {Vec};
return IV;
}
template <ComponentEnum DestCT, ComponentEnum OriginCT, typename Ty, int N>
typename hlsl::enable_if<
DestCT != OriginCT && __detail::IsComponentTypeAvailable<DestCT>::value &&
__detail::IsCompatibleVectorElement<OriginCT, Ty>::value,
InterpretedVector<typename __detail::ComponentTypeTraits<DestCT>::Type,
__detail::DstN<DestCT, OriginCT, N>::Value,
DestCT> >::type
Convert(vector<Ty, N> Vec) {
vector<typename __detail::ComponentTypeTraits<DestCT>::Type,
__detail::DstN<DestCT, OriginCT, N>::Value>
Result;
dx::__builtin_LinAlg_Convert(Result, Vec, OriginCT, DestCT);
return MakeInterpretedVector<DestCT>(Result);
}
template <ComponentEnum DestCT, ComponentEnum OriginCT, typename Ty, int N>
typename hlsl::enable_if<
DestCT == OriginCT &&
__detail::IsCompatibleVectorElement<OriginCT, Ty>::value,
InterpretedVector<Ty, N, DestCT> >::type
Convert(vector<Ty, N> Vec) {
return MakeInterpretedVector<DestCT>(Vec);
}
template <ComponentEnum CT, SIZE_TYPE M, SIZE_TYPE N, MatrixUseEnum Use,
MatrixScopeEnum Scope>
class Matrix {
using ElementType = typename __detail::ComponentTypeTraits<CT>::Type;
// If this isn't a native scalar, we have a type that may pack more than 1
// element in each scalar value. (Ex. 8bit => 4elems, 16bit => 2elems)
static const uint ElementsPerScalar =
__detail::ComponentTypeTraits<CT>::ElementsPerScalar;
static const bool IsNativeScalar =
__detail::ComponentTypeTraits<CT>::IsNativeScalar;
using HandleT = __builtin_LinAlgMatrix
[[__LinAlgMatrix_Attributes(CT, M, N, Use, Scope)]];
HandleT __handle;
template <ComponentEnum NewCT, MatrixUseEnum NewUse = Use,
bool Transpose = false>
[[nodiscard]] Matrix<NewCT, __detail::DimMN<M, N, Transpose>::M,
__detail::DimMN<M, N, Transpose>::N, NewUse, Scope>
Cast() {
Matrix<NewCT, __detail::DimMN<M, N, Transpose>::M,
__detail::DimMN<M, N, Transpose>::N, NewUse, Scope>
Result;
dx::__builtin_LinAlg_CopyConvertMatrix(Result.__handle, __handle,
Transpose);
return Result;
}
template <typename Ty>
[[nodiscard]] static
typename hlsl::enable_if<hlsl::is_arithmetic<Ty>::value, Matrix>::type
Splat(Ty Val) {
Matrix Result;
dx::__builtin_LinAlg_FillMatrix(Result.__handle, hlsl::is_signed<Ty>::value,
Val);
return Result;
}
template <uint Align = __detail::DefaultAlign<CT, M, N>::Value>
[[nodiscard]] static Matrix Load(ByteAddressBuffer Res, uint StartOffset,
uint Stride, MatrixLayoutEnum Layout) {
Matrix Result;
dx::__builtin_LinAlg_MatrixLoadFromDescriptor(
Result.__handle, Res, StartOffset, Stride, Layout, Align);
return Result;
}
template <uint Align = __detail::DefaultAlign<CT, M, N>::Value>
[[nodiscard]] static Matrix Load(RWByteAddressBuffer Res, uint StartOffset,
uint Stride, MatrixLayoutEnum Layout) {
Matrix Result;
dx::__builtin_LinAlg_MatrixLoadFromDescriptor(
Result.__handle, Res, StartOffset, Stride, Layout, Align);
return Result;
}
template <typename Ty, SIZE_TYPE Size>
[[nodiscard]] static typename hlsl::enable_if<
(hlsl::is_same<typename hlsl::strip_vector_type<Ty>::type,
ElementType>::value ||
hlsl::is_integral_or_packed_integral<
typename hlsl::strip_vector_type<Ty>::type>::value),
Matrix>::type
Load(groupshared Ty Arr[Size], uint StartIdx, uint Stride,
MatrixLayoutEnum Layout) {
Matrix Result;
dx::__builtin_LinAlg_MatrixLoadFromMemory(Result.__handle, Arr, StartIdx,
Stride, Layout);
return Result;
}
template <ComponentEnum LocalCT = CT>
typename hlsl::enable_if<LocalCT == CT && IsNativeScalar, uint>::type
Length() {
return dx::__builtin_LinAlg_MatrixLength(__handle);
}
template <ComponentEnum LocalCT = CT>
typename hlsl::enable_if<LocalCT == CT && IsNativeScalar, uint2>::type
GetCoordinate(uint Index) {
return dx::__builtin_LinAlg_MatrixGetCoordinate(__handle, Index);
}
template <ComponentEnum LocalCT = CT>
typename hlsl::enable_if<LocalCT == CT && IsNativeScalar, ElementType>::type
Get(uint Index) {
ElementType Result;
dx::__builtin_LinAlg_MatrixGetElement(Result, __handle, Index);
return Result;
}
template <ComponentEnum LocalCT = CT>
typename hlsl::enable_if<LocalCT == CT && IsNativeScalar, void>::type
Set(uint Index, ElementType Value) {
dx::__builtin_LinAlg_MatrixSetElement(__handle, __handle, Index, Value);
}
template <uint Align = __detail::DefaultAlign<CT, M, N>::Value>
void Store(RWByteAddressBuffer Res, uint StartOffset, uint Stride,
MatrixLayoutEnum Layout) {
dx::__builtin_LinAlg_MatrixStoreToDescriptor(__handle, Res, StartOffset,
Stride, Layout, Align);
}
template <typename Ty, SIZE_TYPE Size>
typename hlsl::enable_if<
(hlsl::is_same<typename hlsl::strip_vector_type<Ty>::type,
ElementType>::value ||
hlsl::is_integral_or_packed_integral<
typename hlsl::strip_vector_type<Ty>::type>::value),
void>::type
Store(groupshared Ty Arr[Size], uint StartIdx, uint Stride,
MatrixLayoutEnum Layout) {
dx::__builtin_LinAlg_MatrixStoreToMemory(__handle, Arr, StartIdx, Stride,
Layout);
}
// Accumulate methods
template <uint Align = __detail::DefaultAlign<CT, M, N>::Value,
MatrixUseEnum UseLocal = Use>
typename hlsl::enable_if<Use == MatrixUse::Accumulator && UseLocal == Use,
void>::type
InterlockedAccumulate(RWByteAddressBuffer Res, uint StartOffset, uint Stride,
MatrixLayoutEnum Layout) {
dx::__builtin_LinAlg_MatrixAccumulateToDescriptor(
__handle, Res, StartOffset, Stride, Layout, Align);
}
template <typename Ty, MatrixUseEnum UseLocal = Use, SIZE_TYPE Size>
typename hlsl::enable_if<
hlsl::is_same<typename hlsl::strip_vector_type<Ty>::type,
ElementType>::value &&
hlsl::is_arithmetic_vector<Ty>::value &&
Use == MatrixUse::Accumulator && UseLocal == Use,
void>::type
InterlockedAccumulate(groupshared Ty Arr[Size], uint StartIdx, uint Stride,
MatrixLayoutEnum Layout) {
dx::__builtin_LinAlg_MatrixAccumulateToMemory(__handle, Arr, StartIdx,
Stride, Layout);
}
template <typename Ty, MatrixUseEnum UseLocal = Use, SIZE_TYPE Size>
typename hlsl::enable_if<
hlsl::is_same<typename hlsl::strip_vector_type<Ty>::type,
uint8_t4_packed>::value &&
Use == MatrixUse::Accumulator && UseLocal == Use,
void>::type
InterlockedAccumulate(groupshared Ty Arr[Size], uint StartIdx, uint Stride,
MatrixLayoutEnum Layout) {
dx::__builtin_LinAlg_MatrixAccumulateToMemory(__handle, Arr, StartIdx,
Stride, Layout);
}
template <ComponentEnum MatrixCT, MatrixUseEnum UseLocal = Use>
typename hlsl::enable_if<Use == MatrixUse::Accumulator && UseLocal == Use,
void>::type
Accumulate(const Matrix<MatrixCT, M, N, MatrixUse::A, Scope> MatrixA) {
dx::__builtin_LinAlg_MatrixAccumulate(__handle, __handle, MatrixA.__handle);
}
template <ComponentEnum MatrixCT, MatrixUseEnum UseLocal = Use>
typename hlsl::enable_if<Use == MatrixUse::Accumulator && UseLocal == Use,
void>::type
Accumulate(const Matrix<MatrixCT, M, N, MatrixUse::B, Scope> MatrixB) {
dx::__builtin_LinAlg_MatrixAccumulate(__handle, __handle, MatrixB.__handle);
}
template <ComponentEnum LHSCT, ComponentEnum RHSCT, SIZE_TYPE K,
MatrixUseEnum UseLocal = Use>
typename hlsl::enable_if<Use == MatrixUse::Accumulator && UseLocal == Use,
void>::type
MultiplyAccumulate(const Matrix<LHSCT, M, K, MatrixUse::A, Scope> MatrixA,
const Matrix<RHSCT, K, N, MatrixUse::B, Scope> MatrixB) {
dx::__builtin_LinAlg_MatrixMatrixMultiplyAccumulate(
__handle, MatrixA.__handle, MatrixB.__handle, __handle);
}
};
// Thread-scope Matrices are read-only. Using a template partial
// specialization for this simplifies the SFINAE-foo above.
template <ComponentEnum CT, SIZE_TYPE M, SIZE_TYPE N, MatrixUseEnum Use>
class Matrix<CT, M, N, Use, MatrixScope::Thread> {
using ElementType = typename __detail::ComponentTypeTraits<CT>::Type;
using HandleT = __builtin_LinAlgMatrix
[[__LinAlgMatrix_Attributes(CT, M, N, Use, MatrixScope::Thread)]];
HandleT __handle;
template <MatrixLayoutEnum Layout, uint Align = 128,
MatrixUseEnum UseLocal = Use>
[[nodiscard]] static
typename hlsl::enable_if<Use == MatrixUse::A && UseLocal == Use,
Matrix>::type
Load(ByteAddressBuffer Res, uint StartOffset, uint Stride) {
Matrix Result;
dx::__builtin_LinAlg_MatrixLoadFromDescriptor(
Result.__handle, Res, StartOffset, Stride, Layout, Align);
return Result;
}
template <uint Align = 128, MatrixUseEnum UseLocal = Use>
typename hlsl::enable_if<Use == MatrixUse::Accumulator && UseLocal == Use,
void>::type
InterlockedAccumulate(RWByteAddressBuffer Res, uint StartOffset) {
dx::__builtin_LinAlg_MatrixAccumulateToDescriptor(
__handle, Res, StartOffset, 0, MatrixLayout::OuterProductOptimal,
Align);
}
};
MatrixUseEnum AccumulatorLayout() {
return (MatrixUseEnum)(dx::__builtin_LinAlg_MatrixQueryAccumulatorLayout());
}
template <ComponentEnum OutCT, ComponentEnum ACT, ComponentEnum BCT,
SIZE_TYPE M, SIZE_TYPE N, SIZE_TYPE K>
[[nodiscard]] Matrix<OutCT, M, N, MatrixUse::Accumulator, MatrixScope::Wave>
Multiply(const Matrix<ACT, M, K, MatrixUse::A, MatrixScope::Wave> MatrixA,
const Matrix<BCT, K, N, MatrixUse::B, MatrixScope::Wave> MatrixB) {
Matrix<OutCT, M, N, MatrixUse::Accumulator, MatrixScope::Wave> Result;
dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle,
MatrixB.__handle);
return Result;
}
template <ComponentEnum CT, SIZE_TYPE M, SIZE_TYPE N, SIZE_TYPE K>
[[nodiscard]] Matrix<CT, M, N, MatrixUse::Accumulator, MatrixScope::Wave>
Multiply(const Matrix<CT, M, K, MatrixUse::A, MatrixScope::Wave> MatrixA,
const Matrix<CT, K, N, MatrixUse::B, MatrixScope::Wave> MatrixB) {
Matrix<CT, M, N, MatrixUse::Accumulator, MatrixScope::Wave> Result;
dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle,
MatrixB.__handle);
return Result;
}
template <ComponentEnum OutCT, ComponentEnum ACT, ComponentEnum BCT,
SIZE_TYPE M, SIZE_TYPE N, SIZE_TYPE K>
[[nodiscard]] Matrix<OutCT, M, N, MatrixUse::Accumulator,
MatrixScope::ThreadGroup>
Multiply(
const Matrix<ACT, M, K, MatrixUse::A, MatrixScope::ThreadGroup> MatrixA,
const Matrix<BCT, K, N, MatrixUse::B, MatrixScope::ThreadGroup> MatrixB) {
Matrix<OutCT, M, N, MatrixUse::Accumulator, MatrixScope::ThreadGroup> Result;
dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle,
MatrixB.__handle);
return Result;
}
template <ComponentEnum CT, SIZE_TYPE M, SIZE_TYPE N, SIZE_TYPE K>
[[nodiscard]] Matrix<CT, M, N, MatrixUse::Accumulator, MatrixScope::ThreadGroup>
Multiply(
const Matrix<CT, M, K, MatrixUse::A, MatrixScope::ThreadGroup> MatrixA,
const Matrix<CT, K, N, MatrixUse::B, MatrixScope::ThreadGroup> MatrixB) {
Matrix<CT, M, N, MatrixUse::Accumulator, MatrixScope::ThreadGroup> Result;
dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle,
MatrixB.__handle);
return Result;
}
// Cooperative Vector Replacement API
// Cooperative Vector operates on per-thread vectors multiplying against B
// matrices with thread scope.
template <typename OutputTy, typename InputTy, SIZE_TYPE M, SIZE_TYPE K,
ComponentEnum CT>
typename hlsl::enable_if<hlsl::is_arithmetic<InputTy>::value,
vector<OutputTy, M> >::type
Multiply(Matrix<CT, M, K, MatrixUse::A, MatrixScope::Thread> MatrixA,
vector<InputTy, K> Vec) {
vector<OutputTy, M> Result;
dx::__builtin_LinAlg_MatrixVectorMultiply(
Result, MatrixA.__handle, hlsl::is_signed<OutputTy>::value, Vec,
__detail::TypeTraits<InputTy>::CompType);
return Result;
}
template <typename OutputTy, typename InputTy, ComponentEnum InputCT,
SIZE_TYPE M, SIZE_TYPE K, SIZE_TYPE VecK, ComponentEnum MatrixCT>
typename hlsl::enable_if<
InterpretedVector<InputTy, VecK, InputCT>::Size == K &&
__detail::IsCompatibleVectorElement<InputCT, InputTy>::value,
vector<OutputTy, M> >::type
Multiply(Matrix<MatrixCT, M, K, MatrixUse::A, MatrixScope::Thread> MatrixA,
InterpretedVector<InputTy, VecK, InputCT> InterpVec) {
vector<OutputTy, M> Result;
dx::__builtin_LinAlg_MatrixVectorMultiply(
Result, MatrixA.__handle, hlsl::is_signed<OutputTy>::value,
InterpVec.Data, InterpVec.Interpretation);
return Result;
}
template <typename OutputTy, typename InputTy, typename BiasTy, SIZE_TYPE M,
SIZE_TYPE K, ComponentEnum CT>
typename hlsl::enable_if<hlsl::is_arithmetic<InputTy>::value &&
hlsl::is_arithmetic<BiasTy>::value,
vector<OutputTy, M> >::type
MultiplyAdd(Matrix<CT, M, K, MatrixUse::A, MatrixScope::Thread> MatrixA,
vector<InputTy, K> Vec, vector<BiasTy, M> Bias) {
InterpretedVector<OutputTy, M, __detail::TypeTraits<OutputTy>::CompType>
BiasConvInterp = Convert<__detail::TypeTraits<OutputTy>::CompType,
__detail::TypeTraits<BiasTy>::CompType>(Bias);
vector<OutputTy, M> Result;
dx::__builtin_LinAlg_MatrixVectorMultiplyAdd(
Result, MatrixA.__handle, hlsl::is_signed<OutputTy>::value, Vec,
__detail::TypeTraits<InputTy>::CompType, BiasConvInterp.Data);
return Result;
}
template <typename OutputTy, typename InputTy, ComponentEnum InputCT,
typename BiasTy, SIZE_TYPE M, SIZE_TYPE K, SIZE_TYPE VecK,
ComponentEnum MatrixCT>
typename hlsl::enable_if<
VecK == __detail::ScalarCountFromPackedComponents<InputCT, K>::Value &&
__detail::IsCompatibleVectorElement<InputCT, InputTy>::value &&
hlsl::is_arithmetic<BiasTy>::value,
vector<OutputTy, M> >::type
MultiplyAdd(Matrix<MatrixCT, M, K, MatrixUse::A, MatrixScope::Thread> MatrixA,
InterpretedVector<InputTy, VecK, InputCT> InterpVec,
vector<BiasTy, M> Bias) {
InterpretedVector<OutputTy, M, __detail::TypeTraits<OutputTy>::CompType>
BiasConvInterp = Convert<__detail::TypeTraits<OutputTy>::CompType,
__detail::TypeTraits<BiasTy>::CompType>(Bias);
vector<OutputTy, M> Result;
dx::__builtin_LinAlg_MatrixVectorMultiplyAdd(
Result, MatrixA.__handle, hlsl::is_signed<OutputTy>::value,
InterpVec.Data, InterpVec.Interpretation, BiasConvInterp.Data);
return Result;
}
template <typename OutputTy, typename InputTy, ComponentEnum BiasCT,
SIZE_TYPE M, SIZE_TYPE K, ComponentEnum MatrixCT>
typename hlsl::enable_if<hlsl::is_arithmetic<InputTy>::value,
vector<OutputTy, M> >::type
MultiplyAdd(Matrix<MatrixCT, M, K, MatrixUse::A, MatrixScope::Thread> MatrixA,
vector<InputTy, K> Vec, VectorRef<BiasCT, M> BiasRef) {
using BiasVecTy =
vector<typename __detail::ComponentTypeTraits<BiasCT>::Type,
__detail::ScalarCountFromPackedComponents<BiasCT, M>::Value>;
BiasVecTy Bias = BiasRef.Buf.template Load<BiasVecTy>(BiasRef.Offset);
// Convert currently does not support packed type vector sizes that
// are not a multiple of the number of elements per scalar, so we
// need to do an extra conversion here to get it into the right shape.
// For example, if BiasRef is F8_E4M3FN and M is 7, it gets loaded into
// vector<uint, 2>, and if OutputTy is half, Convert will return
// vector<half, 8> instead of vector<half, 7>.
// https://github.com/microsoft/DirectXShaderCompiler/issues/8418
//
// Convert to OutputTy vector with padding
using BiasConvInterpPaddedTy = InterpretedVector<
OutputTy,
__detail::DstN<
__detail::TypeTraits<OutputTy>::CompType, BiasCT,
__detail::ScalarCountFromPackedComponents< BiasCT, M>::Value>::Value,
__detail::TypeTraits<OutputTy>::CompType>;
BiasConvInterpPaddedTy BiasConvInterpPadded =
Convert<__detail::TypeTraits<OutputTy>::CompType, BiasCT>(Bias);
// Truncate the vector to the correct size M
vector<OutputTy, M> BiasConv = (vector<OutputTy, M>)BiasConvInterpPadded.Data;
vector<OutputTy, M> Result;
dx::__builtin_LinAlg_MatrixVectorMultiplyAdd(
Result, MatrixA.__handle, hlsl::is_signed<OutputTy>::value, Vec,
__detail::TypeTraits<InputTy>::CompType, BiasConv);
return Result;
}
template <typename OutputTy, typename InputTy, ComponentEnum InputCT,
ComponentEnum BiasCT, SIZE_TYPE M, SIZE_TYPE K, SIZE_TYPE VecK,
ComponentEnum MatrixCT>
typename hlsl::enable_if<
VecK == __detail::ScalarCountFromPackedComponents<InputCT, K>::Value &&
__detail::IsCompatibleVectorElement<InputCT, InputTy>::value,
vector<OutputTy, M> >::type
MultiplyAdd(Matrix<MatrixCT, M, K, MatrixUse::A, MatrixScope::Thread> MatrixA,
InterpretedVector<InputTy, VecK, InputCT> InterpVec,
VectorRef<BiasCT, M> BiasRef) {
using BiasVecTy =
vector<typename __detail::ComponentTypeTraits<BiasCT>::Type,
__detail::ScalarCountFromPackedComponents<BiasCT, M>::Value>;
BiasVecTy Bias = BiasRef.Buf.template Load<BiasVecTy>(BiasRef.Offset);
// Convert currently does not support packed type vector sizes that
// are not a multiple of the number of elements per scalar, so we
// need to do an extra conversion here to get it into the right shape.
// For example, if BiasRef is F8_E4M3FN and M is 7, it gets loaded into
// vector<uint, 2>, and if OutputTy is half, Convert will return
// vector<half, 8> instead of vector<half, 7>.
// https://github.com/microsoft/DirectXShaderCompiler/issues/8418
//
// Convert to OutputTy vector with padding
using BiasConvInterpPaddedTy = InterpretedVector<
OutputTy,
__detail::DstN<
__detail::TypeTraits<OutputTy>::CompType, BiasCT,
__detail::ScalarCountFromPackedComponents< BiasCT, M>::Value>::Value,
__detail::TypeTraits<OutputTy>::CompType>;
BiasConvInterpPaddedTy BiasConvInterpPadded =
Convert<__detail::TypeTraits<OutputTy>::CompType, BiasCT>(Bias);
// Truncate the vector to the correct size M
vector<OutputTy, M> BiasConv = (vector<OutputTy, M>)BiasConvInterpPadded.Data;
vector<OutputTy, M> Result;
dx::__builtin_LinAlg_MatrixVectorMultiplyAdd(
Result, MatrixA.__handle, hlsl::is_signed<OutputTy>::value,
InterpVec.Data, InterpVec.Interpretation, BiasConv);
return Result;
}
// Outer product functions
template <ComponentEnum CT, typename InputTy, SIZE_TYPE M, SIZE_TYPE N>
[[nodiscard]] typename hlsl::enable_if<
hlsl::is_arithmetic<InputTy>::value,
Matrix<CT, M, N, MatrixUse::Accumulator, MatrixScope::Thread> >::type
OuterProduct(vector<InputTy, M> VecA, vector<InputTy, N> VecB) {
Matrix<CT, M, N, MatrixUse::Accumulator, MatrixScope::Thread> Result;
dx::__builtin_LinAlg_MatrixOuterProduct(
Result.__handle, hlsl::is_signed<InputTy>::value, VecA, VecB);
return Result;
}
template <uint Align = 64, typename InputTy, SIZE_TYPE M>
typename hlsl::enable_if<hlsl::is_arithmetic<InputTy>::value, void>::type
InterlockedAccumulate(RWByteAddressBuffer Res, uint StartOffset,
vector<InputTy, M> Vec) {
dx::__builtin_LinAlg_VectorAccumulateToDescriptor(Res, StartOffset, Align,
Vec);
}
} // namespace linalg
} // namespace dx
#pragma dxc diagnostic pop
#endif // SM 6.10 check and HV version check
#endif // _HLSL_DX_LINALG_H_

29
vendor/hlsl-headers/enable_if vendored Normal file
View File

@ -0,0 +1,29 @@
//===----------------------------------------------------------------------===//
//
// Part of the DirectXShaderCompiler, under the Apache License v2.0 with LLVM
// Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// SFINAE construct for enable_if to enable and disable declarations.
//===----------------------------------------------------------------------===//
#ifndef __HLSL_ENABLE_IF
#define __HLSL_ENABLE_IF
#if __HLSL_VERSION >= 2021
namespace hlsl {
template <bool B, typename T> struct enable_if {};
template <typename T> struct enable_if<true, T> {
using type = T;
};
} // namespace hlsl
#endif // __HLSL_VERSION >= 2021
#endif // __HLSL_ENABLE_IF

134
vendor/hlsl-headers/type_traits vendored Normal file
View File

@ -0,0 +1,134 @@
//===----------------------------------------------------------------------===//
//
// Part of the DirectXShaderCompiler, under the Apache License v2.0 with LLVM
// Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Template trait constructs for driving template specialization.
//===----------------------------------------------------------------------===//
#ifndef __HLSL_TYPE_TRAITS
#define __HLSL_TYPE_TRAITS
#if __HLSL_VERSION >= 2021
#define SIZE_TYPE int
namespace hlsl {
template <typename T, typename U> struct is_same {
static const bool value = false;
};
template <typename T> struct is_same<T, T> {
static const bool value = true;
};
template <typename T> struct is_arithmetic {
static const bool value = false;
};
#define __ARITHMETIC_TYPE(type) \
template <> struct is_arithmetic<type> { \
static const bool value = true; \
};
#if __HLSL_ENABLE_16_BIT
__ARITHMETIC_TYPE(uint16_t)
__ARITHMETIC_TYPE(int16_t)
#endif
__ARITHMETIC_TYPE(uint)
__ARITHMETIC_TYPE(int)
__ARITHMETIC_TYPE(uint64_t)
__ARITHMETIC_TYPE(int64_t)
__ARITHMETIC_TYPE(half)
__ARITHMETIC_TYPE(float)
__ARITHMETIC_TYPE(double)
#undef __ARITHMETIC_TYPE
template <typename T> struct is_integral {
static const bool value = false;
};
#define __INTEGRAL_TYPE(type) \
template <> struct is_integral<type> { \
static const bool value = true; \
};
#if __HLSL_ENABLE_16_BIT
__INTEGRAL_TYPE(uint16_t)
__INTEGRAL_TYPE(int16_t)
#endif
__INTEGRAL_TYPE(uint)
__INTEGRAL_TYPE(int)
__INTEGRAL_TYPE(uint64_t)
__INTEGRAL_TYPE(int64_t)
#undef __INTEGRAL_TYPE
template <typename T> struct is_packed_integral {
static const bool value = false;
};
#if __hlsl_dx_compiler
template <> struct is_packed_integral<uint8_t4_packed> {
static const bool value = true;
};
template <> struct is_packed_integral<int8_t4_packed> {
static const bool value = true;
};
#endif
template <typename T> struct is_integral_or_packed_integral {
static const bool value =
is_integral<T>::value || is_packed_integral<T>::value;
};
template <typename T> struct is_signed {
static const bool value = true;
};
#define __UNSIGNED_TYPE(type) \
template <> struct is_signed<type> { \
static const bool value = false; \
};
#if __HLSL_ENABLE_16_BIT
__UNSIGNED_TYPE(uint16_t)
#endif
__UNSIGNED_TYPE(uint)
__UNSIGNED_TYPE(uint64_t)
#undef __UNSIGNED_TYPE
template <typename T> struct is_vector {
static const bool value = false;
};
template <typename T, uint N> struct is_vector<vector<T, N> > {
static const bool value = true;
};
template <typename T> struct strip_vector_type {
using type = T;
};
template <typename T, SIZE_TYPE N> struct strip_vector_type<vector<T, N> > {
using type = T;
};
template <typename T> struct is_arithmetic_vector {
static const bool value =
is_arithmetic<T>::value ||
(is_vector<T>::value &&
is_arithmetic<typename strip_vector_type<T>::type>::value);
};
} // namespace hlsl
#endif // __HLSL_VERSION >= 2021
#endif // __HLSL_TYPE_TRAITS

42
vendor/hlsl-headers/vector_utils vendored Normal file
View File

@ -0,0 +1,42 @@
//===----------------------------------------------------------------------===//
//
// Part of the DirectXShaderCompiler, under the Apache License v2.0 with LLVM
// Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Header for vector template utility functions for operating on vector
// templates.
//===----------------------------------------------------------------------===//
#ifndef __HLSL_VECTOR_UTILS
#define __HLSL_VECTOR_UTILS
#if __HLSL_VERSION >= 2021
#include <enable_if>
namespace hlsl {
template <int Off, int OSz, typename T, int ISz>
typename hlsl::enable_if<Off + OSz <= ISz, vector<T, OSz> >::type
slice(vector<T, ISz> In) {
vector<T, OSz> Result = (vector<T, OSz>)0;
[unroll]
for (int I = 0; I < OSz; ++I)
Result[I] = In[I + Off];
return Result;
}
template <int OSz, typename T, int ISz>
vector<T, OSz> slice(vector<T, ISz> In) {
return slice<0, OSz, T, ISz>(In);
}
} // namespace hlsl
#endif // __HLSL_VERSION >= 2021
#endif // __HLSL_VECTOR_UTILS

View File

@ -0,0 +1,275 @@
// Copyright (c) 2024 Google LLC
//
// This file is licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef _HLSL_VK_KHR_COOPERATIVE_MATRIX_H_
#define _HLSL_VK_KHR_COOPERATIVE_MATRIX_H_
#if __SPIRV_MAJOR_VERSION__ == 1 && __SPIRV_MINOR_VERSION__ < 6
#error "CooperativeMatrix requires a minimum of SPIR-V 1.6"
#endif
#include <vk/spirv.h>
namespace vk {
namespace khr {
// The base cooperative matrix class. The template arguments correspond to the
// operands in the OpTypeCooperativeMatrixKHR instruction.
template <typename ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
class CooperativeMatrix {
template <class NewComponentType>
CooperativeMatrix<NewComponentType, scope, rows, columns, use> cast();
// Apply OpSNegate or OFNegate, depending on ComponentType, in a element by
// element manner.
CooperativeMatrix negate();
// Apply OpIAdd or OFAdd, depending on ComponentType, in a element by element
// manner.
CooperativeMatrix operator+(CooperativeMatrix other);
// Apply OpISub or OFSub, depending on ComponentType, in a element by element
// manner.
CooperativeMatrix operator-(CooperativeMatrix other);
// Apply OpIMul or OFMul, depending on ComponentType, in a element by element
// manner.
CooperativeMatrix operator*(CooperativeMatrix other);
// Apply OpSDiv, OpUDiv or OFDiv, depending on ComponentType, in a element by
// element manner.
CooperativeMatrix operator/(CooperativeMatrix other);
// Apply OpMatrixTimesScalar in a element by element manner.
CooperativeMatrix operator*(ComponentType scalar);
// Store the cooperative matrix using OpCooperativeMatrixStoreKHR to
// data using the given memory layout, stride, and memory access operands.
// `NonPrivatePointer` and `MakePointerAvailable` with the workgroup scope
// will be added to the memory access operands to make the memory coherent.
//
// This function uses a SPIR-V pointer because HLSL does not allow groupshared
// memory object to be passed by reference. The pointer is a hack to get
// around that.
//
// The layout and stride will be passed to the SPIR-V instruction as is. The
// precise meaning can be found in the specification for
// SPV_KHR_cooperative_matrix.
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
class Type>
void Store(WorkgroupSpirvPointer<Type> data, uint32_t stride);
// Same as above, but uses MemoryAccessMaskNone for the memory access
// operands.
template <CooperativeMatrixLayout layout, class Type>
void Store(WorkgroupSpirvPointer<Type> data, uint32_t stride) {
Store<MemoryAccessMaskNone, layout>(data, stride);
}
// Store the cooperative matrix using OpCooperativeMatrixStoreKHR to
// data[index] using the given memory layout, stride, and memory access
// operands. The layout and stride will be passed to the SPIR-V instruction as
// is. The precise meaning can be found in the specification for
// SPV_KHR_cooperative_matrix.
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
class Type>
void Store(RWStructuredBuffer<Type> data, uint32_t index, uint32_t stride);
// Same as above, but uses MemoryAccessMaskNone for the memory access
// operands.
template <CooperativeMatrixLayout layout, class Type>
void Store(RWStructuredBuffer<Type> data, uint32_t index, uint32_t stride) {
Store<MemoryAccessMaskNone, layout>(data, index, stride);
}
// Store the cooperative matrix using OpCooperativeMatrixStoreKHR to
// data[index] using the given memory layout, stride, and memory access
// operands. `NonPrivatePointer` and `MakePointerAvailable` with the
// QueueFamily scope will be added to the memory access operands to make the
// memory coherent.
//
// The layout and stride will be passed to the SPIR-V instruction as is. The
// precise meaning can be found in the specification for
// SPV_KHR_cooperative_matrix.
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
class Type>
void CoherentStore(globallycoherent RWStructuredBuffer<Type> data,
uint32_t index, uint32_t stride);
// Same as above, but uses MemoryAccessMaskNone for the memory access operands
// template argument.
template <CooperativeMatrixLayout layout, class Type>
void CoherentStore(globallycoherent RWStructuredBuffer<Type> data,
uint32_t index, uint32_t stride) {
CoherentStore<MemoryAccessMaskNone, layout>(data, index, stride);
}
// Loads a cooperative matrix using OpCooperativeMatrixLoadKHR from
// data using the given memory layout, stride, and memory access operands.
// `NonPrivatePointer` and `MakePointerVisible` with the workgroup scope
// will be added to the memory access operands to make the memory coherent.
//
// This function uses a SPIR-V pointer because HLSL does not allow groupshared
// memory object to be passed by reference. The pointer is a hack to get
// around that.
//
// The layout and stride will be passed to the SPIR-V instruction as is. The
// precise meaning can be found in the specification for
// SPV_KHR_cooperative_matrix.
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
class Type>
static CooperativeMatrix Load(WorkgroupSpirvPointer<Type> data,
uint32_t stride);
// Same as above, but uses MemoryAccessMaskNone for the memory access
// operands.
template <CooperativeMatrixLayout layout, class Type>
static CooperativeMatrix Load(WorkgroupSpirvPointer<Type> data,
uint32_t stride) {
return Load<MemoryAccessMaskNone, layout>(data, stride);
}
// Loads a cooperative matrix using OpCooperativeMatrixLoadKHR from
// data[index] using the given memory layout, stride, and memory access
// operands.
//
// The layout and stride will be passed to the SPIR-V instruction as is. The
// precise meaning can be found in the specification for
// SPV_KHR_cooperative_matrix.
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
class Type>
static CooperativeMatrix Load(RWStructuredBuffer<Type> data, uint32_t index,
uint32_t stride);
// Same as above, but uses MemoryAccessMaskNone for the memory access
// operands.
template <CooperativeMatrixLayout layout, class Type>
static CooperativeMatrix Load(RWStructuredBuffer<Type> data, uint32_t index,
uint32_t stride) {
return Load<MemoryAccessMaskNone, layout>(data, index, stride);
}
// Loads a cooperative matrix using OpCooperativeMatrixLoadKHR from
// data[index] using the given memory layout, stride, and memory access
// operands. `NonPrivatePointer` and `MakePointerVisible` with the QueueFamily
// scope will be added to the memory access operands to make the memory
// coherent.
//
//
// The layout and stride will be passed to the SPIR-V instruction as is. The
// precise meaning can be found in the specification for
// SPV_KHR_cooperative_matrix.
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
class Type>
static CooperativeMatrix
CoherentLoad(globallycoherent RWStructuredBuffer<Type> data, uint32_t index,
uint32_t stride);
// Same as above, but uses MemoryAccessMaskNone for the memory access operands
// template argument.
template <CooperativeMatrixLayout layout, class Type>
static CooperativeMatrix
CoherentLoad(globallycoherent RWStructuredBuffer<Type> data, uint32_t index,
uint32_t stride) {
return CoherentLoad<MemoryAccessMaskNone, layout>(data, index, stride);
}
// Loads a cooperative matrix using OpCooperativeMatrixLoadKHR from
// data[index] using the given memory layout, stride, and memory access
// operands. No memory access bits are added to the operands. Since the memory
// is readonly, there should be no need.
//
// The layout and stride will be passed to the SPIR-V instruction as is. The
// precise meaning can be found in the specification for
// SPV_KHR_cooperative_matrix.
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
class Type>
static CooperativeMatrix Load(StructuredBuffer<Type> data, uint32_t index,
uint32_t stride);
// Same as above, but uses MemoryAccessMaskNone for the memory access
// operands.
template <CooperativeMatrixLayout layout, class Type>
static CooperativeMatrix Load(StructuredBuffer<Type> data, uint32_t index,
uint32_t stride) {
return Load<MemoryAccessMaskNone, layout>(data, index, stride);
}
// Constructs a cooperative matrix with all values initialized to v. Note that
// all threads in scope must have the same value for v.
static CooperativeMatrix Splat(ComponentType v);
// Returns the result of OpCooperativeMatrixLengthKHR on the current type.
static uint32_t GetLength();
// Functions to access the elements of the cooperative matrix. The index must
// be less than GetLength().
void Set(ComponentType value, uint32_t index);
ComponentType Get(uint32_t index);
static const bool hasSignedIntegerComponentType =
(ComponentType(0) - ComponentType(1) < ComponentType(0));
// clang-format off
using SpirvMatrixType = vk::SpirvOpaqueType<
/* OpTypeCooperativeMatrixKHR */ 4456, ComponentType,
vk::integral_constant<uint, scope>, vk::integral_constant<uint, rows>,
vk::integral_constant<uint, columns>, vk::integral_constant<uint, use> >;
[[vk::ext_extension("SPV_KHR_cooperative_matrix")]]
[[vk::ext_capability(/* CooperativeMatrixKHRCapability */ 6022)]]
[[vk::ext_capability(/* VulkanMemoryModel */ 5345)]]
SpirvMatrixType _matrix;
// clang-format on
};
// Cooperative matrix that can be used in the "a" position of a multiply add
// instruction (r = (a * b) + c).
template <typename ComponentType, Scope scope, uint rows, uint columns>
using CooperativeMatrixA =
CooperativeMatrix<ComponentType, scope, rows, columns,
CooperativeMatrixUseMatrixAKHR>;
// Cooperative matrix that can be used in the "b" position of a multiply add
// instruction (r = (a * b) + c).
template <typename ComponentType, Scope scope, uint rows, uint columns>
using CooperativeMatrixB =
CooperativeMatrix<ComponentType, scope, rows, columns,
CooperativeMatrixUseMatrixBKHR>;
// Cooperative matrix that can be used in the "r" and "c" position of a multiply
// add instruction (r = (a * b) + c).
template <typename ComponentType, Scope scope, uint rows, uint columns>
using CooperativeMatrixAccumulator =
CooperativeMatrix<ComponentType, scope, rows, columns,
CooperativeMatrixUseMatrixAccumulatorKHR>;
// Returns the result of OpCooperativeMatrixMulAddKHR when applied to a, b, and
// c. The cooperative matrix operands are inferred, with the
// SaturatingAccumulationKHR bit not set.
template <typename ComponentType, Scope scope, uint rows, uint columns, uint K>
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns>
cooperativeMatrixMultiplyAdd(
CooperativeMatrixA<ComponentType, scope, rows, K> a,
CooperativeMatrixB<ComponentType, scope, K, columns> b,
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns> c);
// Returns the result of OpCooperativeMatrixMulAddKHR when applied to a, b, and
// c. The cooperative matrix operands are inferred, with the
// SaturatingAccumulationKHR bit set.
template <typename ComponentType, Scope scope, uint rows, uint columns, uint K>
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns>
cooperativeMatrixSaturatingMultiplyAdd(
CooperativeMatrixA<ComponentType, scope, rows, K> a,
CooperativeMatrixB<ComponentType, scope, K, columns> b,
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns> c);
} // namespace khr
} // namespace vk
#include <vk/khr/cooperative_matrix.impl>
#endif // _HLSL_VK_KHR_COOPERATIVE_MATRIX_H_

View File

@ -0,0 +1,377 @@
// Copyright (c) 2024 Google LLC
//
// This file is licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include <vk/opcode_selector.h>
template <typename ResultType, typename ComponentType>
[[vk::ext_instruction(/* OpMatrixTimesScalar */ 143)]] ResultType
__builtin_spv_MatrixTimesScalar(ResultType a, ComponentType b);
template <typename ComponentType, vk::Scope scope, uint rows, uint columns,
vk::CooperativeMatrixUse use>
[[vk::ext_instruction(/* OpCompositeExtract */ 81)]] ComponentType
__builtin_spv_ExtractFromCooperativeMatrix(
typename vk::khr::CooperativeMatrix<ComponentType, scope, rows, columns,
use>::SpirvMatrixType matrix,
uint32_t index);
template <typename CoopMatrixType, typename ComponentType>
[[vk::ext_instruction(/* OpCompositeConstruct */ 80)]] CoopMatrixType
__builtin_spv_ConstructCooperativeMatrix(ComponentType value);
template <class ResultPointerType, class BaseType>
[[vk::ext_instruction(/* OpAccessChain */ 65)]] ResultPointerType
__builtin_spv_AccessChain([[vk::ext_reference]] BaseType base, uint32_t index);
template <class ObjectType, class PointerType>
[[vk::ext_instruction(/* OpLoad */ 61)]] ObjectType
__builtin_spv_LoadPointer(PointerType base);
template <class PointerType, class ObjectType>
[[vk::ext_instruction(/* OpLoad */ 62)]] void
__builtin_spv_StorePointer(PointerType base, ObjectType object);
template <typename ComponentType, vk::Scope scope, uint rows, uint columns,
vk::CooperativeMatrixUse use>
[[vk::ext_instruction(/* OpCompositeInsert */ 82)]]
typename vk::khr::CooperativeMatrix<ComponentType, scope, rows, columns,
use>::SpirvMatrixType
__builtin_spv_InsertIntoCooperativeMatrix(
ComponentType value,
typename vk::khr::CooperativeMatrix<ComponentType, scope, rows, columns,
use>::SpirvMatrixType matrix,
uint32_t index);
// Define the load and store instructions
template <typename ResultType, typename PointerType>
[[vk::ext_instruction(/* OpCooperativeMatrixLoadKHR */ 4457)]] ResultType
__builtin_spv_CooperativeMatrixLoadKHR(
[[vk::ext_reference]] PointerType pointer,
vk::CooperativeMatrixLayout memory_layout, uint stride,
[[vk::ext_literal]] uint32_t memory_operand);
template <typename ResultType, typename PointerType>
[[vk::ext_instruction(/* OpCooperativeMatrixLoadKHR */ 4457)]] ResultType
__builtin_spv_CooperativeMatrixLoadKHR(
[[vk::ext_reference]] PointerType pointer,
vk::CooperativeMatrixLayout memory_layout, uint stride,
[[vk::ext_literal]] uint32_t memory_operand, vk::Scope scope);
template <typename ResultType, typename PointerType>
[[vk::ext_instruction(/* OpCooperativeMatrixLoadKHR */ 4457)]] ResultType
__builtin_spv_CooperativeMatrixWorkgroupLoadKHR(
vk::WorkgroupSpirvPointer<PointerType> pointer,
vk::CooperativeMatrixLayout memory_layout, uint stride,
[[vk::ext_literal]] uint32_t memory_operand, vk::Scope scope);
template <typename ObjectType, typename PointerType>
[[vk::ext_instruction(/* OpCooperativeMatrixStoreKHR */ 4458)]] void
__builtin_spv_CooperativeMatrixStoreKHR(
[[vk::ext_reference]] PointerType pointer, ObjectType object,
vk::CooperativeMatrixLayout memory_layout, uint stride,
[[vk::ext_literal]] uint32_t memory_operand, vk::Scope scope);
template <typename ObjectType, typename PointerType>
[[vk::ext_instruction(/* OpCooperativeMatrixStoreKHR */ 4458)]] void
__builtin_spv_CooperativeMatrixStoreKHR(
[[vk::ext_reference]] PointerType pointer, ObjectType object,
vk::CooperativeMatrixLayout memory_layout, uint stride,
[[vk::ext_literal]] uint32_t memory_operand);
template <typename ObjectType, typename PointerType>
[[vk::ext_instruction(/* OpCooperativeMatrixStoreKHR */ 4458)]] void
__builtin_spv_CooperativeMatrixWorkgroupStoreKHR(
vk::WorkgroupSpirvPointer<PointerType> pointer, ObjectType object,
vk::CooperativeMatrixLayout memory_layout, uint stride,
[[vk::ext_literal]] uint32_t memory_operand, vk::Scope scope);
// We cannot define `OpCooperativeMatrixLengthKHR` using ext_instruction because
// one of the operands is a type id. This builtin will have specific code in the
// compiler to expand it.
template <class MatrixType> uint __builtin_spv_CooperativeMatrixLengthKHR();
// Arithmetic Instructions
template <typename ResultType, typename MatrixTypeA, typename MatrixTypeB,
typename MatrixTypeC>
[[vk::ext_instruction(/* OpCooperativeMatrixMulAddKHR */ 4459)]] ResultType
__builtin_spv_CooperativeMatrixMulAddKHR(MatrixTypeA a, MatrixTypeB b,
MatrixTypeC c,
[[vk::ext_literal]] int operands);
namespace vk {
namespace khr {
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
template <class NewComponentType>
CooperativeMatrix<NewComponentType, scope, rows, columns, use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>::cast() {
using ResultType =
CooperativeMatrix<NewComponentType, scope, rows, columns, use>;
ResultType result;
result._matrix = util::ConversionSelector<ComponentType, NewComponentType>::
template Convert<typename ResultType::SpirvMatrixType>(_matrix);
return result;
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>::negate() {
CooperativeMatrix result;
result._matrix = util::ArithmeticSelector<ComponentType>::Negate(_matrix);
return result;
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>::operator+(
CooperativeMatrix other) {
CooperativeMatrix result;
result._matrix =
util::ArithmeticSelector<ComponentType>::Add(_matrix, other._matrix);
return result;
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>::operator-(
CooperativeMatrix other) {
CooperativeMatrix result;
result._matrix =
util::ArithmeticSelector<ComponentType>::Sub(_matrix, other._matrix);
return result;
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>::operator*(
CooperativeMatrix other) {
CooperativeMatrix result;
result._matrix =
util::ArithmeticSelector<ComponentType>::Mul(_matrix, other._matrix);
return result;
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>::operator/(
CooperativeMatrix other) {
CooperativeMatrix result;
result._matrix =
util::ArithmeticSelector<ComponentType>::Div(_matrix, other._matrix);
return result;
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>::operator*(
ComponentType scalar) {
CooperativeMatrix result;
result._matrix = __builtin_spv_MatrixTimesScalar(_matrix, scalar);
return result;
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
class Type>
void CooperativeMatrix<ComponentType, scope, rows, columns, use>::Store(
WorkgroupSpirvPointer<Type> data, uint32_t stride) {
__builtin_spv_CooperativeMatrixWorkgroupStoreKHR(
data, _matrix, layout, stride,
memoryAccessOperands | MemoryAccessNonPrivatePointerMask |
MemoryAccessMakePointerAvailableMask,
ScopeWorkgroup);
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
class Type>
void CooperativeMatrix<ComponentType, scope, rows, columns, use>::Store(
RWStructuredBuffer<Type> data, uint32_t index, uint32_t stride) {
__builtin_spv_CooperativeMatrixStoreKHR(data[index], _matrix, layout, stride,
memoryAccessOperands);
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
class Type>
void CooperativeMatrix<ComponentType, scope, rows, columns, use>::CoherentStore(
globallycoherent RWStructuredBuffer<Type> data, uint32_t index,
uint32_t stride) {
__builtin_spv_CooperativeMatrixStoreKHR(
data[index], _matrix, layout, stride,
memoryAccessOperands | MemoryAccessNonPrivatePointerMask |
MemoryAccessMakePointerAvailableMask,
ScopeQueueFamily);
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
class Type>
CooperativeMatrix<ComponentType, scope, rows, columns, use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>::Load(
vk::WorkgroupSpirvPointer<Type> buffer, uint32_t stride) {
CooperativeMatrix result;
result._matrix =
__builtin_spv_CooperativeMatrixWorkgroupLoadKHR<SpirvMatrixType>(
buffer, layout, stride,
memoryAccessOperands | MemoryAccessNonPrivatePointerMask |
MemoryAccessMakePointerVisibleMask,
ScopeWorkgroup);
return result;
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
class Type>
CooperativeMatrix<ComponentType, scope, rows, columns, use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>::Load(
RWStructuredBuffer<Type> buffer, uint32_t index, uint32_t stride) {
CooperativeMatrix result;
result._matrix = __builtin_spv_CooperativeMatrixLoadKHR<SpirvMatrixType>(
buffer[index], layout, stride, memoryAccessOperands);
return result;
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
class Type>
CooperativeMatrix<ComponentType, scope, rows, columns, use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>::CoherentLoad(
RWStructuredBuffer<Type> buffer, uint32_t index, uint32_t stride) {
CooperativeMatrix result;
result._matrix = __builtin_spv_CooperativeMatrixLoadKHR<SpirvMatrixType>(
buffer[index], layout, stride,
memoryAccessOperands | MemoryAccessNonPrivatePointerMask |
MemoryAccessMakePointerVisibleMask,
ScopeQueueFamily);
return result;
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
template <uint32_t memoryAccessOperands, CooperativeMatrixLayout layout,
class Type>
CooperativeMatrix<ComponentType, scope, rows, columns, use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>::Load(
StructuredBuffer<Type> buffer, uint32_t index, uint32_t stride) {
CooperativeMatrix result;
result._matrix = __builtin_spv_CooperativeMatrixLoadKHR<SpirvMatrixType>(
buffer[index], layout, stride, MemoryAccessMaskNone);
return result;
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>
CooperativeMatrix<ComponentType, scope, rows, columns, use>::Splat(
ComponentType v) {
CooperativeMatrix result;
result._matrix = __builtin_spv_ConstructCooperativeMatrix<SpirvMatrixType>(v);
return result;
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
uint CooperativeMatrix<ComponentType, scope, rows, columns, use>::GetLength() {
return __builtin_spv_CooperativeMatrixLengthKHR<SpirvMatrixType>();
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
ComponentType CooperativeMatrix<ComponentType, scope, rows, columns, use>::Get(
uint32_t index) {
// clang-format off
using ComponentPtr = vk::SpirvOpaqueType<
/* OpTypePointer */ 32,
/* function storage class */ vk::Literal<vk::integral_constant<uint, 7> >,
ComponentType>;
// clang-format on
ComponentPtr ptr = __builtin_spv_AccessChain<ComponentPtr>(_matrix, index);
return __builtin_spv_LoadPointer<ComponentType>(ptr);
}
template <class ComponentType, Scope scope, uint rows, uint columns,
CooperativeMatrixUse use>
void CooperativeMatrix<ComponentType, scope, rows, columns, use>::Set(
ComponentType value, uint32_t index) {
// clang-format off
using ComponentPtr = vk::SpirvOpaqueType<
/* OpTypePointer */ 32,
/* function storage class */ vk::Literal<vk::integral_constant<uint, 7> >,
ComponentType>;
// clang-format on
ComponentPtr ptr = __builtin_spv_AccessChain<ComponentPtr>(_matrix, index);
return __builtin_spv_StorePointer(ptr, value);
}
template <typename ComponentType, Scope scope, uint rows, uint columns, uint K>
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns>
cooperativeMatrixMultiplyAdd(
CooperativeMatrixA<ComponentType, scope, rows, K> a,
CooperativeMatrixB<ComponentType, scope, K, columns> b,
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns> c) {
const vk::CooperativeMatrixOperandsMask allSignedComponents =
vk::CooperativeMatrixOperandsMatrixASignedComponentsKHRMask |
vk::CooperativeMatrixOperandsMatrixBSignedComponentsKHRMask |
vk::CooperativeMatrixOperandsMatrixCSignedComponentsKHRMask |
vk::CooperativeMatrixOperandsMatrixResultSignedComponentsKHRMask;
const vk::CooperativeMatrixOperandsMask operands =
(vk::CooperativeMatrixOperandsMask)(
a.hasSignedIntegerComponentType
? allSignedComponents
: vk::CooperativeMatrixOperandsMaskNone);
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns> result;
result._matrix = __builtin_spv_CooperativeMatrixMulAddKHR<
typename CooperativeMatrixAccumulator<ComponentType, scope, rows,
columns>::SpirvMatrixType>(
a._matrix, b._matrix, c._matrix, operands);
return result;
}
template <typename ComponentType, Scope scope, uint rows, uint columns, uint K>
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns>
cooperativeMatrixSaturatingMultiplyAdd(
CooperativeMatrixA<ComponentType, scope, rows, K> a,
CooperativeMatrixB<ComponentType, scope, K, columns> b,
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns> c) {
const vk::CooperativeMatrixOperandsMask allSignedComponents =
vk::CooperativeMatrixOperandsMatrixASignedComponentsKHRMask |
vk::CooperativeMatrixOperandsMatrixBSignedComponentsKHRMask |
vk::CooperativeMatrixOperandsMatrixCSignedComponentsKHRMask |
vk::CooperativeMatrixOperandsMatrixResultSignedComponentsKHRMask |
vk::CooperativeMatrixOperandsSaturatingAccumulationKHRMask;
const vk::CooperativeMatrixOperandsMask operands =
(vk::CooperativeMatrixOperandsMask)(
a.hasSignedIntegerComponentType
? allSignedComponents
: vk::CooperativeMatrixOperandsSaturatingAccumulationKHRMask);
CooperativeMatrixAccumulator<ComponentType, scope, rows, columns> result;
result._matrix = __builtin_spv_CooperativeMatrixMulAddKHR<
typename CooperativeMatrixAccumulator<ComponentType, scope, rows,
columns>::SpirvMatrixType>(
a._matrix, b._matrix, c._matrix, operands);
return result;
}
} // namespace khr
} // namespace vk

227
vendor/hlsl-headers/vk/opcode_selector.h vendored Normal file
View File

@ -0,0 +1,227 @@
// Copyright (c) 2024 Google LLC
//
// This file is licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef _HLSL_VK_KHR_OPCODE_SELECTOR_H_
#define _HLSL_VK_KHR_OPCODE_SELECTOR_H_
#define DECLARE_UNARY_OP(name, opcode) \
template <typename ResultType> \
[[vk::ext_instruction(opcode)]] ResultType __builtin_spv_##name( \
ResultType a)
DECLARE_UNARY_OP(CopyObject, 83);
DECLARE_UNARY_OP(SNegate, 126);
DECLARE_UNARY_OP(FNegate, 127);
#define DECLARE_CONVERSION_OP(name, opcode) \
template <typename ResultType, typename OperandType> \
[[vk::ext_instruction(opcode)]] ResultType __builtin_spv_##name( \
OperandType a)
DECLARE_CONVERSION_OP(ConvertFtoU, 109);
DECLARE_CONVERSION_OP(ConvertFtoS, 110);
DECLARE_CONVERSION_OP(ConvertSToF, 111);
DECLARE_CONVERSION_OP(ConvertUToF, 112);
DECLARE_CONVERSION_OP(UConvert, 113);
DECLARE_CONVERSION_OP(SConvert, 114);
DECLARE_CONVERSION_OP(FConvert, 115);
DECLARE_CONVERSION_OP(Bitcast, 124);
#undef DECLARY_UNARY_OP
#define DECLARE_BINOP(name, opcode) \
template <typename ResultType> \
[[vk::ext_instruction(opcode)]] ResultType __builtin_spv_##name( \
ResultType a, ResultType b)
DECLARE_BINOP(IAdd, 128);
DECLARE_BINOP(FAdd, 129);
DECLARE_BINOP(ISub, 130);
DECLARE_BINOP(FSub, 131);
DECLARE_BINOP(IMul, 132);
DECLARE_BINOP(FMul, 133);
DECLARE_BINOP(UDiv, 134);
DECLARE_BINOP(SDiv, 135);
DECLARE_BINOP(FDiv, 136);
#undef DECLARE_BINOP
namespace vk {
namespace util {
template <class ComponentType> class ArithmeticSelector;
#define ARITHMETIC_SELECTOR(BaseType, OpNegate, OpAdd, OpSub, OpMul, OpDiv, \
SIGNED_INTEGER_TYPE) \
template <> class ArithmeticSelector<BaseType> { \
template <class T> static T Negate(T a) { return OpNegate(a); } \
template <class T> static T Add(T a, T b) { return OpAdd(a, b); } \
template <class T> static T Sub(T a, T b) { return OpSub(a, b); } \
template <class T> static T Mul(T a, T b) { return OpMul(a, b); } \
template <class T> static T Div(T a, T b) { return OpDiv(a, b); } \
};
ARITHMETIC_SELECTOR(half, __builtin_spv_FNegate, __builtin_spv_FAdd,
__builtin_spv_FSub, __builtin_spv_FMul, __builtin_spv_FDiv,
false);
ARITHMETIC_SELECTOR(float, __builtin_spv_FNegate, __builtin_spv_FAdd,
__builtin_spv_FSub, __builtin_spv_FMul, __builtin_spv_FDiv,
false);
ARITHMETIC_SELECTOR(double, __builtin_spv_FNegate, __builtin_spv_FAdd,
__builtin_spv_FSub, __builtin_spv_FMul, __builtin_spv_FDiv,
false);
#if __HLSL_ENABLE_16_BIT
ARITHMETIC_SELECTOR(int16_t, __builtin_spv_SNegate, __builtin_spv_IAdd,
__builtin_spv_ISub, __builtin_spv_IMul, __builtin_spv_SDiv,
true);
ARITHMETIC_SELECTOR(uint16_t, __builtin_spv_SNegate, __builtin_spv_IAdd,
__builtin_spv_ISub, __builtin_spv_IMul, __builtin_spv_UDiv,
false);
#endif // __HLSL_ENABLE_16_BIT
ARITHMETIC_SELECTOR(int32_t, __builtin_spv_SNegate, __builtin_spv_IAdd,
__builtin_spv_ISub, __builtin_spv_IMul, __builtin_spv_SDiv,
true);
ARITHMETIC_SELECTOR(int64_t, __builtin_spv_SNegate, __builtin_spv_IAdd,
__builtin_spv_ISub, __builtin_spv_IMul, __builtin_spv_SDiv,
true);
ARITHMETIC_SELECTOR(uint32_t, __builtin_spv_SNegate, __builtin_spv_IAdd,
__builtin_spv_ISub, __builtin_spv_IMul, __builtin_spv_UDiv,
false);
ARITHMETIC_SELECTOR(uint64_t, __builtin_spv_SNegate, __builtin_spv_IAdd,
__builtin_spv_ISub, __builtin_spv_IMul, __builtin_spv_UDiv,
false);
// The conversion selector is will be used to convert one type to another
// using the SPIR-V conversion instructions. See
// https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#_conversion_instructions.
// SourceType and TargetType must be integer or floating point scalar type.
// ConversionSelector::Convert converts an object of type S to an object of type
// T. S must be SourceType, a vector of SourceType, or a cooperative matrix of
// SourceType. T must be TargetType, a vector of TargetType, or a cooperative
// matrix of TargetType. T must have the same number of components as S. T is a
// cooperative matrix if and only if S is a cooperative matrix.
template <class SourceType, class TargetType> class ConversionSelector;
#define CONVERSION_SELECTOR(SourceType, TargetType, OpConvert) \
template <> class ConversionSelector<SourceType, TargetType> { \
template <class T, class S> static T Convert(S a) { \
return OpConvert<T>(a); \
} \
};
#if __HLSL_ENABLE_16_BIT
CONVERSION_SELECTOR(uint16_t, uint16_t, __builtin_spv_CopyObject);
CONVERSION_SELECTOR(uint16_t, int16_t, __builtin_spv_Bitcast);
CONVERSION_SELECTOR(uint16_t, uint32_t, __builtin_spv_UConvert);
CONVERSION_SELECTOR(uint16_t, int32_t, __builtin_spv_SConvert);
CONVERSION_SELECTOR(uint16_t, uint64_t, __builtin_spv_UConvert);
CONVERSION_SELECTOR(uint16_t, int64_t, __builtin_spv_SConvert);
CONVERSION_SELECTOR(uint16_t, half, __builtin_spv_ConvertUToF);
CONVERSION_SELECTOR(uint16_t, float, __builtin_spv_ConvertUToF);
CONVERSION_SELECTOR(uint16_t, double, __builtin_spv_ConvertUToF);
CONVERSION_SELECTOR(int16_t, uint16_t, __builtin_spv_Bitcast);
CONVERSION_SELECTOR(int16_t, int16_t, __builtin_spv_CopyObject);
CONVERSION_SELECTOR(int16_t, uint32_t, __builtin_spv_UConvert);
CONVERSION_SELECTOR(int16_t, int32_t, __builtin_spv_SConvert);
CONVERSION_SELECTOR(int16_t, uint64_t, __builtin_spv_UConvert);
CONVERSION_SELECTOR(int16_t, int64_t, __builtin_spv_SConvert);
CONVERSION_SELECTOR(int16_t, half, __builtin_spv_ConvertSToF);
CONVERSION_SELECTOR(int16_t, float, __builtin_spv_ConvertSToF);
CONVERSION_SELECTOR(int16_t, double, __builtin_spv_ConvertSToF);
CONVERSION_SELECTOR(uint32_t, uint16_t, __builtin_spv_UConvert);
CONVERSION_SELECTOR(uint32_t, int16_t, __builtin_spv_SConvert);
CONVERSION_SELECTOR(int32_t, uint16_t, __builtin_spv_UConvert);
CONVERSION_SELECTOR(int32_t, int16_t, __builtin_spv_SConvert);
CONVERSION_SELECTOR(uint64_t, uint16_t, __builtin_spv_UConvert);
CONVERSION_SELECTOR(uint64_t, int16_t, __builtin_spv_SConvert);
CONVERSION_SELECTOR(int64_t, uint16_t, __builtin_spv_UConvert);
CONVERSION_SELECTOR(int64_t, int16_t, __builtin_spv_SConvert);
CONVERSION_SELECTOR(half, uint16_t, __builtin_spv_ConvertFtoU);
CONVERSION_SELECTOR(half, int16_t, __builtin_spv_ConvertFtoS);
CONVERSION_SELECTOR(float, uint16_t, __builtin_spv_ConvertFtoU);
CONVERSION_SELECTOR(float, int16_t, __builtin_spv_ConvertFtoS);
CONVERSION_SELECTOR(double, uint16_t, __builtin_spv_ConvertFtoU);
CONVERSION_SELECTOR(double, int16_t, __builtin_spv_ConvertFtoS);
#endif
CONVERSION_SELECTOR(uint32_t, uint32_t, __builtin_spv_CopyObject);
CONVERSION_SELECTOR(uint32_t, int32_t, __builtin_spv_Bitcast);
CONVERSION_SELECTOR(uint32_t, uint64_t, __builtin_spv_UConvert);
CONVERSION_SELECTOR(uint32_t, int64_t, __builtin_spv_SConvert);
CONVERSION_SELECTOR(uint32_t, half, __builtin_spv_ConvertUToF);
CONVERSION_SELECTOR(uint32_t, float, __builtin_spv_ConvertUToF);
CONVERSION_SELECTOR(uint32_t, double, __builtin_spv_ConvertUToF);
CONVERSION_SELECTOR(int32_t, uint32_t, __builtin_spv_Bitcast);
CONVERSION_SELECTOR(int32_t, int32_t, __builtin_spv_CopyObject);
CONVERSION_SELECTOR(int32_t, uint64_t, __builtin_spv_UConvert);
CONVERSION_SELECTOR(int32_t, int64_t, __builtin_spv_SConvert);
CONVERSION_SELECTOR(int32_t, half, __builtin_spv_ConvertSToF);
CONVERSION_SELECTOR(int32_t, float, __builtin_spv_ConvertSToF);
CONVERSION_SELECTOR(int32_t, double, __builtin_spv_ConvertSToF);
CONVERSION_SELECTOR(uint64_t, uint32_t, __builtin_spv_UConvert);
CONVERSION_SELECTOR(uint64_t, int32_t, __builtin_spv_SConvert);
CONVERSION_SELECTOR(uint64_t, uint64_t, __builtin_spv_Bitcast);
CONVERSION_SELECTOR(uint64_t, int64_t, __builtin_spv_CopyObject);
CONVERSION_SELECTOR(uint64_t, half, __builtin_spv_ConvertUToF);
CONVERSION_SELECTOR(uint64_t, float, __builtin_spv_ConvertUToF);
CONVERSION_SELECTOR(uint64_t, double, __builtin_spv_ConvertUToF);
CONVERSION_SELECTOR(int64_t, uint32_t, __builtin_spv_UConvert);
CONVERSION_SELECTOR(int64_t, int32_t, __builtin_spv_SConvert);
CONVERSION_SELECTOR(int64_t, uint64_t, __builtin_spv_Bitcast);
CONVERSION_SELECTOR(int64_t, int64_t, __builtin_spv_CopyObject);
CONVERSION_SELECTOR(int64_t, half, __builtin_spv_ConvertSToF);
CONVERSION_SELECTOR(int64_t, float, __builtin_spv_ConvertSToF);
CONVERSION_SELECTOR(int64_t, double, __builtin_spv_ConvertSToF);
CONVERSION_SELECTOR(half, uint32_t, __builtin_spv_ConvertFtoU);
CONVERSION_SELECTOR(half, int32_t, __builtin_spv_ConvertFtoS);
CONVERSION_SELECTOR(half, uint64_t, __builtin_spv_ConvertFtoU);
CONVERSION_SELECTOR(half, int64_t, __builtin_spv_ConvertFtoS);
CONVERSION_SELECTOR(half, half, __builtin_spv_CopyObject);
#if __HLSL_ENABLE_16_BIT
CONVERSION_SELECTOR(half, float, __builtin_spv_FConvert);
#else
CONVERSION_SELECTOR(half, float, __builtin_spv_CopyObject);
#endif
CONVERSION_SELECTOR(half, double, __builtin_spv_FConvert);
CONVERSION_SELECTOR(float, uint32_t, __builtin_spv_ConvertFtoU);
CONVERSION_SELECTOR(float, int32_t, __builtin_spv_ConvertFtoS);
CONVERSION_SELECTOR(float, uint64_t, __builtin_spv_ConvertFtoU);
CONVERSION_SELECTOR(float, int64_t, __builtin_spv_ConvertFtoS);
#if __HLSL_ENABLE_16_BIT
CONVERSION_SELECTOR(float, half, __builtin_spv_FConvert);
#else
CONVERSION_SELECTOR(float, half, __builtin_spv_CopyObject);
#endif
CONVERSION_SELECTOR(float, float, __builtin_spv_CopyObject);
CONVERSION_SELECTOR(float, double, __builtin_spv_FConvert);
CONVERSION_SELECTOR(double, uint32_t, __builtin_spv_ConvertFtoU);
CONVERSION_SELECTOR(double, int32_t, __builtin_spv_ConvertFtoS);
CONVERSION_SELECTOR(double, uint64_t, __builtin_spv_ConvertFtoU);
CONVERSION_SELECTOR(double, int64_t, __builtin_spv_ConvertFtoS);
CONVERSION_SELECTOR(double, half, __builtin_spv_FConvert);
CONVERSION_SELECTOR(double, float, __builtin_spv_FConvert);
CONVERSION_SELECTOR(double, double, __builtin_spv_CopyObject);
}; // namespace util
} // namespace vk
#endif // _HLSL_VK_KHR_OPCODE_SELECTOR_H_

85
vendor/hlsl-headers/vk/spirv.h vendored Normal file
View File

@ -0,0 +1,85 @@
// Copyright (c) 2024 Google LLC
//
// This file is licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef _HLSL_VK_SPIRV_H_
#define _HLSL_VK_SPIRV_H_
namespace vk {
enum CooperativeMatrixUse {
CooperativeMatrixUseMatrixAKHR = 0,
CooperativeMatrixUseMatrixBKHR = 1,
CooperativeMatrixUseMatrixAccumulatorKHR = 2,
CooperativeMatrixUseMax = 0x7fffffff,
};
enum CooperativeMatrixLayout {
CooperativeMatrixLayoutRowMajorKHR = 0,
CooperativeMatrixLayoutColumnMajorKHR = 1,
CooperativeMatrixLayoutRowBlockedInterleavedARM = 4202,
CooperativeMatrixLayoutColumnBlockedInterleavedARM = 4203,
CooperativeMatrixLayoutMax = 0x7fffffff,
};
enum CooperativeMatrixOperandsMask {
CooperativeMatrixOperandsMaskNone = 0,
CooperativeMatrixOperandsMatrixASignedComponentsKHRMask = 0x00000001,
CooperativeMatrixOperandsMatrixBSignedComponentsKHRMask = 0x00000002,
CooperativeMatrixOperandsMatrixCSignedComponentsKHRMask = 0x00000004,
CooperativeMatrixOperandsMatrixResultSignedComponentsKHRMask = 0x00000008,
CooperativeMatrixOperandsSaturatingAccumulationKHRMask = 0x00000010,
};
enum MemoryAccessMask {
MemoryAccessMaskNone = 0,
MemoryAccessVolatileMask = 0x00000001,
MemoryAccessAlignedMask = 0x00000002,
MemoryAccessNontemporalMask = 0x00000004,
MemoryAccessMakePointerAvailableMask = 0x00000008,
MemoryAccessMakePointerAvailableKHRMask = 0x00000008,
MemoryAccessMakePointerVisibleMask = 0x00000010,
MemoryAccessMakePointerVisibleKHRMask = 0x00000010,
MemoryAccessNonPrivatePointerMask = 0x00000020,
MemoryAccessNonPrivatePointerKHRMask = 0x00000020,
MemoryAccessAliasScopeINTELMaskMask = 0x00010000,
MemoryAccessNoAliasINTELMaskMask = 0x00020000,
};
enum Scope {
ScopeCrossDevice = 0,
ScopeDevice = 1,
ScopeWorkgroup = 2,
ScopeSubgroup = 3,
ScopeInvocation = 4,
ScopeQueueFamily = 5,
ScopeQueueFamilyKHR = 5,
ScopeShaderCallKHR = 6,
ScopeMax = 0x7fffffff,
};
enum StorageClass {
StorageClassWorkgroup = 4,
};
// An opaque type to represent a Spir-V pointer to the workgroup storage class.
// clang-format off
template <typename PointeeType>
using WorkgroupSpirvPointer = const vk::SpirvOpaqueType<
/* OpTypePointer */ 32,
vk::Literal<vk::integral_constant<uint, StorageClassWorkgroup> >,
PointeeType>;
// clang-format on
// Returns an opaque Spir-V pointer to v. The memory object v's storage class
// modifier must be groupshared. If the incorrect storage class is used, then
// there will be a validation error, and it will not show the correct
template <typename T>
[[vk::ext_instruction(/* OpCopyObject */ 83)]] WorkgroupSpirvPointer<T>
GetGroupSharedAddress([[vk::ext_reference]] T v);
} // namespace vk
#endif // _HLSL_VK_SPIRV_H_

25
vendor/hlsl_headers.zig vendored Normal file
View File

@ -0,0 +1,25 @@
//! HLSL standard headers that dxc compiles in and resolves for angled
//! includes when no file is found on disk (e.g. `#include <dx/linalg.h>`).
//! Copied from tools/clang/lib/Headers/hlsl; see hlsl-headers/LICENSE.txt.
pub const Header = struct { name: []const u8, text: []const u8 };
pub const headers = [_]Header{
.{ .name = "enable_if", .text = @embedFile("hlsl-headers/enable_if") },
.{ .name = "type_traits", .text = @embedFile("hlsl-headers/type_traits") },
.{ .name = "vector_utils", .text = @embedFile("hlsl-headers/vector_utils") },
.{ .name = "dx/linalg.h", .text = @embedFile("hlsl-headers/dx/linalg.h") },
.{ .name = "vk/opcode_selector.h", .text = @embedFile("hlsl-headers/vk/opcode_selector.h") },
.{ .name = "vk/spirv.h", .text = @embedFile("hlsl-headers/vk/spirv.h") },
.{ .name = "vk/khr/cooperative_matrix.h", .text = @embedFile("hlsl-headers/vk/khr/cooperative_matrix.h") },
.{ .name = "vk/khr/cooperative_matrix.impl", .text = @embedFile("hlsl-headers/vk/khr/cooperative_matrix.impl") },
};
pub fn find(name: []const u8) ?[]const u8 {
for (headers) |h| {
if (std.mem.eql(u8, h.name, name)) return h.text;
}
return null;
}
const std = @import("std");