Compare commits
No commits in common. "main" and "hillclimb" have entirely different histories.
27
README.md
27
README.md
|
|
@ -7,7 +7,7 @@
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
HLSL 2018 / 2021 → DXIL / SPIR-V · Written in Zig · No LLVM dependency
|
HLSL 2021 → DXIL / SPIR-V · Written in Zig · No LLVM dependency
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
|
|
@ -19,9 +19,9 @@
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
zdxc is an HLSL compiler written from scratch in Zig. It supports HLSL 2018
|
zdxc is an HLSL 2021 compiler written from scratch in Zig. It emits DXIL and
|
||||||
and 2021, emits DXIL and SPIR-V, supports DXC-style command lines, and
|
SPIR-V, supports DXC-style command lines, and provides a DXC-compatible COM
|
||||||
provides a DXC-compatible COM interface for existing engine integrations.
|
interface for existing engine integrations.
|
||||||
|
|
||||||
Use it as a development drop-in replacement for DXC, link its small C API directly,
|
Use it as a development drop-in replacement for DXC, link its small C API directly,
|
||||||
or import it as a Zig module. The compiler has no package dependencies and
|
or import it as a Zig module. The compiler has no package dependencies and
|
||||||
|
|
@ -29,7 +29,7 @@ signs its own DXIL, so there is no separate `dxil.dll` to ship.
|
||||||
|
|
||||||
| Fast iteration | Small footprint | Easy to embed |
|
| Fast iteration | Small footprint | Easy to embed |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| About **15× faster compilation** in the Hyperion benchmark. | **4.2 MB** Windows drop-in, compared with **19.3 MB** for DXC plus its DXIL library. | A **static library** by default, with a C API and a native Zig module. |
|
| About **14× faster compilation** in the Hyperion benchmark. | **4.2 MB** Windows drop-in, compared with **19.3 MB** for DXC plus its DXIL library. | A **static library** by default, with a C API and a native Zig module. |
|
||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
|
|
@ -70,21 +70,14 @@ Download Windows, Linux, and macOS bundles from a successful run's **Artifacts**
|
||||||
section on [GitHub Actions](https://github.com/peterino2/zdxc/actions).
|
section on [GitHub Actions](https://github.com/peterino2/zdxc/actions).
|
||||||
Each bundle includes the CLI, static C library, header, and DXC drop-in.
|
Each bundle includes the CLI, static C library, header, and DXC drop-in.
|
||||||
|
|
||||||
See the [case studies](https://zdxc.org/case-studies.html) for benchmark
|
See the [Hyperion case study](https://zdxc.org/case-studies.html) for benchmark
|
||||||
measurements and methodology. In Hyperion's Windows DXIL cook, zdxc's compile
|
measurements and methodology. In that Windows DXIL workload, zdxc's compile
|
||||||
step was **15.5× faster** and the complete shader cook was **2.5× faster**;
|
step was **13.9× faster** and the complete shader cook was **2.5× faster**.
|
||||||
Unreal Engine 5.8's editor compiled its 11,156 startup shaders **4.3× faster**.
|
|
||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
zdxc is **alpha software**. HLSL 2021 is the default; use `-HV 2018` for
|
zdxc is **alpha software**, focused on HLSL 2021 (`-HV 2021`). DXC compatibility
|
||||||
HLSL 2018 shaders. DXIL supports work graph node shaders in `lib_6_8`
|
is still being developed; not every DXC interface or feature is implemented.
|
||||||
libraries, SM 6.8 `Barrier()`, and `[WaveSize]` metadata. Work graph nodes
|
|
||||||
are not supported by the SPIR-V backend. See the
|
|
||||||
[command-line guide](docs/manual/03-command-line.md) for examples.
|
|
||||||
|
|
||||||
DXC compatibility is still being developed; not every interface or feature
|
|
||||||
is implemented.
|
|
||||||
The [drop-in manual](https://zdxc.org/manual.html#section-dxc-drop-in) documents
|
The [drop-in manual](https://zdxc.org/manual.html#section-dxc-drop-in) documents
|
||||||
the current interface coverage.
|
the current interface coverage.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -24,10 +24,8 @@ no `dxil.dll`: zdxc signs DXIL itself.
|
||||||
|
|
||||||
| Class | Interfaces |
|
| Class | Interfaces |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `CLSID_DxcCompiler` | `IDxcCompiler3` (`Compile`), `IDxcCompiler` (`Compile`, `Preprocess`), `IDxcCompiler2` (`CompileWithDebug`), `IDxcVersionInfo` (reports 1.11) |
|
| `CLSID_DxcCompiler` | `IDxcCompiler3` (`Compile`), `IDxcVersionInfo` (reports 1.11) |
|
||||||
| `CLSID_DxcUtils` (also reached as `CLSID_DxcLibrary`) | `IDxcUtils`: blob creation, `LoadFile`, `CreateDefaultIncludeHandler`, `GetBlobAsUtf8` / `GetBlobAsWide`, `GetDxilContainerPart`, `CreateReflection` |
|
| `CLSID_DxcUtils` (also reached as `CLSID_DxcLibrary`) | `IDxcUtils`: blob creation, `LoadFile`, `CreateDefaultIncludeHandler`, `GetBlobAsUtf8` / `GetBlobAsWide`, `GetDxilContainerPart` |
|
||||||
| `CLSID_DxcContainerReflection` | `IDxcContainerReflection`: load and inspect container parts, `GetPartReflection` |
|
|
||||||
| `CLSID_DxcContainerBuilder` | `IDxcContainerBuilder`: load, add/remove parts, serialize a signed container |
|
|
||||||
|
|
||||||
`Compile` takes the same arguments as the command line and follows DXC:
|
`Compile` takes the same arguments as the command line and follows DXC:
|
||||||
|
|
||||||
|
|
@ -46,21 +44,13 @@ no `dxil.dll`: zdxc signs DXIL itself.
|
||||||
|
|
||||||
Classes and methods that are not implemented return `REGDB_E_CLASSNOTREG`
|
Classes and methods that are not implemented return `REGDB_E_CLASSNOTREG`
|
||||||
or `E_NOTIMPL`. These include:
|
or `E_NOTIMPL`. These include:
|
||||||
|
- the legacy `IDxcCompiler` and `IDxcCompiler2` interfaces;
|
||||||
- `Disassemble`;
|
- `Disassemble`;
|
||||||
- `BuildArguments` and `GetPDBContents`;
|
- `CreateReflection`, `BuildArguments` and `GetPDBContents`;
|
||||||
- the validator, linker, and PDB classes.
|
- the validator, linker, container and PDB classes.
|
||||||
|
|
||||||
DXIL results include `DXC_OUT_REFLECTION`. `CreateReflection` reads zdxc
|
The result has no `DXC_OUT_REFLECTION` output (the reflection container
|
||||||
reflection blobs and exposes `ID3D12ShaderReflection` or
|
that `CreateReflection` reads).
|
||||||
`ID3D12LibraryReflection`. `CompileWithDebug` compiles the shader but returns
|
|
||||||
no separate debug name or blob; zdxc does not write PDBs.
|
|
||||||
|
|
||||||
Language support is zdxc's own. HLSL 2021 is the default; pass `-HV 2018`
|
Language support is zdxc's own: HLSL 2021, with `-HV 2021` as the only
|
||||||
for HLSL 2018's component-wise `&&`, `||`, and numeric `?:`, which evaluate
|
version.
|
||||||
both operands or branches. `-HV 2016` and `-HV 2017` use the same legacy
|
|
||||||
operator semantics. These options apply to both executable and library calls.
|
|
||||||
|
|
||||||
DXIL supports work graph node shaders compiled as `lib_6_8`, including
|
|
||||||
node input/output records and the `broadcasting`, `coalescing`, and `thread`
|
|
||||||
launch modes. Work graph nodes are not supported with `-spirv`.
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ order: 1
|
||||||
title: Introduction
|
title: Introduction
|
||||||
---
|
---
|
||||||
|
|
||||||
zdxc is a from-scratch HLSL compiler written in Zig. It emits DXIL and
|
zdxc is a from-scratch HLSL 2021 compiler written in Zig. It emits DXIL and
|
||||||
SPIR-V and has no package dependencies. The same compiler is available through
|
SPIR-V and has no package dependencies. The same compiler is available through
|
||||||
four interfaces:
|
four interfaces:
|
||||||
|
|
||||||
|
|
@ -15,14 +15,5 @@ four interfaces:
|
||||||
| `zdxc` Zig module | Direct access to the compiler from a Zig build. |
|
| `zdxc` Zig module | Direct access to the compiler from a Zig build. |
|
||||||
| `dxc` / `dxcompiler` | Drop-in names and entry points for existing DXC clients. |
|
| `dxc` / `dxcompiler` | Drop-in names and entry points for existing DXC clients. |
|
||||||
|
|
||||||
HLSL 2021 is the default language version. Select HLSL 2018 with `-HV 2018`;
|
The source language is HLSL 2021; `-HV 2021` is the only language version.
|
||||||
`-HV 2016` and `-HV 2017` are also accepted with the same legacy operator
|
|
||||||
semantics. The language version is independent of the target shader model.
|
|
||||||
|
|
||||||
Compute shaders support thread groups, `groupshared` storage, and group
|
|
||||||
barriers. The DXIL backend also supports work graph node shaders in
|
|
||||||
`lib_6_8` libraries, SM 6.8 `Barrier()`, and `[WaveSize]` metadata. Work graph
|
|
||||||
nodes are not supported in SPIR-V. See the
|
|
||||||
[command-line guide](03-command-line.md) for language and work graph examples.
|
|
||||||
|
|
||||||
DXIL output is signed by zdxc itself, so no separate `dxil` library is needed.
|
DXIL output is signed by zdxc itself, so no separate `dxil` library is needed.
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,6 @@ a file or, through the library interfaces, from memory.
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `-T <profile>` | Target profile, such as `vs_6_0`, `ps_6_0`, or `cs_6_0`. |
|
| `-T <profile>` | Target profile, such as `vs_6_0`, `ps_6_0`, or `cs_6_0`. |
|
||||||
| `-E <name>` | Shader entry point. |
|
| `-E <name>` | Shader entry point. |
|
||||||
| `-HV <version>` | HLSL language version: `2021` (default), `2018`, `2017`, or `2016`. |
|
|
||||||
| `-D <name[=value]>` | Define a preprocessor macro. |
|
| `-D <name[=value]>` | Define a preprocessor macro. |
|
||||||
| `-I <directory>` | Add an include search directory. |
|
| `-I <directory>` | Add an include search directory. |
|
||||||
| `-Fo <file>` | Write the object to a file. |
|
| `-Fo <file>` | Write the object to a file. |
|
||||||
|
|
@ -20,75 +19,12 @@ a file or, through the library interfaces, from memory.
|
||||||
| `-P` | Preprocess instead of compiling. |
|
| `-P` | Preprocess instead of compiling. |
|
||||||
| `-spirv` | Emit SPIR-V instead of DXIL. |
|
| `-spirv` | Emit SPIR-V instead of DXIL. |
|
||||||
| `-Zpr` / `-Zpc` | Select row- or column-major matrix packing. |
|
| `-Zpr` / `-Zpc` | Select row- or column-major matrix packing. |
|
||||||
| `-O0` … `-O3`, `-Od` | Select the optimization level. `-Od`, as in dxc, still promotes locals to SSA values and removes dead code, but does nothing else. |
|
| `-O0` … `-O3`, `-Od` | Select the optimization level. |
|
||||||
| `--job=<file>` | Compile a JSON batch of shaders in one process. |
|
| `--job=<file>` | Compile a JSON batch of shaders in one process. |
|
||||||
|
|
||||||
DXIL is the default backend. Add `-spirv` for SPIR-V, with the `-fvk-*` and
|
DXIL is the default backend. Add `-spirv` for SPIR-V, with the `-fvk-*` and
|
||||||
`-fspv-*` options controlling Vulkan bindings, layout, and target environment.
|
`-fspv-*` options controlling Vulkan bindings, layout, and target environment.
|
||||||
|
|
||||||
## HLSL language versions
|
|
||||||
|
|
||||||
Use `-HV 2018` when compiling shaders written for HLSL 2018:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
zdxc -HV 2018 -T ps_6_0 -E main shader.hlsl -Fo shader.dxil
|
|
||||||
zdxc -HV 2018 -spirv -T ps_6_0 -E main shader.hlsl -Fo shader.spv
|
|
||||||
```
|
|
||||||
|
|
||||||
The default is `-HV 2021`. In the legacy modes (`2016`, `2017`, and `2018`),
|
|
||||||
`&&` and `||` evaluate both operands and operate component-wise on vectors;
|
|
||||||
numeric `?:` evaluates both branches and permits a vector condition to
|
|
||||||
select per component. In 2021 mode, logical operands and the conditional
|
|
||||||
test are scalar, and evaluation short-circuits. Code that relies on an
|
|
||||||
unevaluated expression to avoid side effects needs particular care when
|
|
||||||
switching to a legacy mode.
|
|
||||||
|
|
||||||
The preprocessor macro `__HLSL_VERSION` reflects the selected version.
|
|
||||||
`-HV` selects language semantics; `-T` independently selects the shader
|
|
||||||
stage and shader model. These options also work in batch jobs and through
|
|
||||||
the C API and DXC drop-in.
|
|
||||||
|
|
||||||
## Compute thread groups and work graphs
|
|
||||||
|
|
||||||
Compute shaders use `[numthreads(x, y, z)]` to declare their thread group
|
|
||||||
size, `groupshared` for group-local storage, and intrinsics such as
|
|
||||||
`GroupMemoryBarrierWithGroupSync()` for synchronization. Compile them with
|
|
||||||
a compute profile, for example `-T cs_6_0 -E main`, for DXIL or SPIR-V.
|
|
||||||
|
|
||||||
For DXIL, `[WaveSize]` is emitted in entry-point and runtime metadata,
|
|
||||||
including the minimum, maximum, and preferred sizes for SM 6.8 wave-size
|
|
||||||
ranges. SM 6.8's `Barrier()` supports memory flags, UAVs, and node records.
|
|
||||||
|
|
||||||
Work graphs use node shaders in a shader library. Compile with `-T lib_6_8`
|
|
||||||
and mark each node with `[Shader("node")]` and its `[NodeLaunch]` mode;
|
|
||||||
there is no single `-E` entry point for the library. The supported launch
|
|
||||||
modes are `broadcasting`, `coalescing`, and `thread`. Node input/output
|
|
||||||
records, record allocation and completion, dispatch grids, node IDs, and
|
|
||||||
`GetRemainingRecursionLevels()` are supported by the DXIL backend.
|
|
||||||
|
|
||||||
For example, save this broadcasting node as `node.hlsl`:
|
|
||||||
|
|
||||||
```hlsl
|
|
||||||
RWStructuredBuffer<uint> values : register(u0);
|
|
||||||
|
|
||||||
[Shader("node")]
|
|
||||||
[NodeLaunch("broadcasting")]
|
|
||||||
[NodeDispatchGrid(1, 1, 1)]
|
|
||||||
[numthreads(64, 1, 1)]
|
|
||||||
void Fill(uint3 id : SV_DispatchThreadID)
|
|
||||||
{
|
|
||||||
values[id.x] = id.x;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```sh
|
|
||||||
zdxc -T lib_6_8 node.hlsl -Fo node.dxil
|
|
||||||
```
|
|
||||||
|
|
||||||
This produces a node shader library for a host application's work graph.
|
|
||||||
Work graph nodes are DXIL-only; compiling them with `-spirv` reports an
|
|
||||||
unsupported-feature error.
|
|
||||||
|
|
||||||
## Diagnostics and exit status
|
## Diagnostics and exit status
|
||||||
|
|
||||||
Diagnostics follow dxc's command-line format. Exit status is 0 for success,
|
Diagnostics follow dxc's command-line format. Exit status is 0 for success,
|
||||||
|
|
|
||||||
|
|
@ -28,10 +28,8 @@ no `dxil.dll`: zdxc signs DXIL itself.
|
||||||
|
|
||||||
| Class | Interfaces |
|
| Class | Interfaces |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `CLSID_DxcCompiler` | `IDxcCompiler3` (`Compile`), `IDxcCompiler` (`Compile`, `Preprocess`), `IDxcCompiler2` (`CompileWithDebug`), `IDxcVersionInfo` (reports 1.11) |
|
| `CLSID_DxcCompiler` | `IDxcCompiler3` (`Compile`), `IDxcVersionInfo` (reports 1.11) |
|
||||||
| `CLSID_DxcUtils` (also reached as `CLSID_DxcLibrary`) | `IDxcUtils`: blob creation, `LoadFile`, `CreateDefaultIncludeHandler`, `GetBlobAsUtf8` / `GetBlobAsWide`, `GetDxilContainerPart`, `CreateReflection` |
|
| `CLSID_DxcUtils` (also reached as `CLSID_DxcLibrary`) | `IDxcUtils`: blob creation, `LoadFile`, `CreateDefaultIncludeHandler`, `GetBlobAsUtf8` / `GetBlobAsWide`, `GetDxilContainerPart` |
|
||||||
| `CLSID_DxcContainerReflection` | `IDxcContainerReflection`: load and inspect container parts, `GetPartReflection` |
|
|
||||||
| `CLSID_DxcContainerBuilder` | `IDxcContainerBuilder`: load, add/remove parts, serialize a signed container |
|
|
||||||
|
|
||||||
`Compile` takes the same arguments as the command line and follows DXC:
|
`Compile` takes the same arguments as the command line and follows DXC:
|
||||||
|
|
||||||
|
|
@ -50,21 +48,13 @@ no `dxil.dll`: zdxc signs DXIL itself.
|
||||||
|
|
||||||
Classes and methods that are not implemented return `REGDB_E_CLASSNOTREG`
|
Classes and methods that are not implemented return `REGDB_E_CLASSNOTREG`
|
||||||
or `E_NOTIMPL`. These include:
|
or `E_NOTIMPL`. These include:
|
||||||
|
- the legacy `IDxcCompiler` and `IDxcCompiler2` interfaces;
|
||||||
- `Disassemble`;
|
- `Disassemble`;
|
||||||
- `BuildArguments` and `GetPDBContents`;
|
- `CreateReflection`, `BuildArguments` and `GetPDBContents`;
|
||||||
- the validator, linker, and PDB classes.
|
- the validator, linker, container and PDB classes.
|
||||||
|
|
||||||
DXIL results include `DXC_OUT_REFLECTION`. `CreateReflection` reads zdxc
|
The result has no `DXC_OUT_REFLECTION` output (the reflection container
|
||||||
reflection blobs and exposes `ID3D12ShaderReflection` or
|
that `CreateReflection` reads).
|
||||||
`ID3D12LibraryReflection`. `CompileWithDebug` compiles the shader but returns
|
|
||||||
no separate debug name or blob; zdxc does not write PDBs.
|
|
||||||
|
|
||||||
Language support is zdxc's own. HLSL 2021 is the default; pass `-HV 2018`
|
Language support is zdxc's own: HLSL 2021, with `-HV 2021` as the only
|
||||||
for HLSL 2018's component-wise `&&`, `||`, and numeric `?:`, which evaluate
|
version.
|
||||||
both operands or branches. `-HV 2016` and `-HV 2017` use the same legacy
|
|
||||||
operator semantics. These options apply to both executable and library calls.
|
|
||||||
|
|
||||||
DXIL supports work graph node shaders compiled as `lib_6_8`, including
|
|
||||||
node input/output records and the `broadcasting`, `coalescing`, and `thread`
|
|
||||||
launch modes. Work graph nodes are not supported with `-spirv`.
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
/*
|
/*
|
||||||
* zdxc: an HLSL 2018 / 2021 to DXIL and SPIR-V compiler.
|
* zdxc: an HLSL 2021 to DXIL and SPIR-V compiler.
|
||||||
*
|
*
|
||||||
* The C API. Link libzdxc statically (zig build -Dlinkage=static, the
|
* The C API. Link libzdxc statically (zig build -Dlinkage=static, the
|
||||||
* default) or dynamically (-Dlinkage=dynamic); it needs nothing besides
|
* default) or dynamically (-Dlinkage=dynamic); it needs nothing besides
|
||||||
|
|
|
||||||
|
|
@ -528,7 +528,6 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
|
||||||
const zv = stats.begin(.spirv);
|
const zv = stats.begin(.spirv);
|
||||||
defer if (opts.spirv) zv.end();
|
defer if (opts.spirv) zv.end();
|
||||||
if (opts.spirv) {
|
if (opts.spirv) {
|
||||||
try zdxc.ir.inline_calls.runResourceReturns(m);
|
|
||||||
zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) {
|
zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) {
|
||||||
error.Unsupported => {
|
error.Unsupported => {
|
||||||
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
|
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
|
||||||
|
|
@ -564,7 +563,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
|
||||||
m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed;
|
m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed;
|
||||||
};
|
};
|
||||||
const zd = stats.begin(.dxil);
|
const zd = stats.begin(.dxil);
|
||||||
const dxil_out = zdxc.dxil.emit.emitWithReflectionAt(arena, m, profile.?, &diags, if (opts.no_opt) .none else if (opts.opt_level == .od) .debug else .full) catch |err| switch (err) {
|
const dxil_out = zdxc.dxil.emit.emitWithReflection(arena, m, profile.?, &diags, !opts.no_opt and opts.opt_level != .od) catch |err| switch (err) {
|
||||||
error.Unsupported => {
|
error.Unsupported => {
|
||||||
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
|
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
|
||||||
return error.CompileFailed;
|
return error.CompileFailed;
|
||||||
|
|
|
||||||
112
src/dxcapi.zig
112
src/dxcapi.zig
|
|
@ -112,8 +112,6 @@ const IID_IDxcIncludeHandler = GUID.parse("7f61fc7d-950d-467f-b3e3-3c02fb49187c"
|
||||||
const IID_IDxcOperationResult = GUID.parse("cedb484a-d4e9-445a-b991-ca21ca157dc2");
|
const IID_IDxcOperationResult = GUID.parse("cedb484a-d4e9-445a-b991-ca21ca157dc2");
|
||||||
const IID_IDxcResult = GUID.parse("58346cda-dde7-4497-9461-6f87af5e0659");
|
const IID_IDxcResult = GUID.parse("58346cda-dde7-4497-9461-6f87af5e0659");
|
||||||
const IID_IDxcCompiler3 = GUID.parse("228b4687-5a6a-4730-900c-9702b2203f54");
|
const IID_IDxcCompiler3 = GUID.parse("228b4687-5a6a-4730-900c-9702b2203f54");
|
||||||
const IID_IDxcCompiler = GUID.parse("8c210bf3-011f-4422-8d70-6f9acb8db617");
|
|
||||||
const IID_IDxcCompiler2 = GUID.parse("a005a9d9-b8bb-4594-b5c9-0e633bec4d37");
|
|
||||||
const IID_IDxcUtils = GUID.parse("4605c4cb-2019-492a-ada4-65f20bb7d67f");
|
const IID_IDxcUtils = GUID.parse("4605c4cb-2019-492a-ada4-65f20bb7d67f");
|
||||||
const IID_IDxcVersionInfo = GUID.parse("b04f5b50-2059-4f12-a8ff-a1e0cde1cc7e");
|
const IID_IDxcVersionInfo = GUID.parse("b04f5b50-2059-4f12-a8ff-a1e0cde1cc7e");
|
||||||
|
|
||||||
|
|
@ -741,18 +739,6 @@ const Compiler3Vtbl = extern struct {
|
||||||
Disassemble: *const fn (This, ?*const Buffer, *const GUID, ?Out) callconv(cc) HRESULT,
|
Disassemble: *const fn (This, ?*const Buffer, *const GUID, ?Out) callconv(cc) HRESULT,
|
||||||
};
|
};
|
||||||
|
|
||||||
const DxcDefine = extern struct { Name: ?[*:0]const WCHAR, Value: ?[*:0]const WCHAR };
|
|
||||||
|
|
||||||
/// IDxcCompiler and IDxcCompiler2 (hassle-rs and other older clients):
|
|
||||||
/// entry point, profile and defines as parameters, the source as a blob.
|
|
||||||
const Compiler2Vtbl = extern struct {
|
|
||||||
unknown: UnknownVtbl,
|
|
||||||
Compile: *const fn (This, ?*anyopaque, ?[*:0]const WCHAR, ?[*:0]const WCHAR, ?[*:0]const WCHAR, ?[*]const ?[*:0]const WCHAR, u32, ?[*]const DxcDefine, u32, ?*anyopaque, ?Out) callconv(cc) HRESULT,
|
|
||||||
Preprocess: *const fn (This, ?*anyopaque, ?[*:0]const WCHAR, ?[*]const ?[*:0]const WCHAR, u32, ?[*]const DxcDefine, u32, ?*anyopaque, ?Out) callconv(cc) HRESULT,
|
|
||||||
Disassemble: *const fn (This, ?*anyopaque, ?Out) callconv(cc) HRESULT,
|
|
||||||
CompileWithDebug: *const fn (This, ?*anyopaque, ?[*:0]const WCHAR, ?[*:0]const WCHAR, ?[*:0]const WCHAR, ?[*]const ?[*:0]const WCHAR, u32, ?[*]const DxcDefine, u32, ?*anyopaque, ?Out, ?*?[*:0]WCHAR, ?Out) callconv(cc) HRESULT,
|
|
||||||
};
|
|
||||||
|
|
||||||
const VersionInfoVtbl = extern struct {
|
const VersionInfoVtbl = extern struct {
|
||||||
unknown: UnknownVtbl,
|
unknown: UnknownVtbl,
|
||||||
GetVersion: *const fn (This, ?*u32, ?*u32) callconv(cc) HRESULT,
|
GetVersion: *const fn (This, ?*u32, ?*u32) callconv(cc) HRESULT,
|
||||||
|
|
@ -762,17 +748,8 @@ const VersionInfoVtbl = extern struct {
|
||||||
const Compiler = struct {
|
const Compiler = struct {
|
||||||
compiler: Iface(Compiler3Vtbl) = .{ .vtbl = &compiler_vtbl },
|
compiler: Iface(Compiler3Vtbl) = .{ .vtbl = &compiler_vtbl },
|
||||||
version: Iface(VersionInfoVtbl) = .{ .vtbl = &version_vtbl },
|
version: Iface(VersionInfoVtbl) = .{ .vtbl = &version_vtbl },
|
||||||
legacy: Iface(Compiler2Vtbl) = .{ .vtbl = &legacy_vtbl },
|
|
||||||
rc: RefCount = .{},
|
rc: RefCount = .{},
|
||||||
|
|
||||||
const legacy_vtbl: Compiler2Vtbl = .{
|
|
||||||
.unknown = .{ .QueryInterface = legacyQueryInterface, .AddRef = legacyAddRef, .Release = legacyRelease },
|
|
||||||
.Compile = legacyCompile,
|
|
||||||
.Preprocess = legacyPreprocess,
|
|
||||||
.Disassemble = legacyDisassemble,
|
|
||||||
.CompileWithDebug = legacyCompileWithDebug,
|
|
||||||
};
|
|
||||||
|
|
||||||
const compiler_vtbl: Compiler3Vtbl = .{
|
const compiler_vtbl: Compiler3Vtbl = .{
|
||||||
.unknown = .{ .QueryInterface = queryInterface, .AddRef = addRef, .Release = release },
|
.unknown = .{ .QueryInterface = queryInterface, .AddRef = addRef, .Release = release },
|
||||||
.Compile = compileFn,
|
.Compile = compileFn,
|
||||||
|
|
@ -793,8 +770,6 @@ const Compiler = struct {
|
||||||
&c.compiler
|
&c.compiler
|
||||||
else if (iid.eql(IID_IDxcVersionInfo))
|
else if (iid.eql(IID_IDxcVersionInfo))
|
||||||
&c.version
|
&c.version
|
||||||
else if (iid.eql(IID_IDxcCompiler) or iid.eql(IID_IDxcCompiler2))
|
|
||||||
&c.legacy
|
|
||||||
else
|
else
|
||||||
null;
|
null;
|
||||||
if (p == null) {
|
if (p == null) {
|
||||||
|
|
@ -859,85 +834,6 @@ const Compiler = struct {
|
||||||
_ = put(out, null);
|
_ = put(out, null);
|
||||||
return E_NOTIMPL;
|
return E_NOTIMPL;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn legacyOf(this: This) *Compiler {
|
|
||||||
return parent(Compiler, "legacy", this);
|
|
||||||
}
|
|
||||||
fn legacyQueryInterface(this: This, iid: *const GUID, out: ?Out) callconv(cc) HRESULT {
|
|
||||||
return legacyOf(this).query(iid, out);
|
|
||||||
}
|
|
||||||
fn legacyAddRef(this: This) callconv(cc) ULONG {
|
|
||||||
return legacyOf(this).rc.addRef();
|
|
||||||
}
|
|
||||||
fn legacyRelease(this: This) callconv(cc) ULONG {
|
|
||||||
return release(&legacyOf(this).compiler);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacyCompile(_: This, source: ?*anyopaque, name: ?[*:0]const WCHAR, entry: ?[*:0]const WCHAR, profile: ?[*:0]const WCHAR, args: ?[*]const ?[*:0]const WCHAR, count: u32, defines: ?[*]const DxcDefine, define_count: u32, include: ?*anyopaque, out: ?Out) callconv(cc) HRESULT {
|
|
||||||
const p = profile orelse {
|
|
||||||
_ = put(out, null);
|
|
||||||
return E_INVALIDARG;
|
|
||||||
};
|
|
||||||
return legacyRun(source, name, .{ .compile = .{ .entry = entry, .profile = p } }, args, count, defines, define_count, include, out);
|
|
||||||
}
|
|
||||||
fn legacyCompileWithDebug(this: This, source: ?*anyopaque, name: ?[*:0]const WCHAR, entry: ?[*:0]const WCHAR, profile: ?[*:0]const WCHAR, args: ?[*]const ?[*:0]const WCHAR, count: u32, defines: ?[*]const DxcDefine, define_count: u32, include: ?*anyopaque, out: ?Out, debug_name: ?*?[*:0]WCHAR, debug_blob: ?Out) callconv(cc) HRESULT {
|
|
||||||
// No separate debug blob (zdxc writes no PDBs).
|
|
||||||
if (debug_name) |d| d.* = null;
|
|
||||||
if (debug_blob) |d| d.* = null;
|
|
||||||
return legacyCompile(this, source, name, entry, profile, args, count, defines, define_count, include, out);
|
|
||||||
}
|
|
||||||
fn legacyPreprocess(_: This, source: ?*anyopaque, name: ?[*:0]const WCHAR, args: ?[*]const ?[*:0]const WCHAR, count: u32, defines: ?[*]const DxcDefine, define_count: u32, include: ?*anyopaque, out: ?Out) callconv(cc) HRESULT {
|
|
||||||
return legacyRun(source, name, .preprocess, args, count, defines, define_count, include, out);
|
|
||||||
}
|
|
||||||
fn legacyDisassemble(_: This, _: ?*anyopaque, out: ?Out) callconv(cc) HRESULT {
|
|
||||||
_ = put(out, null);
|
|
||||||
return E_NOTIMPL;
|
|
||||||
}
|
|
||||||
|
|
||||||
const LegacyMode = union(enum) {
|
|
||||||
compile: struct { entry: ?[*:0]const WCHAR, profile: [*:0]const WCHAR },
|
|
||||||
preprocess,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// The legacy calls as IDxcCompiler3 arguments: `-E entry -T profile`
|
|
||||||
/// (or `-P`), the arguments, then `-D name=value` per define.
|
|
||||||
fn legacyRun(source: ?*anyopaque, name: ?[*:0]const WCHAR, mode: LegacyMode, args: ?[*]const ?[*:0]const WCHAR, count: u32, defines: ?[*]const DxcDefine, define_count: u32, include: ?*anyopaque, out: ?Out) HRESULT {
|
|
||||||
const o = out orelse return E_POINTER;
|
|
||||||
o.* = null;
|
|
||||||
const blob = source orelse return E_INVALIDARG;
|
|
||||||
if ((count > 0 and args == null) or (define_count > 0 and defines == null)) return E_INVALIDARG;
|
|
||||||
const r = runLegacy(blob, name, mode, if (args) |a| a[0..count] else &.{}, if (defines) |d| d[0..define_count] else &.{}, include) catch |e| return switch (e) {
|
|
||||||
error.OutOfMemory => E_OUTOFMEMORY,
|
|
||||||
error.InvalidArgument => E_INVALIDARG,
|
|
||||||
};
|
|
||||||
o.* = &r.iface;
|
|
||||||
return S_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn runLegacy(blob: *anyopaque, name: ?[*:0]const WCHAR, mode: LegacyMode, wargs: []const ?[*:0]const WCHAR, defines: []const DxcDefine, include: ?*anyopaque) error{ OutOfMemory, InvalidArgument }!*Result {
|
|
||||||
if (thread_arena == null) thread_arena = .init(gpa);
|
|
||||||
const arena = &thread_arena.?;
|
|
||||||
defer _ = arena.reset(.{ .retain_with_limit = retain_limit });
|
|
||||||
const a = arena.allocator();
|
|
||||||
var args: std.ArrayList([]const u8) = .empty;
|
|
||||||
switch (mode) {
|
|
||||||
.compile => |c| {
|
|
||||||
if (c.entry) |e| try args.appendSlice(a, &.{ "-E", try fromWide(a, e) });
|
|
||||||
try args.appendSlice(a, &.{ "-T", try fromWide(a, c.profile) });
|
|
||||||
},
|
|
||||||
.preprocess => try args.append(a, "-P"),
|
|
||||||
}
|
|
||||||
for (wargs) |w| try args.append(a, try fromWide(a, w orelse return error.InvalidArgument));
|
|
||||||
for (defines) |d| {
|
|
||||||
const n = try fromWide(a, d.Name orelse continue);
|
|
||||||
try args.appendSlice(a, &.{ "-D", if (d.Value) |v| try std.fmt.allocPrint(a, "{s}={s}", .{ n, try fromWide(a, v) }) else n });
|
|
||||||
}
|
|
||||||
const text = Utils.blobText(a, blob) catch |e| return switch (e) {
|
|
||||||
error.OutOfMemory => error.OutOfMemory,
|
|
||||||
else => error.InvalidArgument,
|
|
||||||
};
|
|
||||||
return runText(a, args.items, text, if (name) |n| try fromWide(a, n) else null, include);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Each thread's compile arena, kept between calls. Freeing it per call
|
/// Each thread's compile arena, kept between calls. Freeing it per call
|
||||||
|
|
@ -955,17 +851,11 @@ fn run(source: *const Buffer, wargs: []const ?[*:0]const WCHAR, include: ?*anyop
|
||||||
const args = try a.alloc([]const u8, wargs.len);
|
const args = try a.alloc([]const u8, wargs.len);
|
||||||
for (args, wargs) |*d, w| d.* = try fromWide(a, w orelse return error.InvalidArgument);
|
for (args, wargs) |*d, w| d.* = try fromWide(a, w orelse return error.InvalidArgument);
|
||||||
const bytes: []const u8 = if (source.ptr) |p| p[0..source.size] else &.{};
|
const bytes: []const u8 = if (source.ptr) |p| p[0..source.size] else &.{};
|
||||||
return runText(a, args, try decodeText(a, bytes, source.encoding), null, include);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A compile of `text` (in the caller's thread arena).
|
|
||||||
fn runText(a: std.mem.Allocator, args: []const []const u8, text: []const u8, source_name: ?[]const u8, include: ?*anyopaque) error{ OutOfMemory, InvalidArgument }!*Result {
|
|
||||||
var client: ClientFs = undefined;
|
var client: ClientFs = undefined;
|
||||||
var threaded: std.Io.Threaded = .init_single_threaded;
|
var threaded: std.Io.Threaded = .init_single_threaded;
|
||||||
var req: compile.Request = .{
|
var req: compile.Request = .{
|
||||||
.args = args,
|
.args = args,
|
||||||
.source = text,
|
.source = try decodeText(a, bytes, source.encoding),
|
||||||
.source_name = source_name,
|
|
||||||
.io = threaded.io(),
|
.io = threaded.io(),
|
||||||
.fs = NoFs.fileSystem(),
|
.fs = NoFs.fileSystem(),
|
||||||
.compat_notes = false,
|
.compat_notes = false,
|
||||||
|
|
|
||||||
497
src/dxil/cfg.zig
497
src/dxil/cfg.zig
|
|
@ -1,497 +0,0 @@
|
||||||
//! Control-flow cleanup, as dxc's simplifycfg does it: a block that only
|
|
||||||
//! branches to a block with no other predecessor takes that block in, and
|
|
||||||
//! a block holding nothing but an unconditional branch is bypassed (its
|
|
||||||
//! predecessors branch straight to its successor). Lowering gives every
|
|
||||||
//! statement, scope and inlined call its own blocks, and the optimizer
|
|
||||||
//! empties many more; without this they stay as chains of branches.
|
|
||||||
//!
|
|
||||||
//! Run on a function in SSA form, after promotion (which drops the blocks
|
|
||||||
//! no path reaches).
|
|
||||||
|
|
||||||
const std = @import("std");
|
|
||||||
const Allocator = std.mem.Allocator;
|
|
||||||
const module = @import("module.zig");
|
|
||||||
const promote = @import("promote.zig");
|
|
||||||
const stats = @import("../stats.zig");
|
|
||||||
|
|
||||||
const Value = module.Value;
|
|
||||||
const Inst = module.Inst;
|
|
||||||
|
|
||||||
const none = std.math.maxInt(u32);
|
|
||||||
|
|
||||||
const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child;
|
|
||||||
const Case = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "switch"), "cases")).pointer.child;
|
|
||||||
|
|
||||||
fn isTerminator(inst: Inst) bool {
|
|
||||||
return switch (inst.op) {
|
|
||||||
.ret, .br, .@"switch", .@"unreachable" => true,
|
|
||||||
else => false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Most cost of the instructions one arm of an if may hoist above its
|
|
||||||
/// branch to become a select (LLVM's phi-node-folding-threshold, as in
|
|
||||||
/// dxc).
|
|
||||||
const max_arm_cost = 2;
|
|
||||||
|
|
||||||
const State = struct {
|
|
||||||
a: Allocator,
|
|
||||||
m: *const module.Module,
|
|
||||||
insts: []Inst,
|
|
||||||
/// Each block's instructions (old indices), its terminator last.
|
|
||||||
body: []std.ArrayList(u32),
|
|
||||||
/// Predecessor edges (a block twice if it branches here twice).
|
|
||||||
preds: []std.ArrayList(u32),
|
|
||||||
/// The block that now holds a merged block's terminator: phis naming
|
|
||||||
/// the merged block mean it.
|
|
||||||
owner: []u32,
|
|
||||||
alive: []bool,
|
|
||||||
/// Phis replaced by their one input.
|
|
||||||
repl: []?Value,
|
|
||||||
|
|
||||||
fn find(s: *State, b: u32) u32 {
|
|
||||||
var x = b;
|
|
||||||
while (s.owner[x] != x) x = s.owner[x];
|
|
||||||
var y = b;
|
|
||||||
while (s.owner[y] != x) {
|
|
||||||
const next = s.owner[y];
|
|
||||||
s.owner[y] = x;
|
|
||||||
y = next;
|
|
||||||
}
|
|
||||||
return x;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn term(s: *State, b: u32) *Inst {
|
|
||||||
const items = s.body[b].items;
|
|
||||||
return &s.insts[items[items.len - 1]];
|
|
||||||
}
|
|
||||||
|
|
||||||
fn hasPhis(s: *State, b: u32) bool {
|
|
||||||
return s.insts[s.body[b].items[0]].op == .phi;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn removePred(s: *State, b: u32, p: u32) void {
|
|
||||||
const l = &s.preds[b];
|
|
||||||
for (l.items, 0..) |x, k| if (x == p) {
|
|
||||||
_ = l.swapRemove(k);
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
fn renamePred(s: *State, x: u32, from: u32, to: u32) void {
|
|
||||||
for (s.preds[x].items) |*p| {
|
|
||||||
if (p.* == from) p.* = to;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn countPred(s: *State, b: u32, p: u32) u32 {
|
|
||||||
var c: u32 = 0;
|
|
||||||
for (s.preds[b].items) |x| c += @intFromBool(x == p);
|
|
||||||
return c;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `b` (unconditional branch to `c`, `c`'s only predecessor) takes in
|
|
||||||
/// `c`.
|
|
||||||
fn merge(s: *State, b: u32, c: u32) Allocator.Error!void {
|
|
||||||
const cb = s.body[c].items;
|
|
||||||
var k: usize = 0;
|
|
||||||
while (k < cb.len and s.insts[cb[k]].op == .phi) : (k += 1) {
|
|
||||||
s.repl[cb[k]] = s.insts[cb[k]].op.phi.incoming[0].val;
|
|
||||||
}
|
|
||||||
const bb = &s.body[b];
|
|
||||||
_ = bb.pop();
|
|
||||||
try bb.appendSlice(s.a, cb[k..]);
|
|
||||||
s.alive[c] = false;
|
|
||||||
s.owner[c] = b;
|
|
||||||
// (`c`'s successors now have `b` for a predecessor.)
|
|
||||||
switch (s.term(b).op) {
|
|
||||||
.br => |br| {
|
|
||||||
s.renamePred(br.then, c, b);
|
|
||||||
if (br.@"else") |e| s.renamePred(e, c, b);
|
|
||||||
},
|
|
||||||
.@"switch" => |sw| {
|
|
||||||
s.renamePred(sw.default, c, b);
|
|
||||||
for (sw.cases) |x| s.renamePred(x.block, c, b);
|
|
||||||
},
|
|
||||||
else => {},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Retargets `p`'s edges to `b` at `c`.
|
|
||||||
fn retarget(s: *State, p: u32, b: u32, c: u32) Allocator.Error!void {
|
|
||||||
const t = s.term(p);
|
|
||||||
switch (t.op) {
|
|
||||||
.br => |*br| {
|
|
||||||
if (br.then == b) br.then = c;
|
|
||||||
if (br.@"else") |*e| if (e.* == b) {
|
|
||||||
e.* = c;
|
|
||||||
};
|
|
||||||
},
|
|
||||||
.@"switch" => |*sw| {
|
|
||||||
if (sw.default == b) sw.default = c;
|
|
||||||
const cs = try s.a.dupe(Case, sw.cases);
|
|
||||||
for (cs) |*x| if (x.block == b) {
|
|
||||||
x.block = c;
|
|
||||||
};
|
|
||||||
sw.cases = cs;
|
|
||||||
},
|
|
||||||
else => unreachable,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// True if `b` is cheap instructions safe to run on either path (see
|
|
||||||
/// cost) and `br m`, and only `p` branches to it.
|
|
||||||
fn armFrom(s: *State, b: u32, p: u32, m: u32) bool {
|
|
||||||
if (s.preds[b].items.len != 1 or s.preds[b].items[0] != p) return false;
|
|
||||||
const t = s.term(b).op;
|
|
||||||
if (t != .br or t.br.@"else" != null or t.br.then != m) return false;
|
|
||||||
const items = s.body[b].items;
|
|
||||||
var total: u32 = 0;
|
|
||||||
for (items[0 .. items.len - 1]) |i| {
|
|
||||||
total += s.cost(s.insts[i]) orelse return false;
|
|
||||||
if (total > max_arm_cost) return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What hoisting `inst` above a branch costs, or null if it cannot
|
|
||||||
/// be: it has an effect, may trap (integer division), or reads memory.
|
|
||||||
fn cost(s: *State, inst: Inst) ?u32 {
|
|
||||||
return switch (inst.op) {
|
|
||||||
.binop => |b| switch (b.op) {
|
|
||||||
.udiv, .sdiv, .urem, .srem => if (s.m.types.items[inst.ty] == .int) null else 1,
|
|
||||||
else => 1,
|
|
||||||
},
|
|
||||||
.cast => |c| if (c.op == .bitcast) 0 else 1,
|
|
||||||
.cmp, .select, .extractvalue, .extractelement, .insertelement => 1,
|
|
||||||
else => null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The instructions of `b` before its terminator, moved to the end of
|
|
||||||
/// `p` (before its terminator).
|
|
||||||
fn hoist(s: *State, b: u32, p: u32) Allocator.Error!void {
|
|
||||||
const from = s.body[b].items;
|
|
||||||
if (from.len < 2) return;
|
|
||||||
const to = &s.body[p];
|
|
||||||
const t = to.pop().?;
|
|
||||||
try to.appendSlice(s.a, from[0 .. from.len - 1]);
|
|
||||||
try to.append(s.a, t);
|
|
||||||
from[0] = from[from.len - 1];
|
|
||||||
s.body[b].shrinkRetainingCapacity(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A branch to one block every way goes there unconditionally; the
|
|
||||||
/// phis there keep one input from it.
|
|
||||||
fn collapse(s: *State, b: u32) Allocator.Error!bool {
|
|
||||||
const t = s.term(b);
|
|
||||||
const target: u32 = switch (t.op) {
|
|
||||||
.br => |br| if (br.@"else") |e| (if (e == br.then) e else return false) else return false,
|
|
||||||
.@"switch" => |sw| blk: {
|
|
||||||
for (sw.cases) |c| if (c.block != sw.default) return false;
|
|
||||||
break :blk sw.default;
|
|
||||||
},
|
|
||||||
else => return false,
|
|
||||||
};
|
|
||||||
t.op = .{ .br = .{ .then = target } };
|
|
||||||
while (s.countPred(target, b) > 1) s.removePred(target, b);
|
|
||||||
const cb = s.body[target].items;
|
|
||||||
var k: usize = 0;
|
|
||||||
while (k < cb.len and s.insts[cb[k]].op == .phi) : (k += 1) {
|
|
||||||
const phi = &s.insts[cb[k]].op.phi;
|
|
||||||
var out: std.ArrayList(Edge) = .empty;
|
|
||||||
var seen = false;
|
|
||||||
for (phi.incoming) |in| {
|
|
||||||
if (s.find(in.block) == b) {
|
|
||||||
if (seen) continue;
|
|
||||||
seen = true;
|
|
||||||
}
|
|
||||||
try out.append(s.a, in);
|
|
||||||
}
|
|
||||||
phi.incoming = out.items;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `m`'s two predecessors: a conditional branch and a block it
|
|
||||||
/// branches to (a triangle), or two blocks one conditional
|
|
||||||
/// branch picks between (a diamond). `m`'s phis become selects on the
|
|
||||||
/// branch's condition, and the branch goes straight to `m` (dxc's
|
|
||||||
/// simplifycfg folds two-entry phis so). True if done.
|
|
||||||
fn ifConvert(s: *State, m: u32) Allocator.Error!bool {
|
|
||||||
const ps = s.preds[m].items;
|
|
||||||
if (ps.len != 2 or ps[0] == ps[1]) return false;
|
|
||||||
// The branching block, and the block each of its arms reaches `m`
|
|
||||||
// from.
|
|
||||||
var p: u32 = none;
|
|
||||||
var via: [2]u32 = undefined;
|
|
||||||
for (0..2) |k| {
|
|
||||||
const q = ps[k];
|
|
||||||
const other = ps[1 - k];
|
|
||||||
const t = s.term(q).op;
|
|
||||||
if (q == m or t != .br) continue;
|
|
||||||
const e = t.br.@"else" orelse continue;
|
|
||||||
if (t.br.then == m and e == other and s.armFrom(other, q, m)) {
|
|
||||||
p = q;
|
|
||||||
via = .{ q, other };
|
|
||||||
} else if (e == m and t.br.then == other and s.armFrom(other, q, m)) {
|
|
||||||
p = q;
|
|
||||||
via = .{ other, q };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (p == none) {
|
|
||||||
// A diamond: both predecessors empty, from one branch.
|
|
||||||
if (s.preds[ps[0]].items.len != 1) return false;
|
|
||||||
const q = s.preds[ps[0]].items[0];
|
|
||||||
if (q == m or !s.armFrom(ps[0], q, m) or !s.armFrom(ps[1], q, m)) return false;
|
|
||||||
const t = s.term(q).op;
|
|
||||||
if (t != .br) return false;
|
|
||||||
const e = t.br.@"else" orelse return false;
|
|
||||||
if (t.br.then == ps[0] and e == ps[1]) {
|
|
||||||
via = .{ ps[0], ps[1] };
|
|
||||||
} else if (t.br.then == ps[1] and e == ps[0]) {
|
|
||||||
via = .{ ps[1], ps[0] };
|
|
||||||
} else return false;
|
|
||||||
p = q;
|
|
||||||
}
|
|
||||||
const cond = s.term(p).op.br.cond.?;
|
|
||||||
const mb = s.body[m].items;
|
|
||||||
var k: usize = 0;
|
|
||||||
while (k < mb.len and s.insts[mb[k]].op == .phi) : (k += 1) {
|
|
||||||
const inst = &s.insts[mb[k]];
|
|
||||||
var vals: [2]?Value = .{ null, null };
|
|
||||||
for (inst.op.phi.incoming) |in| {
|
|
||||||
const from = s.find(in.block);
|
|
||||||
if (from == via[0]) vals[0] = in.val else if (from == via[1]) vals[1] = in.val;
|
|
||||||
}
|
|
||||||
if (vals[0] == null or vals[1] == null) return false;
|
|
||||||
}
|
|
||||||
k = 0;
|
|
||||||
while (k < mb.len and s.insts[mb[k]].op == .phi) : (k += 1) {
|
|
||||||
const inst = &s.insts[mb[k]];
|
|
||||||
var vals: [2]Value = undefined;
|
|
||||||
for (inst.op.phi.incoming) |in| {
|
|
||||||
const from = s.find(in.block);
|
|
||||||
if (from == via[0]) vals[0] = in.val else if (from == via[1]) vals[1] = in.val;
|
|
||||||
}
|
|
||||||
if (std.meta.eql(vals[0], vals[1])) {
|
|
||||||
s.repl[mb[k]] = vals[0];
|
|
||||||
} else inst.op = .{ .select = .{ .cond = cond, .t = vals[0], .f = vals[1] } };
|
|
||||||
}
|
|
||||||
// `p` goes to `m`, running what the arms did first; their blocks
|
|
||||||
// go.
|
|
||||||
for (via) |v| if (v != p) try s.hoist(v, p);
|
|
||||||
s.term(p).op = .{ .br = .{ .then = m } };
|
|
||||||
for (via) |v| if (v != p) {
|
|
||||||
s.alive[v] = false;
|
|
||||||
s.preds[v].clearRetainingCapacity();
|
|
||||||
};
|
|
||||||
s.preds[m].clearRetainingCapacity();
|
|
||||||
try s.preds[m].append(s.a, p);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Bypasses `b` (only `br c`): its predecessors branch to `c`.
|
|
||||||
fn bypass(s: *State, b: u32, c: u32) Allocator.Error!void {
|
|
||||||
const ps = try s.a.dupe(u32, s.preds[b].items);
|
|
||||||
const phis = s.hasPhis(c);
|
|
||||||
// `c`'s phis: the input from `b` comes from each of `b`'s
|
|
||||||
// predecessors instead.
|
|
||||||
const cb = s.body[c].items;
|
|
||||||
var k: usize = 0;
|
|
||||||
while (k < cb.len and s.insts[cb[k]].op == .phi) : (k += 1) {
|
|
||||||
const phi = &s.insts[cb[k]].op.phi;
|
|
||||||
var out: std.ArrayList(Edge) = .empty;
|
|
||||||
try out.ensureTotalCapacity(s.a, phi.incoming.len + ps.len);
|
|
||||||
for (phi.incoming) |in| {
|
|
||||||
if (s.find(in.block) == b) {
|
|
||||||
for (ps) |p| out.appendAssumeCapacity(.{ .val = in.val, .block = p });
|
|
||||||
} else out.appendAssumeCapacity(in);
|
|
||||||
}
|
|
||||||
phi.incoming = out.items;
|
|
||||||
}
|
|
||||||
// (Each distinct predecessor once: retarget moves all its edges.)
|
|
||||||
for (ps, 0..) |p, i| {
|
|
||||||
if (std.mem.indexOfScalar(u32, ps[0..i], p) != null) continue;
|
|
||||||
try s.retarget(p, b, c);
|
|
||||||
}
|
|
||||||
s.removePred(c, b);
|
|
||||||
try s.preds[c].appendSlice(s.a, ps);
|
|
||||||
s.preds[b].clearRetainingCapacity();
|
|
||||||
s.alive[b] = false;
|
|
||||||
// A conditional branch now going to `c` both ways goes there
|
|
||||||
// unconditionally (when `c` has no phis to give two inputs).
|
|
||||||
if (!phis) for (ps) |p| {
|
|
||||||
const t = s.term(p);
|
|
||||||
if (t.op == .br) if (t.op.br.@"else") |e| if (e == t.op.br.then) {
|
|
||||||
t.op.br = .{ .then = e };
|
|
||||||
s.removePred(c, p);
|
|
||||||
};
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Simplifies `func`'s control flow; true if anything changed.
|
|
||||||
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
|
|
||||||
const zone = stats.begin(.cfg);
|
|
||||||
defer zone.end();
|
|
||||||
const f = &m.functions.items[func];
|
|
||||||
const nb = f.num_blocks;
|
|
||||||
const n: u32 = @intCast(f.insts.items.len);
|
|
||||||
if (nb < 2) return false;
|
|
||||||
|
|
||||||
var s: State = .{
|
|
||||||
.a = a,
|
|
||||||
.m = m,
|
|
||||||
.insts = try a.dupe(Inst, f.insts.items),
|
|
||||||
.body = try a.alloc(std.ArrayList(u32), nb),
|
|
||||||
.preds = try a.alloc(std.ArrayList(u32), nb),
|
|
||||||
.owner = try a.alloc(u32, nb),
|
|
||||||
.alive = try a.alloc(bool, nb),
|
|
||||||
.repl = try a.alloc(?Value, n),
|
|
||||||
};
|
|
||||||
@memset(s.repl, null);
|
|
||||||
@memset(s.alive, true);
|
|
||||||
for (s.owner, 0..) |*o, b| o.* = @intCast(b);
|
|
||||||
{
|
|
||||||
var b: u32 = 0;
|
|
||||||
var start: u32 = 0;
|
|
||||||
for (s.insts, 0..) |inst, i| {
|
|
||||||
if (!isTerminator(inst)) continue;
|
|
||||||
if (b >= nb) return false; // not the block layout expected
|
|
||||||
s.body[b] = .empty;
|
|
||||||
try s.body[b].ensureTotalCapacity(a, i + 1 - start);
|
|
||||||
for (start..i + 1) |k| s.body[b].appendAssumeCapacity(@intCast(k));
|
|
||||||
start = @intCast(i + 1);
|
|
||||||
b += 1;
|
|
||||||
}
|
|
||||||
if (b != nb or start != n) return false;
|
|
||||||
}
|
|
||||||
for (s.preds) |*p| p.* = .empty;
|
|
||||||
for (0..nb) |b| {
|
|
||||||
const t = s.term(@intCast(b)).*;
|
|
||||||
switch (t.op) {
|
|
||||||
.br => |br| {
|
|
||||||
try s.preds[br.then].append(a, @intCast(b));
|
|
||||||
if (br.@"else") |e| try s.preds[e].append(a, @intCast(b));
|
|
||||||
},
|
|
||||||
.@"switch" => |sw| {
|
|
||||||
try s.preds[sw.default].append(a, @intCast(b));
|
|
||||||
for (sw.cases) |c| try s.preds[c.block].append(a, @intCast(b));
|
|
||||||
},
|
|
||||||
else => {},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var changed = false;
|
|
||||||
var again = true;
|
|
||||||
while (again) {
|
|
||||||
again = false;
|
|
||||||
for (0..nb) |bi| {
|
|
||||||
const b: u32 = @intCast(bi);
|
|
||||||
if (!s.alive[b]) continue;
|
|
||||||
// Take in the chain of blocks only `b` leads to.
|
|
||||||
while (true) {
|
|
||||||
const t = s.term(b).*;
|
|
||||||
if (t.op != .br or t.op.br.@"else" != null) break;
|
|
||||||
const c = t.op.br.then;
|
|
||||||
if (c == b or c == 0 or s.preds[c].items.len != 1) break;
|
|
||||||
try s.merge(b, c);
|
|
||||||
changed = true;
|
|
||||||
again = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (1..nb) |bi| {
|
|
||||||
const b: u32 = @intCast(bi);
|
|
||||||
if (!s.alive[b] or s.body[b].items.len != 1) continue;
|
|
||||||
const t = s.term(b).*;
|
|
||||||
if (t.op != .br or t.op.br.@"else" != null) continue;
|
|
||||||
const c = t.op.br.then;
|
|
||||||
const ps = s.preds[b].items;
|
|
||||||
if (c == b or ps.len == 0) continue;
|
|
||||||
if (std.mem.indexOfScalar(u32, ps, b) != null) continue;
|
|
||||||
// With phis in `c`, a predecessor already branching there could
|
|
||||||
// need two values on one edge: left alone.
|
|
||||||
if (s.hasPhis(c)) {
|
|
||||||
const clash = for (ps) |p| {
|
|
||||||
if (s.countPred(c, p) != 0) break true;
|
|
||||||
} else false;
|
|
||||||
if (clash) continue;
|
|
||||||
}
|
|
||||||
try s.bypass(b, c);
|
|
||||||
changed = true;
|
|
||||||
again = true;
|
|
||||||
}
|
|
||||||
for (0..nb) |bi| {
|
|
||||||
const b: u32 = @intCast(bi);
|
|
||||||
if (!s.alive[b] or !try s.collapse(b)) continue;
|
|
||||||
changed = true;
|
|
||||||
again = true;
|
|
||||||
}
|
|
||||||
for (1..nb) |bi| {
|
|
||||||
const b: u32 = @intCast(bi);
|
|
||||||
if (!s.alive[b] or !try s.ifConvert(b)) continue;
|
|
||||||
changed = true;
|
|
||||||
again = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!changed) return false;
|
|
||||||
|
|
||||||
// Lay the blocks out again, in their old order, and renumber.
|
|
||||||
const new_block = try a.alloc(u32, nb);
|
|
||||||
var kept: u32 = 0;
|
|
||||||
for (0..nb) |b| {
|
|
||||||
new_block[b] = if (s.alive[b]) kept else none;
|
|
||||||
if (s.alive[b]) kept += 1;
|
|
||||||
}
|
|
||||||
const index = try a.alloc(u32, n);
|
|
||||||
@memset(index, none);
|
|
||||||
var count: u32 = 0;
|
|
||||||
for (0..nb) |b| if (s.alive[b]) for (s.body[b].items) |i| {
|
|
||||||
if (s.repl[i] != null) continue;
|
|
||||||
index[i] = count;
|
|
||||||
count += 1;
|
|
||||||
};
|
|
||||||
const Map = struct {
|
|
||||||
repl: []const ?Value,
|
|
||||||
index: []const u32,
|
|
||||||
pub fn visit(ctx: *@This(), v: Value, _: promote.Role) Value {
|
|
||||||
var x = v;
|
|
||||||
while (x == .inst) {
|
|
||||||
const r = ctx.repl[x.inst] orelse break;
|
|
||||||
x = r;
|
|
||||||
}
|
|
||||||
return if (x == .inst) .{ .inst = ctx.index[x.inst] } else x;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
var map: Map = .{ .repl = s.repl, .index = index };
|
|
||||||
const ma = m.allocator();
|
|
||||||
var out: std.ArrayList(Inst) = .empty;
|
|
||||||
try out.ensureTotalCapacityPrecise(ma, count);
|
|
||||||
for (0..nb) |b| if (s.alive[b]) for (s.body[b].items) |i| {
|
|
||||||
if (s.repl[i] != null) continue;
|
|
||||||
var inst = s.insts[i];
|
|
||||||
try promote.operands(true, ma, &inst, &map);
|
|
||||||
switch (inst.op) {
|
|
||||||
.phi => |*p| {
|
|
||||||
const es: []Edge = @constCast(p.incoming);
|
|
||||||
for (es) |*e| e.block = new_block[s.find(e.block)];
|
|
||||||
},
|
|
||||||
.br => |*br| {
|
|
||||||
br.then = new_block[br.then];
|
|
||||||
if (br.@"else") |*e| e.* = new_block[e.*];
|
|
||||||
},
|
|
||||||
.@"switch" => |*sw| {
|
|
||||||
sw.default = new_block[sw.default];
|
|
||||||
const cs = try ma.alloc(Case, sw.cases.len);
|
|
||||||
for (sw.cases, cs) |c, *o| o.* = .{ .val = c.val, .block = new_block[c.block] };
|
|
||||||
sw.cases = cs;
|
|
||||||
},
|
|
||||||
else => {},
|
|
||||||
}
|
|
||||||
out.appendAssumeCapacity(inst);
|
|
||||||
};
|
|
||||||
f.insts = out;
|
|
||||||
f.num_blocks = kept;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
325
src/dxil/cse.zig
325
src/dxil/cse.zig
|
|
@ -1,325 +0,0 @@
|
||||||
//! Common subexpression elimination over the dominator tree, as dxc's
|
|
||||||
//! EarlyCSE and GVN do it: an instruction that computes what one in a
|
|
||||||
//! dominating position already computed (same operation, same operands)
|
|
||||||
//! is replaced by it. Only instructions without effects and whose result
|
|
||||||
//! depends on nothing but their operands: arithmetic, comparisons, casts,
|
|
||||||
//! selects, address computations, readnone dx.op calls, and the readonly
|
|
||||||
//! ones that read what cannot change during the shader (constant buffer
|
|
||||||
//! loads, handle creation).
|
|
||||||
//!
|
|
||||||
//! Inlining every call and lowering each use of a cbuffer field to its own
|
|
||||||
//! load leaves many such repeats.
|
|
||||||
|
|
||||||
const std = @import("std");
|
|
||||||
const Allocator = std.mem.Allocator;
|
|
||||||
const module = @import("module.zig");
|
|
||||||
const promote = @import("promote.zig");
|
|
||||||
const stats = @import("../stats.zig");
|
|
||||||
|
|
||||||
const Value = module.Value;
|
|
||||||
const Inst = module.Inst;
|
|
||||||
|
|
||||||
const none = std.math.maxInt(u32);
|
|
||||||
|
|
||||||
fn isTerminator(inst: Inst) bool {
|
|
||||||
return switch (inst.op) {
|
|
||||||
.ret, .br, .@"switch", .@"unreachable" => true,
|
|
||||||
else => false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// dx.op readonly operations that read only what a dispatch cannot change:
|
|
||||||
/// CreateHandle, CBufferLoad, CBufferLoadLegacy, CreateHandleForLib,
|
|
||||||
/// CreateHandleFromBinding, CreateHandleFromHeap.
|
|
||||||
fn stableReadonly(opcode: i64) bool {
|
|
||||||
return switch (opcode) {
|
|
||||||
57, 58, 59, 160, 217, 218 => true,
|
|
||||||
else => false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
fn eligible(m: *const module.Module, inst: Inst) bool {
|
|
||||||
return switch (inst.op) {
|
|
||||||
.binop, .cast, .cmp, .select, .extractvalue, .gep, .extractelement, .insertelement => true,
|
|
||||||
.call => |c| {
|
|
||||||
const callee = m.functions.items[c.callee];
|
|
||||||
if (callee.num_blocks != 0 or !std.mem.startsWith(u8, callee.name, "dx.op.")) return false;
|
|
||||||
switch (callee.attrs) {
|
|
||||||
.nounwind_readnone => return true,
|
|
||||||
.nounwind_readonly => {
|
|
||||||
if (c.args.len == 0 or c.args[0] != .constant) return false;
|
|
||||||
return switch (m.constants.items[c.args[0].constant].kind) {
|
|
||||||
.int => |k| stableReadonly(k),
|
|
||||||
else => false,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
else => return false,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
else => false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An instruction's identity as bytes: its operation, type, the fields
|
|
||||||
/// that are not operands, and its operands (resolved through replaced
|
|
||||||
/// instructions).
|
|
||||||
const Key = struct {
|
|
||||||
buf: std.ArrayList(u8) = .empty,
|
|
||||||
a: Allocator,
|
|
||||||
repl: []const ?Value,
|
|
||||||
failed: bool = false,
|
|
||||||
|
|
||||||
fn resolve(k: *const Key, v: Value) Value {
|
|
||||||
var x = v;
|
|
||||||
while (x == .inst) {
|
|
||||||
const r = k.repl[x.inst] orelse break;
|
|
||||||
x = r;
|
|
||||||
}
|
|
||||||
return x;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn word(k: *Key, w: u64) void {
|
|
||||||
k.buf.appendSlice(k.a, std.mem.asBytes(&w)) catch {
|
|
||||||
k.failed = true;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn visit(k: *Key, v: Value, _: promote.Role) Value {
|
|
||||||
const x = k.resolve(v);
|
|
||||||
const tag: u64 = @backingInt(std.meta.activeTag(x));
|
|
||||||
const id: u64 = switch (x) {
|
|
||||||
inline else => |i| i,
|
|
||||||
};
|
|
||||||
k.word(tag << 32 | id);
|
|
||||||
return v;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn build(k: *Key, inst: Inst) Allocator.Error![]const u8 {
|
|
||||||
k.buf.clearRetainingCapacity();
|
|
||||||
k.word(@backingInt(std.meta.activeTag(inst.op)));
|
|
||||||
k.word(inst.ty);
|
|
||||||
switch (inst.op) {
|
|
||||||
.binop => |b| k.word(@as(u64, @backingInt(b.op)) << 32 | b.flags),
|
|
||||||
.cast => |c| k.word(@backingInt(c.op)),
|
|
||||||
.cmp => |c| k.word(c.pred),
|
|
||||||
.extractvalue => |x| k.word(x.index),
|
|
||||||
.gep => |g| k.word(g.elem),
|
|
||||||
.call => |c| k.word(c.callee),
|
|
||||||
else => {},
|
|
||||||
}
|
|
||||||
var copy = inst;
|
|
||||||
try promote.operands(false, k.a, ©, k);
|
|
||||||
if (k.failed) return error.OutOfMemory;
|
|
||||||
return k.buf.items;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Replaces `func`'s repeated computations; true if any.
|
|
||||||
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
|
|
||||||
const zone = stats.begin(.cse);
|
|
||||||
defer zone.end();
|
|
||||||
const f = &m.functions.items[func];
|
|
||||||
const insts = f.insts.items;
|
|
||||||
const n: u32 = @intCast(insts.len);
|
|
||||||
const nb = f.num_blocks;
|
|
||||||
if (n == 0 or nb == 0) return false;
|
|
||||||
|
|
||||||
const block_start = try a.alloc(u32, nb + 1);
|
|
||||||
{
|
|
||||||
var b: u32 = 0;
|
|
||||||
block_start[0] = 0;
|
|
||||||
for (insts, 0..) |inst, i| if (isTerminator(inst)) {
|
|
||||||
if (b >= nb) return false;
|
|
||||||
b += 1;
|
|
||||||
block_start[b] = @intCast(i + 1);
|
|
||||||
};
|
|
||||||
if (b != nb or block_start[nb] != n) return false;
|
|
||||||
}
|
|
||||||
// Successors, predecessors.
|
|
||||||
const succ_off = try a.alloc(u32, nb + 1);
|
|
||||||
var succs: std.ArrayList(u32) = .empty;
|
|
||||||
for (0..nb) |b| {
|
|
||||||
succ_off[b] = @intCast(succs.items.len);
|
|
||||||
switch (insts[block_start[b + 1] - 1].op) {
|
|
||||||
.br => |br| {
|
|
||||||
try succs.append(a, br.then);
|
|
||||||
if (br.@"else") |e| try succs.append(a, e);
|
|
||||||
},
|
|
||||||
.@"switch" => |sw| {
|
|
||||||
try succs.append(a, sw.default);
|
|
||||||
for (sw.cases) |c| try succs.append(a, c.block);
|
|
||||||
},
|
|
||||||
else => {},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
succ_off[nb] = @intCast(succs.items.len);
|
|
||||||
const pred_off = try a.alloc(u32, nb + 1);
|
|
||||||
@memset(pred_off, 0);
|
|
||||||
for (succs.items) |s| pred_off[s + 1] += 1;
|
|
||||||
for (1..nb + 1) |b| pred_off[b] += pred_off[b - 1];
|
|
||||||
const preds = try a.alloc(u32, succs.items.len);
|
|
||||||
{
|
|
||||||
const fill = try a.dupe(u32, pred_off[0..nb]);
|
|
||||||
for (0..nb) |b| for (succs.items[succ_off[b]..succ_off[b + 1]]) |s| {
|
|
||||||
preds[fill[s]] = @intCast(b);
|
|
||||||
fill[s] += 1;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
// Reverse postorder, then immediate dominators (Cooper, Harvey and
|
|
||||||
// Kennedy).
|
|
||||||
const rpo_index = try a.alloc(u32, nb);
|
|
||||||
@memset(rpo_index, none);
|
|
||||||
const rpo = try a.alloc(u32, nb);
|
|
||||||
var nr: u32 = 0;
|
|
||||||
{
|
|
||||||
const post = try a.alloc(u32, nb);
|
|
||||||
var np: u32 = 0;
|
|
||||||
const seen = try a.alloc(bool, nb);
|
|
||||||
@memset(seen, false);
|
|
||||||
const Frame = struct { b: u32, next: u32 };
|
|
||||||
var stack: std.ArrayList(Frame) = .empty;
|
|
||||||
try stack.append(a, .{ .b = 0, .next = succ_off[0] });
|
|
||||||
seen[0] = true;
|
|
||||||
while (stack.items.len > 0) {
|
|
||||||
const top = &stack.items[stack.items.len - 1];
|
|
||||||
if (top.next < succ_off[top.b + 1]) {
|
|
||||||
const s = succs.items[top.next];
|
|
||||||
top.next += 1;
|
|
||||||
if (!seen[s]) {
|
|
||||||
seen[s] = true;
|
|
||||||
try stack.append(a, .{ .b = s, .next = succ_off[s] });
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
post[np] = top.b;
|
|
||||||
np += 1;
|
|
||||||
_ = stack.pop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (0..np) |k| {
|
|
||||||
rpo[k] = post[np - 1 - k];
|
|
||||||
rpo_index[rpo[k]] = @intCast(k);
|
|
||||||
}
|
|
||||||
nr = np;
|
|
||||||
}
|
|
||||||
const idom = try a.alloc(u32, nb);
|
|
||||||
@memset(idom, none);
|
|
||||||
idom[0] = 0;
|
|
||||||
{
|
|
||||||
var changed = true;
|
|
||||||
while (changed) {
|
|
||||||
changed = false;
|
|
||||||
for (rpo[1..nr]) |b| {
|
|
||||||
var new: u32 = none;
|
|
||||||
for (preds[pred_off[b]..pred_off[b + 1]]) |p| {
|
|
||||||
if (idom[p] == none) continue;
|
|
||||||
if (new == none) {
|
|
||||||
new = p;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
var x = p;
|
|
||||||
var y = new;
|
|
||||||
while (x != y) {
|
|
||||||
while (rpo_index[x] > rpo_index[y]) x = idom[x];
|
|
||||||
while (rpo_index[y] > rpo_index[x]) y = idom[y];
|
|
||||||
}
|
|
||||||
new = x;
|
|
||||||
}
|
|
||||||
if (new != idom[b]) {
|
|
||||||
idom[b] = new;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Dominator tree children, in reverse postorder.
|
|
||||||
const child_off = try a.alloc(u32, nb + 1);
|
|
||||||
@memset(child_off, 0);
|
|
||||||
for (rpo[1..nr]) |b| child_off[idom[b] + 1] += 1;
|
|
||||||
for (1..nb + 1) |b| child_off[b] += child_off[b - 1];
|
|
||||||
const children = try a.alloc(u32, if (nr > 0) nr - 1 else 0);
|
|
||||||
{
|
|
||||||
const fill = try a.dupe(u32, child_off[0..nb]);
|
|
||||||
for (rpo[1..nr]) |b| {
|
|
||||||
children[fill[idom[b]]] = b;
|
|
||||||
fill[idom[b]] += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const repl = try a.alloc(?Value, n);
|
|
||||||
@memset(repl, null);
|
|
||||||
// The keys of the instructions available (in the dominating blocks),
|
|
||||||
// to the instruction.
|
|
||||||
var table: std.StringHashMapUnmanaged(u32) = .empty;
|
|
||||||
var added: std.ArrayList([]const u8) = .empty;
|
|
||||||
var key: Key = .{ .a = a, .repl = repl };
|
|
||||||
var found = false;
|
|
||||||
|
|
||||||
const Frame = struct { b: u32, next: u32, mark: usize };
|
|
||||||
var stack: std.ArrayList(Frame) = .empty;
|
|
||||||
try stack.append(a, .{ .b = 0, .next = child_off[0], .mark = 0 });
|
|
||||||
var entered = true;
|
|
||||||
while (stack.items.len > 0) {
|
|
||||||
const top = &stack.items[stack.items.len - 1];
|
|
||||||
if (entered) {
|
|
||||||
entered = false;
|
|
||||||
top.mark = added.items.len;
|
|
||||||
for (block_start[top.b]..block_start[top.b + 1]) |i| {
|
|
||||||
const inst = insts[i];
|
|
||||||
if (!eligible(m, inst)) continue;
|
|
||||||
// (The key is built in one buffer, and kept only if new.)
|
|
||||||
const gop = try table.getOrPut(a, try key.build(inst));
|
|
||||||
if (gop.found_existing) {
|
|
||||||
repl[i] = .{ .inst = gop.value_ptr.* };
|
|
||||||
found = true;
|
|
||||||
} else {
|
|
||||||
gop.key_ptr.* = try a.dupe(u8, key.buf.items);
|
|
||||||
gop.value_ptr.* = @intCast(i);
|
|
||||||
try added.append(a, gop.key_ptr.*);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (top.next < child_off[top.b + 1]) {
|
|
||||||
const c = children[top.next];
|
|
||||||
top.next += 1;
|
|
||||||
try stack.append(a, .{ .b = c, .next = child_off[c], .mark = 0 });
|
|
||||||
entered = true;
|
|
||||||
} else {
|
|
||||||
for (added.items[top.mark..]) |k| _ = table.remove(k);
|
|
||||||
added.shrinkRetainingCapacity(top.mark);
|
|
||||||
_ = stack.pop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!found) return false;
|
|
||||||
|
|
||||||
// Renumber without the replaced instructions.
|
|
||||||
const index = try a.alloc(u32, n);
|
|
||||||
var count: u32 = 0;
|
|
||||||
for (0..n) |i| {
|
|
||||||
index[i] = count;
|
|
||||||
if (repl[i] == null) count += 1;
|
|
||||||
}
|
|
||||||
const Map = struct {
|
|
||||||
repl: []const ?Value,
|
|
||||||
index: []const u32,
|
|
||||||
pub fn visit(ctx: *@This(), v: Value, _: promote.Role) Value {
|
|
||||||
var x = v;
|
|
||||||
while (x == .inst) {
|
|
||||||
const r = ctx.repl[x.inst] orelse break;
|
|
||||||
x = r;
|
|
||||||
}
|
|
||||||
return if (x == .inst) .{ .inst = ctx.index[x.inst] } else x;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
var map: Map = .{ .repl = repl, .index = index };
|
|
||||||
const ma = m.allocator();
|
|
||||||
var out: std.ArrayList(Inst) = .empty;
|
|
||||||
try out.ensureTotalCapacityPrecise(ma, count);
|
|
||||||
for (insts, 0..) |inst, i| {
|
|
||||||
if (repl[i] != null) continue;
|
|
||||||
var copy = inst;
|
|
||||||
try promote.operands(true, ma, ©, &map);
|
|
||||||
out.appendAssumeCapacity(copy);
|
|
||||||
}
|
|
||||||
f.insts = out;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
@ -28,8 +28,6 @@ const promote = @import("promote.zig");
|
||||||
const unroll = @import("unroll.zig");
|
const unroll = @import("unroll.zig");
|
||||||
const stats = @import("../stats.zig");
|
const stats = @import("../stats.zig");
|
||||||
const sccp = @import("sccp.zig");
|
const sccp = @import("sccp.zig");
|
||||||
const cfg = @import("cfg.zig");
|
|
||||||
const cse = @import("cse.zig");
|
|
||||||
const opt = @import("../ir/opt.zig");
|
const opt = @import("../ir/opt.zig");
|
||||||
|
|
||||||
const TypeId = types.TypeId;
|
const TypeId = types.TypeId;
|
||||||
|
|
@ -55,18 +53,9 @@ pub fn emit(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags:
|
||||||
pub const Output = struct { object: []u8, reflection: []u8 };
|
pub const Output = struct { object: []u8, reflection: []u8 };
|
||||||
|
|
||||||
pub fn emitWithReflection(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, optimize: bool) Error!Output {
|
pub fn emitWithReflection(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, optimize: bool) Error!Output {
|
||||||
return emitWithReflectionAt(gpa, m, profile, diags, if (optimize) .full else .none);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How much `emitWithReflectionAt` optimizes: nothing (-zdxc-no-opt), as
|
|
||||||
/// dxc's -Od does (locals promoted to SSA values and what that leaves
|
|
||||||
/// dead removed, nothing else), or fully.
|
|
||||||
pub const Optimize = enum { none, debug, full };
|
|
||||||
|
|
||||||
pub fn emitWithReflectionAt(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, level: Optimize) Error!Output {
|
|
||||||
var arena_state: BumpArena = .init(gpa);
|
var arena_state: BumpArena = .init(gpa);
|
||||||
defer arena_state.deinit();
|
defer arena_state.deinit();
|
||||||
var e: Emitter = .{ .arena = arena_state.allocator(), .dm = .init(gpa), .m = m, .t = m.types, .profile = profile, .diags = diags, .optimize = level == .full, .promote_only = level == .debug };
|
var e: Emitter = .{ .arena = arena_state.allocator(), .dm = .init(gpa), .m = m, .t = m.types, .profile = profile, .diags = diags, .optimize = optimize };
|
||||||
defer e.dm.deinit();
|
defer e.dm.deinit();
|
||||||
// Native 16-bit types are laid out at their own size.
|
// Native 16-bit types are laid out at their own size.
|
||||||
if (m.native_16bit) e.dm.datalayout = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-f16:16-f32:32-f64:64-n8:16:32:64";
|
if (m.native_16bit) e.dm.datalayout = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-f16:16-f32:32-f64:64-n8:16:32:64";
|
||||||
|
|
@ -100,8 +89,6 @@ const Lowered = union(enum) {
|
||||||
/// A local assigned different elements of one resource array (index
|
/// A local assigned different elements of one resource array (index
|
||||||
/// into Emitter.res_index_locals): it holds the element's index.
|
/// into Emitter.res_index_locals): it holds the element's index.
|
||||||
res_index_local: u32,
|
res_index_local: u32,
|
||||||
/// A work graph node input or output, or a node's records.
|
|
||||||
node: NodeVal,
|
|
||||||
/// A RayQuery local (index into Emitter.rq_locals) and a query handle.
|
/// A RayQuery local (index into Emitter.rq_locals) and a query handle.
|
||||||
rq_local: u32,
|
rq_local: u32,
|
||||||
ray_query: Value,
|
ray_query: Value,
|
||||||
|
|
@ -134,11 +121,6 @@ const Lowered = union(enum) {
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// A node object: its handle (%dx.types.NodeHandle for outputs,
|
|
||||||
/// %dx.types.NodeRecordHandle for records), annotated with `flags`
|
|
||||||
/// (NodeIOFlags) and the record's size.
|
|
||||||
const NodeVal = struct { kind: types.NodeKind, handle: Value, record: TypeId, flags: u32, size: u32 };
|
|
||||||
|
|
||||||
/// Pointer into a flattened local: alloca `base` of `[n x scalar]`, at
|
/// Pointer into a flattened local: alloca `base` of `[n x scalar]`, at
|
||||||
/// component `offset_const` (+ `offset_dyn` if dynamic).
|
/// component `offset_const` (+ `offset_dyn` if dynamic).
|
||||||
const Ptr = struct {
|
const Ptr = struct {
|
||||||
|
|
@ -348,8 +330,6 @@ const Emitter = struct {
|
||||||
dyn_ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty,
|
dyn_ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty,
|
||||||
/// See `emit`.
|
/// See `emit`.
|
||||||
optimize: bool = true,
|
optimize: bool = true,
|
||||||
/// -Od: only promotion runs on the finished functions.
|
|
||||||
promote_only: bool = false,
|
|
||||||
/// Arrays of inlined callees that have returned, by type, for later
|
/// Arrays of inlined callees that have returned, by type, for later
|
||||||
/// callees' locals of that type (per function).
|
/// callees' locals of that type (per function).
|
||||||
array_pool: std.AutoHashMapUnmanaged(TypeId, std.ArrayList(Ptr)) = .empty,
|
array_pool: std.AutoHashMapUnmanaged(TypeId, std.ArrayList(Ptr)) = .empty,
|
||||||
|
|
@ -747,8 +727,6 @@ const Emitter = struct {
|
||||||
/// Graphics entries: signatures; entry properties of the stage.
|
/// Graphics entries: signatures; entry properties of the stage.
|
||||||
sigs: ?module.MdId = null,
|
sigs: ?module.MdId = null,
|
||||||
stage_props: []const ?module.MdId = &.{},
|
stage_props: []const ?module.MdId = &.{},
|
||||||
/// Groupshared memory the entry uses (bytes).
|
|
||||||
groupshared: u32 = 0,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Input qualifier (0 in, 1 out, 2 inout), component type and
|
/// Input qualifier (0 in, 1 out, 2 inout), component type and
|
||||||
|
|
@ -772,7 +750,6 @@ const Emitter = struct {
|
||||||
.callable => 12,
|
.callable => 12,
|
||||||
.mesh => 13,
|
.mesh => 13,
|
||||||
.amplification => 14,
|
.amplification => 14,
|
||||||
.node => 15,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -802,7 +779,7 @@ const Emitter = struct {
|
||||||
var units: std.ArrayList(Unit) = .empty;
|
var units: std.ArrayList(Unit) = .empty;
|
||||||
for (m.entries.items, 0..) |entry, k| {
|
for (m.entries.items, 0..) |entry, k| {
|
||||||
switch (entry.stage) {
|
switch (entry.stage) {
|
||||||
.compute, .raygeneration, .intersection, .anyhit, .closesthit, .miss, .callable, .vertex, .pixel, .geometry, .hull, .domain, .mesh, .amplification, .node => {},
|
.compute, .raygeneration, .intersection, .anyhit, .closesthit, .miss, .callable, .vertex, .pixel, .geometry, .hull, .domain, .mesh, .amplification => {},
|
||||||
else => return e.unsupported("{s} shaders in libraries are not supported yet", .{@tagName(entry.stage)}),
|
else => return e.unsupported("{s} shaders in libraries are not supported yet", .{@tagName(entry.stage)}),
|
||||||
}
|
}
|
||||||
try units.append(e.arena, .{ .order = m.functions.items[entry.func].decl_order, .kind = .entry, .index = @intCast(k) });
|
try units.append(e.arena, .{ .order = m.functions.items[entry.func].decl_order, .kind = .entry, .index = @intCast(k) });
|
||||||
|
|
@ -878,7 +855,6 @@ const Emitter = struct {
|
||||||
try e.libHandles();
|
try e.libHandles();
|
||||||
_ = try e.inlineCall(entry.wrapper, &.{});
|
_ = try e.inlineCall(entry.wrapper, &.{});
|
||||||
try e.finish(lf.func);
|
try e.finish(lf.func);
|
||||||
lf.groupshared = e.groupshared_bytes;
|
|
||||||
var pc_func: ?LibFunc = null;
|
var pc_func: ?LibFunc = null;
|
||||||
if (entry.patch_wrapper) |pw| {
|
if (entry.patch_wrapper) |pw| {
|
||||||
// The patch constant function: a function of its own.
|
// The patch constant function: a function of its own.
|
||||||
|
|
@ -1414,7 +1390,7 @@ const Emitter = struct {
|
||||||
switch (e.entry.stage) {
|
switch (e.entry.stage) {
|
||||||
// (Library functions record the use; their callers decide.)
|
// (Library functions record the use; their callers decide.)
|
||||||
.pixel, .library => {},
|
.pixel, .library => {},
|
||||||
.compute, .mesh, .amplification, .node => if (e.profile.minor < 6) return e.unsupported("derivatives outside pixel shaders need shader model 6.6", .{}),
|
.compute, .mesh, .amplification => if (e.profile.minor < 6) return e.unsupported("derivatives outside pixel shaders need shader model 6.6", .{}),
|
||||||
else => return e.unsupported("derivatives are not available in {s} shaders", .{@tagName(e.entry.stage)}),
|
else => return e.unsupported("derivatives are not available in {s} shaders", .{@tagName(e.entry.stage)}),
|
||||||
}
|
}
|
||||||
if (e.entry.stage == .mesh or e.entry.stage == .amplification) e.uses_mesh_derivatives = true;
|
if (e.entry.stage == .mesh or e.entry.stage == .amplification) e.uses_mesh_derivatives = true;
|
||||||
|
|
@ -1566,17 +1542,6 @@ const Emitter = struct {
|
||||||
try promote.run(e.arena, &e.dm, func, &.empty);
|
try promote.run(e.arena, &e.dm, func, &.empty);
|
||||||
if (e.dm.functions.items[func].insts.items.len == before) break;
|
if (e.dm.functions.items[func].insts.items.len == before) break;
|
||||||
}
|
}
|
||||||
// Repeated computations, then blocks that only branch on:
|
|
||||||
// merged, bypassed, and if-converted.
|
|
||||||
// (What that leaves dead, or folds, and the blocks that leaves
|
|
||||||
// empty: again, until nothing changes.)
|
|
||||||
_ = try cse.run(e.arena, &e.dm, func);
|
|
||||||
var passes: u32 = 0;
|
|
||||||
while (passes < 3 and try cfg.run(e.arena, &e.dm, func)) : (passes += 1) {
|
|
||||||
try promote.run(e.arena, &e.dm, func, &.empty);
|
|
||||||
}
|
|
||||||
} else if (e.promote_only) {
|
|
||||||
try promote.run(e.arena, &e.dm, func, &ranges);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2171,16 +2136,7 @@ const Emitter = struct {
|
||||||
_ = try e.add(void_ty, .{ .br = .{ .then = cont } });
|
_ = try e.add(void_ty, .{ .br = .{ .then = cont } });
|
||||||
} else _ = try e.add(void_ty, .{ .ret = null });
|
} else _ = try e.add(void_ty, .{ .ret = null });
|
||||||
},
|
},
|
||||||
.br => |t| {
|
.br => |t| _ = try e.add(void_ty, .{ .br = .{ .then = try e.blockFor(frame, t.index()) } }),
|
||||||
const br = try e.add(void_ty, .{ .br = .{ .then = try e.blockFor(frame, t.index()) } });
|
|
||||||
// An `[unroll]` loop's back edge: marked for the unroller.
|
|
||||||
switch (f.blocks.items[t.index()].merge) {
|
|
||||||
.loop => |l| if (l.unroll == .unroll and l.@"continue".index() == bi) {
|
|
||||||
e.insts.at(br.inst).md = .unroll;
|
|
||||||
},
|
|
||||||
else => {},
|
|
||||||
}
|
|
||||||
},
|
|
||||||
.cond_br => |c| {
|
.cond_br => |c| {
|
||||||
const cond = (try e.scalars(frame, c.cond))[0];
|
const cond = (try e.scalars(frame, c.cond))[0];
|
||||||
if (frame.taken.len > 0) if (e.constIntOf(cond)) |k| {
|
if (frame.taken.len > 0) if (e.constIntOf(cond)) |k| {
|
||||||
|
|
@ -2277,7 +2233,6 @@ const Emitter = struct {
|
||||||
.constant => |c| return e.list(&.{try e.constant(i.ty, c)}),
|
.constant => |c| return e.list(&.{try e.constant(i.ty, c)}),
|
||||||
.param => |p| return frame.params[p],
|
.param => |p| return frame.params[p],
|
||||||
.spec_constant => return e.unsupported("specialization constants outside SPIR-V", .{}),
|
.spec_constant => return e.unsupported("specialization constants outside SPIR-V", .{}),
|
||||||
.node_io => |x| return e.nodeIo(x),
|
|
||||||
.spirv_inst => return e.unsupported("inline SPIR-V outside SPIR-V", .{}),
|
.spirv_inst => return e.unsupported("inline SPIR-V outside SPIR-V", .{}),
|
||||||
.ray_incoming => |k| {
|
.ray_incoming => |k| {
|
||||||
// The shader's payload / attribute / parameter argument.
|
// The shader's payload / attribute / parameter argument.
|
||||||
|
|
@ -2517,12 +2472,10 @@ const Emitter = struct {
|
||||||
if (frame.vals[s.ptr.index()] == .res_local) {
|
if (frame.vals[s.ptr.index()] == .res_local) {
|
||||||
const slot = &e.res_locals.items[frame.vals[s.ptr.index()].res_local];
|
const slot = &e.res_locals.items[frame.vals[s.ptr.index()].res_local];
|
||||||
const h = frame.vals[s.value.index()];
|
const h = frame.vals[s.value.index()];
|
||||||
if (h != .handle and h != .res_array and h != .node) return e.unsupported("resources not tied to a global are not supported yet", .{});
|
if (h != .handle and h != .res_array) return e.unsupported("resources not tied to a global are not supported yet", .{});
|
||||||
// Selecting between resources at run time has no
|
// Selecting between resources at run time has no
|
||||||
// handle-based lowering here; one assignment is fine.
|
// handle-based lowering here; one assignment is fine.
|
||||||
// (Node objects: again, where every assignment is in
|
if (slot.*) |old| if (!std.meta.eql(old, h)) return e.unsupported("assigning different resources to one variable is not supported yet (in '{s}')", .{frame.f.name});
|
||||||
// one block.)
|
|
||||||
if (slot.*) |old| if (!std.meta.eql(old, h) and !(h == .node and storesInOneBlock(f, s.ptr))) return e.unsupported("assigning different resources to one variable is not supported yet (in '{s}')", .{frame.f.name});
|
|
||||||
slot.* = h;
|
slot.* = h;
|
||||||
return .none;
|
return .none;
|
||||||
}
|
}
|
||||||
|
|
@ -2562,17 +2515,6 @@ const Emitter = struct {
|
||||||
},
|
},
|
||||||
.access => |a| {
|
.access => |a| {
|
||||||
if (frame.vals[a.base.index()] == .mesh) return e.meshAccess(frame, frame.vals[a.base.index()].mesh, a.indices);
|
if (frame.vals[a.base.index()] == .mesh) return e.meshAccess(frame, frame.vals[a.base.index()].mesh, a.indices);
|
||||||
if (frame.vals[a.base.index()] == .node) {
|
|
||||||
const nv = frame.vals[a.base.index()].node;
|
|
||||||
const idx = (try e.scalars(frame, a.indices[0]))[0];
|
|
||||||
if (nv.kind.outputElement()) |k| {
|
|
||||||
if (a.indices.len > 1) return e.unsupported("indexing a node output", .{});
|
|
||||||
return .{ .node = try e.nodeIndex(nv, k, idx) };
|
|
||||||
}
|
|
||||||
const tp = try e.nodeRecordPtr(nv, idx);
|
|
||||||
if (a.indices.len == 1) return .{ .typed = tp };
|
|
||||||
return .{ .typed = try e.typedAccess(frame, tp, a.indices[1..]) };
|
|
||||||
}
|
|
||||||
if (frame.vals[a.base.index()] == .typed) {
|
if (frame.vals[a.base.index()] == .typed) {
|
||||||
var tp = frame.vals[a.base.index()].typed;
|
var tp = frame.vals[a.base.index()].typed;
|
||||||
var path: std.ArrayList(Value) = .empty;
|
var path: std.ArrayList(Value) = .empty;
|
||||||
|
|
@ -2856,7 +2798,6 @@ const Emitter = struct {
|
||||||
fn resCount(e: *Emitter, ty: TypeId) u32 {
|
fn resCount(e: *Emitter, ty: TypeId) u32 {
|
||||||
return switch (e.t.get(ty)) {
|
return switch (e.t.get(ty)) {
|
||||||
.resource, .sampler => if (isRayQuery(e.t, ty)) 0 else 1,
|
.resource, .sampler => if (isRayQuery(e.t, ty)) 0 else 1,
|
||||||
.node => 1,
|
|
||||||
.array => |a| a.len * e.resCount(a.elem),
|
.array => |a| a.len * e.resCount(a.elem),
|
||||||
.@"struct" => |st| blk: {
|
.@"struct" => |st| blk: {
|
||||||
var n: u32 = 0;
|
var n: u32 = 0;
|
||||||
|
|
@ -2903,7 +2844,7 @@ const Emitter = struct {
|
||||||
return switch (v) {
|
return switch (v) {
|
||||||
.agg => |a| a,
|
.agg => |a| a,
|
||||||
.scalars => |vals| if (e.resCount(ty) == 0) .{ .vals = vals, .res = &.{} } else e.unsupported("this value with resources is not supported yet", .{}),
|
.scalars => |vals| if (e.resCount(ty) == 0) .{ .vals = vals, .res = &.{} } else e.unsupported("this value with resources is not supported yet", .{}),
|
||||||
.handle, .res_array, .node => .{ .vals = &.{}, .res = try e.arena.dupe(Lowered, &.{v}) },
|
.handle, .res_array => .{ .vals = &.{}, .res = try e.arena.dupe(Lowered, &.{v}) },
|
||||||
.none => .{ .vals = &.{}, .res = &.{} },
|
.none => .{ .vals = &.{}, .res = &.{} },
|
||||||
else => e.unsupported("this value with resources is not supported yet", .{}),
|
else => e.unsupported("this value with resources is not supported yet", .{}),
|
||||||
};
|
};
|
||||||
|
|
@ -3333,34 +3274,6 @@ const Emitter = struct {
|
||||||
_ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(168), (try e.scalars(frame, args[0]))[0], (try e.scalars(frame, args[1]))[0] });
|
_ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(168), (try e.scalars(frame, args[0]))[0], (try e.scalars(frame, args[1]))[0] });
|
||||||
return .none;
|
return .none;
|
||||||
}
|
}
|
||||||
// SM 6.8's Barrier(memory types or a UAV, semantics): the
|
|
||||||
// arguments as they are (as dxc).
|
|
||||||
if (eq(u8, name, "GetRemainingRecursionLevels") and args.len == 0) {
|
|
||||||
const i32t = try e.dm.intType(32);
|
|
||||||
const fn_i = try e.dxOp("dx.op.getRemainingRecursionLevels", i32t, &.{i32t}, .nounwind_readonly);
|
|
||||||
return e.list(&.{try e.callOp(fn_i, i32t, &.{try e.i32Const(253)})});
|
|
||||||
}
|
|
||||||
if (eq(u8, name, "Barrier") and args.len == 2) {
|
|
||||||
const i32t = try e.dm.intType(32);
|
|
||||||
const sem = (try e.scalars(frame, args[1]))[0];
|
|
||||||
switch (frame.vals[args[0].index()]) {
|
|
||||||
.handle => |h| {
|
|
||||||
const fn_i = try e.dxOp("dx.op.barrierByMemoryHandle", try e.voidTy(), &.{ i32t, e.handle_ty, i32t }, .noduplicate_nounwind);
|
|
||||||
_ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(245), e.resources.items[h].handle, sem });
|
|
||||||
},
|
|
||||||
.scalars => |m| {
|
|
||||||
const fn_i = try e.dxOp("dx.op.barrierByMemoryType", try e.voidTy(), &.{ i32t, i32t, i32t }, .noduplicate_nounwind);
|
|
||||||
_ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(244), m[0], sem });
|
|
||||||
},
|
|
||||||
.node => |nv| {
|
|
||||||
const nt = try e.nodeTypes();
|
|
||||||
const fn_i = try e.dxOp("dx.op.barrierByNodeRecordHandle", try e.voidTy(), &.{ i32t, nt.record_handle, i32t }, .noduplicate_nounwind);
|
|
||||||
_ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(246), nv.handle, sem });
|
|
||||||
},
|
|
||||||
else => return e.unsupported("Barrier on this object is not supported yet", .{}),
|
|
||||||
}
|
|
||||||
return .none;
|
|
||||||
}
|
|
||||||
for (args) |x| if (frame.vals[x.index()] != .scalars) return e.unsupported("intrinsic '{s}' is not supported yet", .{name});
|
for (args) |x| if (frame.vals[x.index()] != .scalars) return e.unsupported("intrinsic '{s}' is not supported yet", .{name});
|
||||||
var a: [4][]const Value = undefined;
|
var a: [4][]const Value = undefined;
|
||||||
for (args, 0..) |x, k| a[k] = try e.scalars(frame, x);
|
for (args, 0..) |x, k| a[k] = try e.scalars(frame, x);
|
||||||
|
|
@ -3725,37 +3638,23 @@ const Emitter = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Interlocked*(dest, value(s) [, out original]) on groupshared memory,
|
/// Interlocked*(dest, value(s) [, out original]) on groupshared memory,
|
||||||
/// node records, buffer elements and texels. (The *FloatBitwise
|
/// buffer elements and texels.
|
||||||
/// compares: on the floats' bits.)
|
|
||||||
fn atomic(e: *Emitter, frame: *Frame, name: []const u8, args: []const Ref) Error!Lowered {
|
fn atomic(e: *Emitter, frame: *Frame, name: []const u8, args: []const Ref) Error!Lowered {
|
||||||
const eq = std.mem.eql;
|
const eq = std.mem.eql;
|
||||||
const op_name = name["Interlocked".len..];
|
const op_name = name["Interlocked".len..];
|
||||||
const dest_ty = frame.f.inst(args[0]).ty;
|
const dest_ty = frame.f.inst(args[0]).ty;
|
||||||
const float_bits = std.mem.endsWith(u8, op_name, "FloatBitwise");
|
const dc = e.compOf(dest_ty);
|
||||||
const dc: Scalar = if (float_bits and e.compOf(dest_ty) == .float) .uint else e.compOf(dest_ty);
|
|
||||||
const wide = dc.size() == 8 and !dc.isFloat() and (frame.vals[args[0].index()] == .buf or frame.vals[args[0].index()] == .texel);
|
const wide = dc.size() == 8 and !dc.isFloat() and (frame.vals[args[0].index()] == .buf or frame.vals[args[0].index()] == .texel);
|
||||||
if ((dc.size() != 4 and !wide) or dc.isFloat()) return e.unsupported("'{s}' on '{s}' is not supported yet", .{ name, try e.t.format(e.arena, dest_ty) });
|
if ((dc.size() != 4 and !wide) or dc.isFloat()) return e.unsupported("'{s}' on '{s}' is not supported yet", .{ name, try e.t.format(e.arena, dest_ty) });
|
||||||
const i32t = try e.dm.intType(32);
|
const i32t = try e.dm.intType(32);
|
||||||
const is_cmp = std.mem.startsWith(u8, op_name, "Compare");
|
const is_cmp = std.mem.startsWith(u8, op_name, "Compare");
|
||||||
const has_orig = (is_cmp and std.mem.startsWith(u8, op_name, "CompareExchange")) or (!is_cmp and args.len == 3);
|
const has_orig = (is_cmp and eq(u8, op_name, "CompareExchange")) or (!is_cmp and args.len == 3);
|
||||||
const val = try e.atomicOperand(float_bits, (try e.scalars(frame, args[if (is_cmp) 2 else 1]))[0]);
|
const val = (try e.scalars(frame, args[if (is_cmp) 2 else 1]))[0];
|
||||||
const cmp = if (is_cmp) try e.atomicOperand(float_bits, (try e.scalars(frame, args[1]))[0]) else null;
|
const cmp = if (is_cmp) (try e.scalars(frame, args[1]))[0] else null;
|
||||||
const orig: Value = switch (frame.vals[args[0].index()]) {
|
const orig: Value = switch (frame.vals[args[0].index()]) {
|
||||||
.ptr, .typed => blk: {
|
.ptr => |p| blk: {
|
||||||
const tag = std.meta.activeTag(frame.vals[args[0].index()]);
|
if (p.addr_space != 3) return e.unsupported("'{s}' on this variable is not supported yet", .{name});
|
||||||
var ptr = if (tag == .ptr) p: {
|
const ptr = try e.elementPtr(p, 0);
|
||||||
const p = frame.vals[args[0].index()].ptr;
|
|
||||||
if (p.addr_space != 3) return e.unsupported("'{s}' on this variable is not supported yet", .{name});
|
|
||||||
break :p try e.elementPtr(p, 0);
|
|
||||||
} else p: {
|
|
||||||
const tp = frame.vals[args[0].index()].typed;
|
|
||||||
if (tp.addr_space != 6) return e.unsupported("'{s}' on this variable is not supported yet", .{name});
|
|
||||||
break :p try e.typedScalarPtr(tp, &.{}, try e.scalarTy(memScalar(e.compOf(dest_ty))));
|
|
||||||
};
|
|
||||||
if (float_bits) {
|
|
||||||
const as: u32 = if (tag == .ptr) 3 else 6;
|
|
||||||
ptr = try e.add(try e.dm.getType(.{ .pointer = .{ .elem = i32t, .addr_space = as } }), .{ .cast = .{ .op = .bitcast, .val = ptr } });
|
|
||||||
}
|
|
||||||
if (cmp) |cv| {
|
if (cmp) |cv| {
|
||||||
const pair = try e.dm.getType(.{ .@"struct" = .{ .name = "", .elems = &.{ i32t, try e.dm.intType(1) } } });
|
const pair = try e.dm.getType(.{ .@"struct" = .{ .name = "", .elems = &.{ i32t, try e.dm.intType(1) } } });
|
||||||
const r = try e.add(pair, .{ .cmpxchg = .{ .ptr = ptr, .cmp = cv, .new = val } });
|
const r = try e.add(pair, .{ .cmpxchg = .{ .ptr = ptr, .cmp = cv, .new = val } });
|
||||||
|
|
@ -3780,25 +3679,10 @@ const Emitter = struct {
|
||||||
},
|
},
|
||||||
else => return e.unsupported("'{s}' on this destination is not supported yet", .{name}),
|
else => return e.unsupported("'{s}' on this destination is not supported yet", .{name}),
|
||||||
};
|
};
|
||||||
const out_ty = frame.f.inst(args[args.len - 1]).ty;
|
if (has_orig) try e.storePtr(try e.outPtr(frame, args[args.len - 1]), &.{orig}, frame.f.inst(args[args.len - 1]).ty);
|
||||||
const orig_val = if (float_bits and e.compOf(out_ty) == .float) try e.add(try e.dm.getType(.float), .{ .cast = .{ .op = .bitcast, .val = orig } }) else orig;
|
|
||||||
if (has_orig) try e.storePtr(try e.outPtr(frame, args[args.len - 1]), &.{orig_val}, out_ty);
|
|
||||||
return .none;
|
return .none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An atomic's value: a float's bits for the *FloatBitwise compares
|
|
||||||
/// (constants folded).
|
|
||||||
fn atomicOperand(e: *Emitter, float_bits: bool, v: Value) Error!Value {
|
|
||||||
if (!float_bits) return v;
|
|
||||||
const i32t = try e.dm.intType(32);
|
|
||||||
if (v == .constant) switch (e.dm.constants.items[v.constant].kind) {
|
|
||||||
.float_bits => |b| return e.i32Const(@as(i32, @bitCast(@as(u32, @truncate(b))))),
|
|
||||||
else => {},
|
|
||||||
};
|
|
||||||
if (e.dm.types.items[try e.valueType(v)] != .float) return v;
|
|
||||||
return e.add(i32t, .{ .cast = .{ .op = .bitcast, .val = v } });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// dx.op.atomicBinOp / atomicCompareExchange at `coords` (padded with
|
/// dx.op.atomicBinOp / atomicCompareExchange at `coords` (padded with
|
||||||
/// undef to three).
|
/// undef to three).
|
||||||
fn resourceAtomic(e: *Emitter, res: Resource, coords: []const Value, op_name: []const u8, dc: Scalar, val: Value, cmp: ?Value) Error!Value {
|
fn resourceAtomic(e: *Emitter, res: Resource, coords: []const Value, op_name: []const u8, dc: Scalar, val: Value, cmp: ?Value) Error!Value {
|
||||||
|
|
@ -4501,7 +4385,6 @@ const Emitter = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn method(e: *Emitter, frame: *Frame, name: []const u8, res_ref: Ref, arg_refs: []const Ref, ty: TypeId) Error!Lowered {
|
fn method(e: *Emitter, frame: *Frame, name: []const u8, res_ref: Ref, arg_refs: []const Ref, ty: TypeId) Error!Lowered {
|
||||||
if (frame.vals[res_ref.index()] == .node) return e.nodeMethod(frame, frame.vals[res_ref.index()].node, name, arg_refs);
|
|
||||||
if (frame.vals[res_ref.index()] == .ray_query) return e.rayQueryMethod(frame, frame.vals[res_ref.index()].ray_query, name, arg_refs, ty);
|
if (frame.vals[res_ref.index()] == .ray_query) return e.rayQueryMethod(frame, frame.vals[res_ref.index()].ray_query, name, arg_refs, ty);
|
||||||
const res = try e.resourceOf(frame, res_ref);
|
const res = try e.resourceOf(frame, res_ref);
|
||||||
const kind = e.resourceKind(res.*);
|
const kind = e.resourceKind(res.*);
|
||||||
|
|
@ -5460,7 +5343,7 @@ const Emitter = struct {
|
||||||
|
|
||||||
fn inputAt(e: *Emitter, k: u32, ty: TypeId, vertex: ?u32) Error!Lowered {
|
fn inputAt(e: *Emitter, k: u32, ty: TypeId, vertex: ?u32) Error!Lowered {
|
||||||
const entry = e.entry;
|
const entry = e.entry;
|
||||||
if (entry.stage == .compute or entry.stage == .mesh or entry.stage == .amplification or entry.stage == .node) return e.computeInput(k, ty);
|
if (entry.stage == .compute or entry.stage == .mesh or entry.stage == .amplification) return e.computeInput(k, ty);
|
||||||
const el = entry.inputs.items[k];
|
const el = entry.inputs.items[k];
|
||||||
const se = if (e.in_elem[k]) |ei| &e.sig_in[ei] else return e.systemValueInput(el.semantic, ty);
|
const se = if (e.in_elem[k]) |ei| &e.sig_in[ei] else return e.systemValueInput(el.semantic, ty);
|
||||||
if (se.interpretation == .shadow) return e.systemValueInput(el.semantic, ty);
|
if (se.interpretation == .shadow) return e.systemValueInput(el.semantic, ty);
|
||||||
|
|
@ -5900,252 +5783,6 @@ const Emitter = struct {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- Work graph nodes ------------------------------------------------
|
|
||||||
|
|
||||||
const NodeTypes = struct { handle: DType, record_handle: DType, info: DType, record_info: DType };
|
|
||||||
|
|
||||||
fn nodeTypes(e: *Emitter) Error!NodeTypes {
|
|
||||||
const i8p = try e.dm.ptrType(try e.dm.intType(8));
|
|
||||||
const i32t = try e.dm.intType(32);
|
|
||||||
return .{
|
|
||||||
.handle = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.NodeHandle", .elems = &.{i8p} } }),
|
|
||||||
.record_handle = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.NodeRecordHandle", .elems = &.{i8p} } }),
|
|
||||||
.info = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.NodeInfo", .elems = &.{ i32t, i32t } } }),
|
|
||||||
.record_info = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.NodeRecordInfo", .elems = &.{ i32t, i32t } } }),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A record type's size and alignment (0, 0 for empty inputs and
|
|
||||||
/// outputs).
|
|
||||||
fn recordLayout(e: *Emitter, record: TypeId) Error![2]u32 {
|
|
||||||
if (record == TypeTable.void_type) return .{ 0, 0 };
|
|
||||||
return e.memLayout(record);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// annotateNodeHandle / annotateNodeRecordHandle of `raw`.
|
|
||||||
fn annotateNode(e: *Emitter, nv: NodeVal, raw: Value) Error!Value {
|
|
||||||
const nt = try e.nodeTypes();
|
|
||||||
const i32t = try e.dm.intType(32);
|
|
||||||
// (Inputs, empty ones too, and output records: record handles.)
|
|
||||||
const outputs = !nv.kind.isInput() and !nv.kind.hasRecords();
|
|
||||||
const info_ty = if (outputs) nt.info else nt.record_info;
|
|
||||||
const hty = if (outputs) nt.handle else nt.record_handle;
|
|
||||||
const f0 = try e.dm.constant(.{ .ty = i32t, .kind = .{ .int = nv.flags } });
|
|
||||||
const f1 = try e.dm.constant(.{ .ty = i32t, .kind = .{ .int = nv.size } });
|
|
||||||
const props = try e.dm.constant(.{ .ty = info_ty, .kind = .{ .aggregate = try e.arena.dupe(module.ConstId, &.{ f0.constant, f1.constant }) } });
|
|
||||||
const fn_i = if (outputs)
|
|
||||||
try e.dxOp("dx.op.annotateNodeHandle", hty, &.{ i32t, hty, info_ty }, .nounwind_readnone)
|
|
||||||
else
|
|
||||||
try e.dxOp("dx.op.annotateNodeRecordHandle", hty, &.{ i32t, hty, info_ty }, .nounwind_readnone);
|
|
||||||
return e.callOp(fn_i, hty, &.{ try e.i32Const(if (outputs) 249 else 251), raw, props });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The node shader's input or output `x.index`: its handle, created
|
|
||||||
/// and annotated.
|
|
||||||
fn nodeIo(e: *Emitter, x: @FieldType(ir.Op, "node_io")) Error!Lowered {
|
|
||||||
const info = e.entry.node orelse return e.unsupported("node objects outside node shaders", .{});
|
|
||||||
const io = if (x.output) info.outputs[x.index] else info.inputs[x.index];
|
|
||||||
const nt = try e.nodeTypes();
|
|
||||||
const i32t = try e.dm.intType(32);
|
|
||||||
var nv: NodeVal = .{ .kind = io.kind, .handle = undefined, .record = io.record, .flags = io.kind.ioFlags() | io.extra_flags, .size = (try e.recordLayout(io.record))[0] };
|
|
||||||
const raw = if (x.output)
|
|
||||||
try e.callOp(try e.dxOp("dx.op.createNodeOutputHandle", nt.handle, &.{ i32t, i32t }, .nounwind_readnone), nt.handle, &.{ try e.i32Const(247), try e.i32Const(x.index) })
|
|
||||||
else
|
|
||||||
try e.callOp(try e.dxOp("dx.op.createNodeInputRecordHandle", nt.record_handle, &.{ i32t, i32t }, .nounwind_readnone), nt.record_handle, &.{ try e.i32Const(250), try e.i32Const(x.index) });
|
|
||||||
nv.handle = try e.annotateNode(nv, raw);
|
|
||||||
return .{ .node = nv };
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Output `idx` of an outputs array (annotated as the array).
|
|
||||||
fn nodeIndex(e: *Emitter, nv: NodeVal, kind: types.NodeKind, idx: Value) Error!NodeVal {
|
|
||||||
const nt = try e.nodeTypes();
|
|
||||||
const i32t = try e.dm.intType(32);
|
|
||||||
const fn_i = try e.dxOp("dx.op.indexNodeHandle", nt.handle, &.{ i32t, nt.handle, i32t }, .nounwind_readnone);
|
|
||||||
const raw = try e.callOp(fn_i, nt.handle, &.{ try e.i32Const(248), nv.handle, idx });
|
|
||||||
var out = nv;
|
|
||||||
out.handle = try e.annotateNode(nv, raw);
|
|
||||||
out.kind = kind;
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Record `idx` of a node object, in node record memory.
|
|
||||||
fn nodeRecordPtr(e: *Emitter, nv: NodeVal, idx: Value) Error!@FieldType(Lowered, "typed") {
|
|
||||||
if (nv.record == TypeTable.void_type) return e.unsupported("records of an empty node input or output", .{});
|
|
||||||
const nt = try e.nodeTypes();
|
|
||||||
const i32t = try e.dm.intType(32);
|
|
||||||
const dty = try e.memoryType(nv.record);
|
|
||||||
const sname = switch (e.dm.types.items[dty]) {
|
|
||||||
.@"struct" => |st| st.name,
|
|
||||||
else => return e.unsupported("node records of type '{s}'", .{try e.t.format(e.arena, nv.record)}),
|
|
||||||
};
|
|
||||||
const pty = try e.dm.getType(.{ .pointer = .{ .elem = dty, .addr_space = 6 } });
|
|
||||||
const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.getNodeRecordPtr.{s}", .{sname}), pty, &.{ i32t, nt.record_handle, i32t }, .nounwind_readnone);
|
|
||||||
const base = try e.callOp(fn_i, pty, &.{ try e.i32Const(239), nv.handle, idx });
|
|
||||||
return .{ .base = base, .dty = dty, .addr_space = 6, .ty = nv.record };
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Methods of node objects.
|
|
||||||
fn nodeMethod(e: *Emitter, frame: *Frame, nv: NodeVal, name: []const u8, arg_refs: []const Ref) Error!Lowered {
|
|
||||||
const eq = std.mem.eql;
|
|
||||||
const nt = try e.nodeTypes();
|
|
||||||
const i32t = try e.dm.intType(32);
|
|
||||||
const i1t = try e.dm.intType(1);
|
|
||||||
const void_ty = try e.voidTy();
|
|
||||||
if (eq(u8, name, "IsValid")) {
|
|
||||||
const fn_i = try e.dxOp("dx.op.nodeOutputIsValid", i1t, &.{ i32t, nt.handle }, .nounwind_readonly);
|
|
||||||
return e.list(&.{try e.callOp(fn_i, i1t, &.{ try e.i32Const(252), nv.handle })});
|
|
||||||
}
|
|
||||||
if (eq(u8, name, "GetThreadNodeOutputRecords") or eq(u8, name, "GetGroupNodeOutputRecords")) {
|
|
||||||
const per_thread = eq(u8, name, "GetThreadNodeOutputRecords");
|
|
||||||
const n = (try e.scalars(frame, arg_refs[0]))[0];
|
|
||||||
const fn_i = try e.dxOp("dx.op.allocateNodeOutputRecords", nt.record_handle, &.{ i32t, nt.handle, i32t, i1t }, .nounwind);
|
|
||||||
const pt = try e.dm.constant(.{ .ty = i1t, .kind = .{ .int = @intFromBool(per_thread) } });
|
|
||||||
const raw = try e.callOp(fn_i, nt.record_handle, &.{ try e.i32Const(238), nv.handle, n, pt });
|
|
||||||
const kind: types.NodeKind = if (per_thread) .thread_output_records else .group_output_records;
|
|
||||||
var out: NodeVal = .{ .kind = kind, .handle = undefined, .record = nv.record, .flags = kind.ioFlags(), .size = nv.size };
|
|
||||||
out.handle = try e.annotateNode(out, raw);
|
|
||||||
return .{ .node = out };
|
|
||||||
}
|
|
||||||
if (eq(u8, name, "GroupIncrementOutputCount") or eq(u8, name, "ThreadIncrementOutputCount")) {
|
|
||||||
const n = (try e.scalars(frame, arg_refs[0]))[0];
|
|
||||||
const fn_i = try e.dxOp("dx.op.incrementOutputCount", void_ty, &.{ i32t, nt.handle, i32t, i1t }, .nounwind);
|
|
||||||
const pt = try e.dm.constant(.{ .ty = i1t, .kind = .{ .int = @intFromBool(eq(u8, name, "ThreadIncrementOutputCount")) } });
|
|
||||||
_ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(240), nv.handle, n, pt });
|
|
||||||
return .none;
|
|
||||||
}
|
|
||||||
if (eq(u8, name, "OutputComplete")) {
|
|
||||||
const fn_i = try e.dxOp("dx.op.outputComplete", void_ty, &.{ i32t, nt.record_handle }, .nounwind);
|
|
||||||
_ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(241), nv.handle });
|
|
||||||
return .none;
|
|
||||||
}
|
|
||||||
if (eq(u8, name, "Count")) {
|
|
||||||
const fn_i = try e.dxOp("dx.op.getInputRecordCount", i32t, &.{ i32t, nt.record_handle }, .nounwind_readonly);
|
|
||||||
return e.list(&.{try e.callOp(fn_i, i32t, &.{ try e.i32Const(242), nv.handle })});
|
|
||||||
}
|
|
||||||
if (eq(u8, name, "FinishedCrossGroupSharing")) {
|
|
||||||
const fn_i = try e.dxOp("dx.op.finishedCrossGroupSharing", i1t, &.{ i32t, nt.record_handle }, .nounwind);
|
|
||||||
return e.list(&.{try e.callOp(fn_i, i1t, &.{ try e.i32Const(243), nv.handle })});
|
|
||||||
}
|
|
||||||
return e.unsupported("node method '{s}' is not supported yet", .{name});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A node shader's entry properties (before its thread group size),
|
|
||||||
/// in dxc's order.
|
|
||||||
fn nodeProps(e: *Emitter, entry: ir.Entry, n: ir.NodeInfo, props: *std.ArrayList(?module.MdId)) Error!void {
|
|
||||||
const dm = &e.dm;
|
|
||||||
const I = struct {
|
|
||||||
fn f(m: *module.Module, v: i64) !?module.MdId {
|
|
||||||
return try m.mdI32(v);
|
|
||||||
}
|
|
||||||
}.f;
|
|
||||||
const i1t = try dm.intType(1);
|
|
||||||
const mdTrue = try dm.mdValue(i1t, try dm.constant(.{ .ty = i1t, .kind = .{ .int = 1 } }));
|
|
||||||
try props.appendSlice(e.arena, &.{ try I(dm, 13), try I(dm, @backingInt(n.launch)) });
|
|
||||||
if (entry.wave_size[0] != 0) {
|
|
||||||
const ws = entry.wave_size;
|
|
||||||
if (e.profile.minor >= 8) {
|
|
||||||
try props.appendSlice(e.arena, &.{ try I(dm, 23), try dm.mdNode(&.{ try I(dm, ws[0]), try I(dm, ws[1]), try I(dm, ws[2]) }) });
|
|
||||||
} else try props.appendSlice(e.arena, &.{ try I(dm, 11), try dm.mdNode(&.{try I(dm, ws[0])}) });
|
|
||||||
}
|
|
||||||
if (n.is_program_entry) try props.appendSlice(e.arena, &.{ try I(dm, 14), mdTrue });
|
|
||||||
try props.appendSlice(e.arena, &.{ try I(dm, 15), try dm.mdNode(&.{ try dm.mdString(n.id.name), try I(dm, n.id.index) }) });
|
|
||||||
try props.appendSlice(e.arena, &.{ try I(dm, 16), try I(dm, if (n.local_root_arguments_table_index) |x| @as(i64, x) else -1) });
|
|
||||||
if (n.share_input_of) |s| try props.appendSlice(e.arena, &.{ try I(dm, 17), try dm.mdNode(&.{ try dm.mdString(s.name), try I(dm, s.index) }) });
|
|
||||||
const grid = struct {
|
|
||||||
fn f(m: *module.Module, g: ?[3]u32) !?module.MdId {
|
|
||||||
const v = g orelse return null;
|
|
||||||
if (v[0] == 0 and v[1] == 0 and v[2] == 0) return null;
|
|
||||||
return try m.mdNode(&.{ try m.mdI32(v[0]), try m.mdI32(v[1]), try m.mdI32(v[2]) });
|
|
||||||
}
|
|
||||||
}.f;
|
|
||||||
if (try grid(dm, n.dispatch_grid)) |g| try props.appendSlice(e.arena, &.{ try I(dm, 18), g });
|
|
||||||
if (try grid(dm, n.max_dispatch_grid)) |g| try props.appendSlice(e.arena, &.{ try I(dm, 22), g });
|
|
||||||
if (n.max_recursion_depth) |d| if (d != 0) try props.appendSlice(e.arena, &.{ try I(dm, 19), try I(dm, d) });
|
|
||||||
if (n.inputs.len > 0) {
|
|
||||||
var l: std.ArrayList(?module.MdId) = .empty;
|
|
||||||
for (n.inputs) |io| try l.append(e.arena, try e.nodeIoProps(io));
|
|
||||||
try props.appendSlice(e.arena, &.{ try I(dm, 20), try dm.mdNode(l.items) });
|
|
||||||
}
|
|
||||||
if (n.outputs.len > 0) {
|
|
||||||
var l: std.ArrayList(?module.MdId) = .empty;
|
|
||||||
for (n.outputs) |io| try l.append(e.arena, try e.nodeIoProps(io));
|
|
||||||
try props.appendSlice(e.arena, &.{ try I(dm, 21), try dm.mdNode(l.items) });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One node input's / output's properties.
|
|
||||||
fn nodeIoProps(e: *Emitter, io: ir.NodeIo) Error!?module.MdId {
|
|
||||||
const dm = &e.dm;
|
|
||||||
var l: std.ArrayList(?module.MdId) = .empty;
|
|
||||||
try l.appendSlice(e.arena, &.{ try dm.mdI32(1), try dm.mdI32(io.kind.ioFlags() | io.extra_flags) });
|
|
||||||
const lay = try e.recordLayout(io.record);
|
|
||||||
if (lay[0] != 0) {
|
|
||||||
var r: std.ArrayList(?module.MdId) = .empty;
|
|
||||||
try r.appendSlice(e.arena, &.{ try dm.mdI32(0), try dm.mdI32(lay[0]) });
|
|
||||||
if (try e.dispatchGridField(io.record, 0)) |g| {
|
|
||||||
try r.appendSlice(e.arena, &.{ try dm.mdI32(1), try dm.mdNode(&.{ try dm.mdI32(g.offset), try dm.mdI32(g.comp), try dm.mdI32(g.count) }) });
|
|
||||||
}
|
|
||||||
try r.appendSlice(e.arena, &.{ try dm.mdI32(2), try dm.mdI32(lay[1]) });
|
|
||||||
try l.appendSlice(e.arena, &.{ try dm.mdI32(2), try dm.mdNode(r.items) });
|
|
||||||
}
|
|
||||||
const i1t = try dm.intType(1);
|
|
||||||
if (!io.kind.isInput()) {
|
|
||||||
try l.appendSlice(e.arena, &.{ try dm.mdI32(3), try dm.mdI32(io.max_records orelse 0) });
|
|
||||||
if (io.array_size) |a| if (a != 0) try l.appendSlice(e.arena, &.{ try dm.mdI32(5), try dm.mdI32(@as(i32, @bitCast(a))) });
|
|
||||||
if (io.max_records_shared_with) |s| try l.appendSlice(e.arena, &.{ try dm.mdI32(4), try dm.mdI32(s) });
|
|
||||||
if (io.allow_sparse_nodes) try l.appendSlice(e.arena, &.{ try dm.mdI32(6), try dm.mdValue(i1t, try dm.constant(.{ .ty = i1t, .kind = .{ .int = 1 } })) });
|
|
||||||
if (io.output_id) |id| try l.appendSlice(e.arena, &.{ try dm.mdI32(0), try dm.mdNode(&.{ try dm.mdString(id.name), try dm.mdI32(id.index) }) });
|
|
||||||
} else if (io.max_records) |m| if (m != 0) try l.appendSlice(e.arena, &.{ try dm.mdI32(3), try dm.mdI32(m) });
|
|
||||||
return try dm.mdNode(l.items);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// SV_DispatchGrid in a record: byte offset, component type (U32 5,
|
|
||||||
/// U16 3) and component count.
|
|
||||||
const DispatchGrid = struct { offset: u32, comp: u32, count: u32 };
|
|
||||||
|
|
||||||
fn dispatchGridField(e: *Emitter, ty: TypeId, base: u32) Error!?DispatchGrid {
|
|
||||||
const st = switch (e.t.get(ty)) {
|
|
||||||
.@"struct" => |s| s,
|
|
||||||
else => return null,
|
|
||||||
};
|
|
||||||
var off: u32 = 0;
|
|
||||||
for (st.fields.items) |fld| {
|
|
||||||
const fl = try e.memLayout(fld.type);
|
|
||||||
off = std.mem.alignForward(u32, off, fl[1]);
|
|
||||||
if (fld.semantic) |sem| if (std.ascii.eqlIgnoreCase(sem, "SV_DispatchGrid")) {
|
|
||||||
const count: u32 = switch (e.t.get(fld.type)) {
|
|
||||||
.vector => |v| v.len,
|
|
||||||
.array => |a| a.len,
|
|
||||||
else => 1,
|
|
||||||
};
|
|
||||||
const scalar_size = fl[0] / count;
|
|
||||||
return .{ .offset = base + off, .comp = if (scalar_size == 2) 3 else 5, .count = count };
|
|
||||||
};
|
|
||||||
if (e.t.get(fld.type) == .@"struct") if (try e.dispatchGridField(fld.type, base + off)) |g| return g;
|
|
||||||
off += fl[0];
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `tp` indexed by `indices` (struct members by constant index).
|
|
||||||
fn typedAccess(e: *Emitter, frame: *Frame, start: @FieldType(Lowered, "typed"), indices: []const Ref) Error!@FieldType(Lowered, "typed") {
|
|
||||||
var tp = start;
|
|
||||||
var path: std.ArrayList(Value) = .empty;
|
|
||||||
try path.appendSlice(e.arena, tp.path);
|
|
||||||
for (indices) |x| {
|
|
||||||
try path.append(e.arena, (try e.scalars(frame, x))[0]);
|
|
||||||
tp.ty = switch (e.t.get(tp.ty)) {
|
|
||||||
.@"struct" => |st| st.fields.items[@intCast(frame.f.inst(x).op.constant.int)].type,
|
|
||||||
.array => |arr| arr.elem,
|
|
||||||
.vector => |v| try e.t.scalar(v.elem),
|
|
||||||
.matrix => |mt| try e.t.vector(mt.elem, mt.cols),
|
|
||||||
else => return e.unsupported("indexing this member is not supported yet", .{}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
tp.path = path.items;
|
|
||||||
return tp;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn typedScalarPtr(e: *Emitter, tp: @FieldType(Lowered, "typed"), sub: []const Value, st: DType) Error!Value {
|
fn typedScalarPtr(e: *Emitter, tp: @FieldType(Lowered, "typed"), sub: []const Value, st: DType) Error!Value {
|
||||||
const idx = try e.arena.alloc(Value, 1 + tp.path.len + sub.len);
|
const idx = try e.arena.alloc(Value, 1 + tp.path.len + sub.len);
|
||||||
idx[0] = try e.i32Const(0);
|
idx[0] = try e.i32Const(0);
|
||||||
|
|
@ -6541,7 +6178,7 @@ const Emitter = struct {
|
||||||
}.f;
|
}.f;
|
||||||
const ident = try dm.mdNode(&.{try dm.mdString("zdxc 0.0.0")});
|
const ident = try dm.mdNode(&.{try dm.mdString("zdxc 0.0.0")});
|
||||||
const version = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, e.profile.minor) });
|
const version = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, e.profile.minor) });
|
||||||
const val_ver = try dm.mdNode(&.{ try mdI32(dm, shader.validator[0]), try mdI32(dm, shader.validator[1]) });
|
const val_ver = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, 11) });
|
||||||
const sm = try dm.mdNode(&.{ try dm.mdString("lib"), try mdI32(dm, e.profile.major), try mdI32(dm, e.profile.minor) });
|
const sm = try dm.mdNode(&.{ try dm.mdString("lib"), try mdI32(dm, e.profile.major), try mdI32(dm, e.profile.minor) });
|
||||||
const resources = try e.resourcesMd();
|
const resources = try e.resourcesMd();
|
||||||
const analysis = try e.libAnalysis(funcs);
|
const analysis = try e.libAnalysis(funcs);
|
||||||
|
|
@ -7076,78 +6713,6 @@ const Emitter = struct {
|
||||||
return @intCast(n);
|
return @intCast(n);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A node shader's RDAT NodeShaderInfo (as dxc's AddShaderNodeInfo).
|
|
||||||
fn rdatNode(e: *Emitter, b: *rdat.Builder, entry: ir.Entry, n: ir.NodeInfo, groupshared: u32) Error!u32 {
|
|
||||||
const rec = struct {
|
|
||||||
fn f(bb: *rdat.Builder, t: rdat.Ext, words: []const u32) !u32 {
|
|
||||||
return bb.record(t, std.mem.sliceAsBytes(words));
|
|
||||||
}
|
|
||||||
}.f;
|
|
||||||
var attrs: std.ArrayList(u32) = .empty;
|
|
||||||
// NodeFuncAttribKind: ID 1, NumThreads 2, ShareInputOf 3,
|
|
||||||
// DispatchGrid 4, MaxRecursionDepth 5, LocalRootArgumentsTableIndex
|
|
||||||
// 6, MaxDispatchGrid 7.
|
|
||||||
const id = try rec(b, .node_ids, &.{ try b.string(n.id.name), n.id.index });
|
|
||||||
try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 1, id }));
|
|
||||||
const nt = entry.num_threads;
|
|
||||||
if (nt[0] != 0 or nt[1] != 0 or nt[2] != 0) try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 2, try b.array(&nt) }));
|
|
||||||
if (n.local_root_arguments_table_index) |x| try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 6, x }));
|
|
||||||
if (n.share_input_of) |s| {
|
|
||||||
const sid = try rec(b, .node_ids, &.{ try b.string(s.name), s.index });
|
|
||||||
try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 3, sid }));
|
|
||||||
}
|
|
||||||
if (n.dispatch_grid) |g| if (g[0] != 0 or g[1] != 0 or g[2] != 0) try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 4, try b.array(&g) }));
|
|
||||||
if (n.max_recursion_depth) |d| if (d != 0) try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 5, d }));
|
|
||||||
if (n.max_dispatch_grid) |g| if (g[0] != 0 or g[1] != 0 or g[2] != 0) try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 7, try b.array(&g) }));
|
|
||||||
const func_attrs = try b.array(attrs.items);
|
|
||||||
const inputs = try e.rdatIoNodes(b, n.inputs);
|
|
||||||
const outputs = try e.rdatIoNodes(b, n.outputs);
|
|
||||||
return rec(b, .node_shaders, &.{ @backingInt(n.launch), groupshared, func_attrs, outputs, inputs });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The IONode records of node inputs or outputs (an index array).
|
|
||||||
fn rdatIoNodes(e: *Emitter, b: *rdat.Builder, ios: []const ir.NodeIo) Error!u32 {
|
|
||||||
const rec = struct {
|
|
||||||
fn f(bb: *rdat.Builder, t: rdat.Ext, words: []const u32) !u32 {
|
|
||||||
return bb.record(t, std.mem.sliceAsBytes(words));
|
|
||||||
}
|
|
||||||
}.f;
|
|
||||||
var nodes: std.ArrayList(u32) = .empty;
|
|
||||||
for (ios) |io| {
|
|
||||||
// NodeAttribKind: OutputID 1, MaxRecords 2, MaxRecordsSharedWith
|
|
||||||
// 3, RecordSizeInBytes 4, RecordDispatchGrid 5, OutputArraySize
|
|
||||||
// 6, AllowSparseNodes 7, RecordAlignmentInBytes 8.
|
|
||||||
var attrs: std.ArrayList(u32) = .empty;
|
|
||||||
if (!io.kind.isInput()) {
|
|
||||||
const oid = io.output_id orelse ir.NodeId{ .name = "" };
|
|
||||||
const id = try rec(b, .node_ids, &.{ try b.string(oid.name), oid.index });
|
|
||||||
try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 1, id }));
|
|
||||||
try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 6, io.array_size orelse 0 }));
|
|
||||||
if (io.max_records orelse 0 != 0) {
|
|
||||||
try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 2, io.max_records.? }));
|
|
||||||
} else if (io.max_records_shared_with) |s| {
|
|
||||||
try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 3, s }));
|
|
||||||
}
|
|
||||||
if (io.allow_sparse_nodes) try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 7, 1 }));
|
|
||||||
} else if (io.max_records orelse 0 != 0) {
|
|
||||||
try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 2, io.max_records.? }));
|
|
||||||
}
|
|
||||||
const lay = try e.recordLayout(io.record);
|
|
||||||
if (lay[0] != 0) {
|
|
||||||
try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 4, lay[0] }));
|
|
||||||
if (try e.dispatchGridField(io.record, 0)) |g| {
|
|
||||||
// ByteOffset (u16), then components (bits 0..1) and
|
|
||||||
// component type (from bit 2).
|
|
||||||
try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 5, g.offset | ((g.count & 3) | (g.comp << 2)) << 16 }));
|
|
||||||
}
|
|
||||||
if (lay[1] != 0) try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 8, lay[1] }));
|
|
||||||
}
|
|
||||||
const arr = try b.array(attrs.items);
|
|
||||||
try nodes.append(e.arena, try rec(b, .io_nodes, &.{ io.kind.ioFlags() | io.extra_flags, arr }));
|
|
||||||
}
|
|
||||||
return b.array(nodes.items);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The library container: feature info, runtime data (RDAT) and the
|
/// The library container: feature info, runtime data (RDAT) and the
|
||||||
/// program.
|
/// program.
|
||||||
fn assembleLibrary(e: *Emitter, gpa: Allocator, funcs: []const LibFunc, bitcode: []const u8) Error![]u8 {
|
fn assembleLibrary(e: *Emitter, gpa: Allocator, funcs: []const LibFunc, bitcode: []const u8) Error![]u8 {
|
||||||
|
|
@ -7205,12 +6770,6 @@ const Emitter = struct {
|
||||||
.cbuffers = func_cbuffers.items,
|
.cbuffers = func_cbuffers.items,
|
||||||
});
|
});
|
||||||
const resources = if (used.items.len > 0) try b.array(used.items) else rdat.null_ref;
|
const resources = if (used.items.len > 0) try b.array(used.items) else rdat.null_ref;
|
||||||
var shader_flags: u16 = 0;
|
|
||||||
const node_info = if (lf.stage == .node) blk: {
|
|
||||||
const n = lf.entry.node.?;
|
|
||||||
if (n.is_program_entry) shader_flags |= 1;
|
|
||||||
break :blk try e.rdatNode(&b, lf.entry, n, lf.groupshared);
|
|
||||||
} else rdat.null_ref;
|
|
||||||
const props = if (e.uses_linalg) try linalg_info.rdatProperties(e.arena, &b, &try linalg_info.functionInfo(e.arena, &e.dm, mats, lf.func)) else rdat.null_ref;
|
const props = if (e.uses_linalg) try linalg_info.rdatProperties(e.arena, &b, &try linalg_info.functionInfo(e.arena, &e.dm, mats, lf.func)) else rdat.null_ref;
|
||||||
const kind = shaderKind(lf.stage);
|
const kind = shaderKind(lf.stage);
|
||||||
try b.addFunction(.{
|
try b.addFunction(.{
|
||||||
|
|
@ -7224,11 +6783,6 @@ const Emitter = struct {
|
||||||
.feature_info2 = @truncate(libinfo.featureInfo(info.flags) >> 32),
|
.feature_info2 = @truncate(libinfo.featureInfo(info.flags) >> 32),
|
||||||
.shader_stage_flag = if (lf.stage == .library) info.mask & 0xffff else info.mask & (@as(u32, 1) << @intCast(kind)),
|
.shader_stage_flag = if (lf.stage == .library) info.mask & 0xffff else info.mask & (@as(u32, 1) << @intCast(kind)),
|
||||||
.min_shader_target = (kind << 16) | (6 << 4) | libinfo.minMinor(info, if (lf.stage == .library) null else kind),
|
.min_shader_target = (kind << 16) | (6 << 4) | libinfo.minMinor(info, if (lf.stage == .library) null else kind),
|
||||||
// (RDAT: 0 where none is specified.)
|
|
||||||
.min_wave_lanes = @intCast(lf.entry.wave_size[0]),
|
|
||||||
.max_wave_lanes = @intCast(if (lf.entry.wave_size[1] != 0) lf.entry.wave_size[1] else lf.entry.wave_size[0]),
|
|
||||||
.shader_flags = shader_flags,
|
|
||||||
.raw_shader_ref = node_info,
|
|
||||||
.extended_properties = props,
|
.extended_properties = props,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -7284,14 +6838,6 @@ const Emitter = struct {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The wave lane counts PSV and RDAT give: WaveSize's minimum, and its
|
|
||||||
/// maximum (a range) or the minimum again; with none, 0 and maxInt.
|
|
||||||
fn waveLanes(entry: ir.Entry) [2]u32 {
|
|
||||||
const ws = entry.wave_size;
|
|
||||||
if (ws[0] == 0) return .{ 0, std.math.maxInt(u32) };
|
|
||||||
return .{ ws[0], if (ws[1] != 0) ws[1] else ws[0] };
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Entry properties of the stage: thread group size and the GS / HS /
|
/// Entry properties of the stage: thread group size and the GS / HS /
|
||||||
/// DS / MS / AS state.
|
/// DS / MS / AS state.
|
||||||
fn stageProps(e: *Emitter, entry: ir.Entry, props: *std.ArrayList(?module.MdId)) Error!void {
|
fn stageProps(e: *Emitter, entry: ir.Entry, props: *std.ArrayList(?module.MdId)) Error!void {
|
||||||
|
|
@ -7302,20 +6848,7 @@ const Emitter = struct {
|
||||||
}
|
}
|
||||||
}.f;
|
}.f;
|
||||||
const threads = try dm.mdNode(&.{ try mdI32(dm, entry.num_threads[0]), try mdI32(dm, entry.num_threads[1]), try mdI32(dm, entry.num_threads[2]) });
|
const threads = try dm.mdNode(&.{ try mdI32(dm, entry.num_threads[0]), try mdI32(dm, entry.num_threads[1]), try mdI32(dm, entry.num_threads[2]) });
|
||||||
if (entry.node) |n| {
|
|
||||||
try e.nodeProps(entry, n, props);
|
|
||||||
try props.appendSlice(e.arena, &.{ try mdI32(dm, 4), threads });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (entry.stage == .compute) try props.appendSlice(e.arena, &.{ try mdI32(dm, 4), threads });
|
if (entry.stage == .compute) try props.appendSlice(e.arena, &.{ try mdI32(dm, 4), threads });
|
||||||
// WaveSize: a value (tag 11) before SM 6.8, a range with a
|
|
||||||
// preferred size after (tag 23; zeros where not given).
|
|
||||||
if (entry.wave_size[0] != 0) {
|
|
||||||
const ws = entry.wave_size;
|
|
||||||
if (e.profile.minor >= 8) {
|
|
||||||
try props.appendSlice(e.arena, &.{ try mdI32(dm, 23), try dm.mdNode(&.{ try mdI32(dm, ws[0]), try mdI32(dm, ws[1]), try mdI32(dm, ws[2]) }) });
|
|
||||||
} else try props.appendSlice(e.arena, &.{ try mdI32(dm, 11), try dm.mdNode(&.{try mdI32(dm, ws[0])}) });
|
|
||||||
}
|
|
||||||
const payload_size: u32 = if (entry.mesh.payload) |p| try e.payloadSize(p) else 0;
|
const payload_size: u32 = if (entry.mesh.payload) |p| try e.payloadSize(p) else 0;
|
||||||
if (entry.stage == .mesh) {
|
if (entry.stage == .mesh) {
|
||||||
// MS state: thread group, max vertices, max primitives,
|
// MS state: thread group, max vertices, max primitives,
|
||||||
|
|
@ -7381,7 +6914,7 @@ const Emitter = struct {
|
||||||
|
|
||||||
const ident = try dm.mdNode(&.{try dm.mdString("zdxc 0.0.0")});
|
const ident = try dm.mdNode(&.{try dm.mdString("zdxc 0.0.0")});
|
||||||
const version = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, e.profile.minor) });
|
const version = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, e.profile.minor) });
|
||||||
const val_ver = try dm.mdNode(&.{ try mdI32(dm, shader.validator[0]), try mdI32(dm, shader.validator[1]) });
|
const val_ver = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, 11) });
|
||||||
const sm = try dm.mdNode(&.{ try dm.mdString(e.profile.kind.profilePrefix()), try mdI32(dm, e.profile.major), try mdI32(dm, e.profile.minor) });
|
const sm = try dm.mdNode(&.{ try dm.mdString(e.profile.kind.profilePrefix()), try mdI32(dm, e.profile.major), try mdI32(dm, e.profile.minor) });
|
||||||
|
|
||||||
const resources = try e.resourcesMd();
|
const resources = try e.resourcesMd();
|
||||||
|
|
@ -7531,7 +7064,6 @@ const Emitter = struct {
|
||||||
.entry = entry.name,
|
.entry = entry.name,
|
||||||
.stage_info = stage_info,
|
.stage_info = stage_info,
|
||||||
.num_threads = if (threaded) entry.num_threads else .{ 0, 0, 0 },
|
.num_threads = if (threaded) entry.num_threads else .{ 0, 0, 0 },
|
||||||
.wave_lanes = waveLanes(entry),
|
|
||||||
.mesh_topology = if (entry.stage == .mesh) @backingInt(entry.mesh.topology) else 0,
|
.mesh_topology = if (entry.stage == .mesh) @backingInt(entry.mesh.topology) else 0,
|
||||||
.uses_view_id = e.uses_view_id,
|
.uses_view_id = e.uses_view_id,
|
||||||
.resources = binds.items,
|
.resources = binds.items,
|
||||||
|
|
@ -7618,29 +7150,15 @@ fn gsTopology(g: ir.GeometryInfo) u32 {
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resources, samplers and (handles too) work graph node objects.
|
|
||||||
fn isResourceType(t: *TypeTable, ty: TypeId) bool {
|
fn isResourceType(t: *TypeTable, ty: TypeId) bool {
|
||||||
return switch (t.get(ty)) {
|
return switch (t.get(ty)) {
|
||||||
.resource, .sampler, .node => true,
|
.resource, .sampler => true,
|
||||||
else => false,
|
else => false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const isRayQuery = @import("../ir/lower.zig").isRayQuery;
|
const isRayQuery = @import("../ir/lower.zig").isRayQuery;
|
||||||
|
|
||||||
/// Whether the stores to local `ptr` are all in one block of `f`.
|
|
||||||
fn storesInOneBlock(f: *const ir.Function, ptr: Ref) bool {
|
|
||||||
var found: ?usize = null;
|
|
||||||
for (f.blocks.items, 0..) |blk, bi| for (blk.insts.items) |r| switch (f.inst(r).op) {
|
|
||||||
.store => |x| if (x.ptr == ptr) {
|
|
||||||
if (found) |b| if (b != bi) return false;
|
|
||||||
found = bi;
|
|
||||||
},
|
|
||||||
else => {},
|
|
||||||
};
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn reachableBlocks(a: Allocator, f: *const ir.Function) Allocator.Error![]bool {
|
fn reachableBlocks(a: Allocator, f: *const ir.Function) Allocator.Error![]bool {
|
||||||
return reachableBlocksTaken(a, f, &.{});
|
return reachableBlocksTaken(a, f, &.{});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -191,22 +191,6 @@ pub fn analyze(m: *const module.Module, f: *const module.Function, o: Options) I
|
||||||
fl |= bit.requires_group;
|
fl |= bit.requires_group;
|
||||||
info.mask &= stage_group;
|
info.mask &= stage_group;
|
||||||
},
|
},
|
||||||
// Barrier by memory type, UAV or node record: groupshared memory
|
|
||||||
// (not as part of ALL_MEMORY, which may drop it) or group
|
|
||||||
// sync / scope semantics need a group (as dxc's
|
|
||||||
// BarrierRequiresGroup).
|
|
||||||
244, 245, 246 => if (args.len > 2) {
|
|
||||||
var needs = false;
|
|
||||||
if (code == 244) if (constInt(m, args[1])) |mem| {
|
|
||||||
const kept = if (mem == 0xF) mem & ~@as(i64, 2) else mem;
|
|
||||||
needs = kept & 2 != 0;
|
|
||||||
};
|
|
||||||
if (constInt(m, args[2])) |sem| needs = needs or sem & 3 != 0;
|
|
||||||
if (needs) {
|
|
||||||
fl |= bit.requires_group;
|
|
||||||
info.mask &= stage_group;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
else => {},
|
else => {},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -106,7 +106,7 @@ const ConstantContext = struct {
|
||||||
pub const Linkage = enum(u32) { external = 0, internal = 3 };
|
pub const Linkage = enum(u32) { external = 0, internal = 3 };
|
||||||
|
|
||||||
/// Attribute group for function declarations (e.g. dx.op functions).
|
/// Attribute group for function declarations (e.g. dx.op functions).
|
||||||
pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly, noreturn_nounwind, noinline_nounwind, noduplicate_nounwind };
|
pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly, noreturn_nounwind, noinline_nounwind };
|
||||||
|
|
||||||
pub const Value = union(enum) {
|
pub const Value = union(enum) {
|
||||||
/// Index into Module.globals (a pointer to the variable).
|
/// Index into Module.globals (a pointer to the variable).
|
||||||
|
|
@ -164,17 +164,7 @@ pub const Inst = struct {
|
||||||
|
|
||||||
/// An instruction's metadata attachment: an index into Module.inst_mds,
|
/// An instruction's metadata attachment: an index into Module.inst_mds,
|
||||||
/// kept out of line (few instructions have one).
|
/// kept out of line (few instructions have one).
|
||||||
/// `unroll` is no attachment: it marks the back edge of an `[unroll]` loop
|
pub const InstMd = enum(u32) { none = 0, _ };
|
||||||
/// for the unroller, and is not written.
|
|
||||||
pub const InstMd = enum(u32) {
|
|
||||||
none = 0,
|
|
||||||
unroll = std.math.maxInt(u32),
|
|
||||||
_,
|
|
||||||
|
|
||||||
pub fn written(md: InstMd) bool {
|
|
||||||
return md != .none and md != .unroll;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const Function = struct {
|
pub const Function = struct {
|
||||||
name: []const u8,
|
name: []const u8,
|
||||||
|
|
@ -681,19 +671,12 @@ const Encoder = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn writeAttributes(e: *Encoder) !void {
|
fn writeAttributes(e: *Encoder) !void {
|
||||||
// Groups 1..6 match FnAttrs order; each applies to the function (index 0xFFFFFFFF).
|
// Groups 1..5 match FnAttrs order; each applies to the function (index 0xFFFFFFFF).
|
||||||
// Attribute kinds: noduplicate = 12, noinline = 14, noreturn = 17,
|
// Attribute kinds: noinline = 14, noreturn = 17, nounwind = 18,
|
||||||
// nounwind = 18, readnone = 20, readonly = 21.
|
// readnone = 20, readonly = 21.
|
||||||
const w = &e.w;
|
const w = &e.w;
|
||||||
try w.enterBlock(block_paramattr_group, 3);
|
try w.enterBlock(block_paramattr_group, 3);
|
||||||
const all = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 }, &.{ 17, 18 }, &.{ 14, 18 }, &.{ 12, 18 } };
|
const groups = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 }, &.{ 17, 18 }, &.{ 14, 18 } };
|
||||||
// noduplicate (the SM 6.8 barriers) only when used: the rest of
|
|
||||||
// the modules are as they were.
|
|
||||||
var n: usize = 5;
|
|
||||||
for (e.m.functions.items) |f| {
|
|
||||||
if (f.attrs == .noduplicate_nounwind) n = 6;
|
|
||||||
}
|
|
||||||
const groups = all[0..n];
|
|
||||||
for (groups, 1..) |kinds, id| {
|
for (groups, 1..) |kinds, id| {
|
||||||
try e.push(id);
|
try e.push(id);
|
||||||
try e.push(0xFFFFFFFF);
|
try e.push(0xFFFFFFFF);
|
||||||
|
|
@ -987,10 +970,10 @@ const Encoder = struct {
|
||||||
}
|
}
|
||||||
// METADATA_ATTACHMENT: [instruction index, (kind, node)...]
|
// METADATA_ATTACHMENT: [instruction index, (kind, node)...]
|
||||||
var any_md = false;
|
var any_md = false;
|
||||||
for (f.insts.items) |inst| any_md = any_md or inst.md.written();
|
for (f.insts.items) |inst| any_md = any_md or inst.md != .none;
|
||||||
if (any_md) {
|
if (any_md) {
|
||||||
try w.enterBlock(block_metadata_attachment, 3);
|
try w.enterBlock(block_metadata_attachment, 3);
|
||||||
for (f.insts.items, 0..) |inst, k| if (inst.md.written()) {
|
for (f.insts.items, 0..) |inst, k| if (inst.md != .none) {
|
||||||
const md = e.m.inst_mds.items[@backingInt(inst.md) - 1];
|
const md = e.m.inst_mds.items[@backingInt(inst.md) - 1];
|
||||||
try e.ops.appendSlice(e.gpa(), &.{ k, md.kind, md.node });
|
try e.ops.appendSlice(e.gpa(), &.{ k, md.kind, md.node });
|
||||||
try e.rec(11);
|
try e.rec(11);
|
||||||
|
|
|
||||||
|
|
@ -23,14 +23,14 @@ const TypeId = module.TypeId;
|
||||||
|
|
||||||
const none = std.math.maxInt(u32);
|
const none = std.math.maxInt(u32);
|
||||||
|
|
||||||
pub const Role = enum { load_ptr, store_ptr, gep_base, other };
|
const Role = enum { load_ptr, store_ptr, gep_base, other };
|
||||||
|
|
||||||
const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child;
|
const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child;
|
||||||
|
|
||||||
/// Visits each operand of `inst` (with the way it is used) through
|
/// Visits each operand of `inst` (with the way it is used) through
|
||||||
/// `ctx.visit(value, role) Value`. With `write`, the results replace the
|
/// `ctx.visit(value, role) Value`. With `write`, the results replace the
|
||||||
/// operands, in newly allocated slices where the operands are slices.
|
/// operands, in newly allocated slices where the operands are slices.
|
||||||
pub fn operands(comptime write: bool, a: Allocator, inst: *Inst, ctx: anytype) Allocator.Error!void {
|
fn operands(comptime write: bool, a: Allocator, inst: *Inst, ctx: anytype) Allocator.Error!void {
|
||||||
const S = struct {
|
const S = struct {
|
||||||
fn one(c: anytype, v: *Value, role: Role) void {
|
fn one(c: anytype, v: *Value, role: Role) void {
|
||||||
const r = c.visit(v.*, role);
|
const r = c.visit(v.*, role);
|
||||||
|
|
@ -1088,7 +1088,6 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
|
||||||
return null;
|
return null;
|
||||||
},
|
},
|
||||||
.binop => |b| {
|
.binop => |b| {
|
||||||
if (try foldFloat(m, repl, inst)) |v| return v;
|
|
||||||
const w = S.intWidth(m, inst.ty) orelse return null;
|
const w = S.intWidth(m, inst.ty) orelse return null;
|
||||||
const l = resolve(repl, b.lhs);
|
const l = resolve(repl, b.lhs);
|
||||||
const r = resolve(repl, b.rhs);
|
const r = resolve(repl, b.rhs);
|
||||||
|
|
@ -1128,10 +1127,6 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
|
||||||
.@"and" => if (S.bits(x, w) == S.bits(-1, w)) return r,
|
.@"and" => if (S.bits(x, w) == S.bits(-1, w)) return r,
|
||||||
else => {},
|
else => {},
|
||||||
};
|
};
|
||||||
if (b.op == .@"and" and w <= 64) {
|
|
||||||
if (rc) |y| return andKnown(m, f, repl, n, l, S.bits(y, w), w, inst.ty);
|
|
||||||
if (lc) |x| return andKnown(m, f, repl, n, r, S.bits(x, w), w, inst.ty);
|
|
||||||
}
|
|
||||||
return null;
|
return null;
|
||||||
},
|
},
|
||||||
.cmp => |c| {
|
.cmp => |c| {
|
||||||
|
|
@ -1164,50 +1159,25 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
|
||||||
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(t) } });
|
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(t) } });
|
||||||
}
|
}
|
||||||
if (c.pred < 32 or c.pred > 41) return null; // integer predicates
|
if (c.pred < 32 or c.pred > 41) return null; // integer predicates
|
||||||
// A bool widened and compared again: `zext i1 x != 0` and
|
|
||||||
// `zext i1 x == 1` are x.
|
|
||||||
if (c.pred == 32 or c.pred == 33) if (l == .inst and l.inst < n) {
|
|
||||||
const z = f.insts.items[l.inst].op;
|
|
||||||
if (z == .cast and z.cast.op == .zext) {
|
|
||||||
const x = resolve(repl, z.cast.val);
|
|
||||||
if (S.intWidth(m, S.ty(m, f, n, phi_var, var_ty, x)) == 1) {
|
|
||||||
if (constInt(m, r)) |k| {
|
|
||||||
if ((c.pred == 33 and k == 0) or (c.pred == 32 and k == 1)) return x;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
const w = S.intWidth(m, S.ty(m, f, n, phi_var, var_ty, l)) orelse return null;
|
const w = S.intWidth(m, S.ty(m, f, n, phi_var, var_ty, l)) orelse return null;
|
||||||
// Each side's possible values: a constant, or selects and phis
|
const x = S.bits(constInt(m, l) orelse return null, w);
|
||||||
// of constants (`(c ? 2 : 1) == 3` is false, as dxc's
|
const y = S.bits(constInt(m, r) orelse return null, w);
|
||||||
// instcombine finds); the same answer for every pair folds.
|
const sx = S.stored(x, w);
|
||||||
var lv: Cands = .{};
|
const sy = S.stored(y, w);
|
||||||
var rv: Cands = .{};
|
const t = switch (c.pred) {
|
||||||
if (!lv.add(m, f, repl, n, l, 2) or !rv.add(m, f, repl, n, r, 2)) return null;
|
32 => x == y,
|
||||||
var result: ?bool = null;
|
33 => x != y,
|
||||||
for (lv.vals[0..lv.len]) |lk| for (rv.vals[0..rv.len]) |rk| {
|
34 => x > y,
|
||||||
const x = S.bits(lk, w);
|
35 => x >= y,
|
||||||
const y = S.bits(rk, w);
|
36 => x < y,
|
||||||
const sx = S.stored(x, w);
|
37 => x <= y,
|
||||||
const sy = S.stored(y, w);
|
38 => sx > sy,
|
||||||
const t = switch (c.pred) {
|
39 => sx >= sy,
|
||||||
32 => x == y,
|
40 => sx < sy,
|
||||||
33 => x != y,
|
else => sx <= sy,
|
||||||
34 => x > y,
|
|
||||||
35 => x >= y,
|
|
||||||
36 => x < y,
|
|
||||||
37 => x <= y,
|
|
||||||
38 => sx > sy,
|
|
||||||
39 => sx >= sy,
|
|
||||||
40 => sx < sy,
|
|
||||||
else => sx <= sy,
|
|
||||||
};
|
|
||||||
if (result) |prev| if (prev != t) return null;
|
|
||||||
result = t;
|
|
||||||
};
|
};
|
||||||
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(result orelse return null) } });
|
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(t) } });
|
||||||
},
|
},
|
||||||
.call => return foldDxOp(m, repl, inst),
|
|
||||||
.select => |sl| {
|
.select => |sl| {
|
||||||
const t = resolve(repl, sl.t);
|
const t = resolve(repl, sl.t);
|
||||||
const fv = resolve(repl, sl.f);
|
const fv = resolve(repl, sl.f);
|
||||||
|
|
@ -1280,240 +1250,6 @@ fn edgePhi(m: *module.Module, insts: []const Inst, block_start: []const u32, rep
|
||||||
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = same orelse return null } });
|
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = same orelse return null } });
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The integer constants a value can be: itself if constant, or each arm
|
|
||||||
/// of a select or input of a phi that is (`depth` levels deep).
|
|
||||||
const Cands = struct {
|
|
||||||
vals: [8]i64 = undefined,
|
|
||||||
len: usize = 0,
|
|
||||||
|
|
||||||
fn add(c: *Cands, m: *const module.Module, f: *const module.Function, repl: []const ?Value, n: u32, v: Value, depth: u32) bool {
|
|
||||||
const x = resolve(repl, v);
|
|
||||||
if (constInt(m, x)) |k| {
|
|
||||||
for (c.vals[0..c.len]) |e| if (e == k) return true;
|
|
||||||
if (c.len == c.vals.len) return false;
|
|
||||||
c.vals[c.len] = k;
|
|
||||||
c.len += 1;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (x != .inst or x.inst >= n or depth == 0) return false;
|
|
||||||
switch (f.insts.items[x.inst].op) {
|
|
||||||
.select => |sl| return c.add(m, f, repl, n, sl.t, depth - 1) and c.add(m, f, repl, n, sl.f, depth - 1),
|
|
||||||
.phi => |p| {
|
|
||||||
for (p.incoming) |in| {
|
|
||||||
const y = resolve(repl, in.val);
|
|
||||||
if (y == .inst and y.inst == x.inst) continue;
|
|
||||||
if (!c.add(m, f, repl, n, y, depth - 1)) return false;
|
|
||||||
}
|
|
||||||
return c.len > 0;
|
|
||||||
},
|
|
||||||
else => return false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/// The bits of the `w`-bit integer `v` known to be zero, from what
|
|
||||||
/// computes it (`depth` levels deep): constants, masks, shifts by
|
|
||||||
/// constants, widening, and the bitwise operations and selects of such.
|
|
||||||
fn knownZero(m: *const module.Module, f: *const module.Function, repl: []const ?Value, n: u32, v: Value, w: u32, depth: u32) u64 {
|
|
||||||
const mask: u64 = if (w >= 64) ~@as(u64, 0) else (@as(u64, 1) << @intCast(w)) - 1;
|
|
||||||
const x = resolve(repl, v);
|
|
||||||
if (constInt(m, x)) |k| return ~@as(u64, @bitCast(k)) & mask;
|
|
||||||
if (x != .inst or x.inst >= n or depth == 0) return 0;
|
|
||||||
const inst = f.insts.items[x.inst];
|
|
||||||
const d = depth - 1;
|
|
||||||
return mask & switch (inst.op) {
|
|
||||||
.binop => |b| switch (b.op) {
|
|
||||||
.@"and" => knownZero(m, f, repl, n, b.lhs, w, d) | knownZero(m, f, repl, n, b.rhs, w, d),
|
|
||||||
.@"or", .xor => knownZero(m, f, repl, n, b.lhs, w, d) & knownZero(m, f, repl, n, b.rhs, w, d),
|
|
||||||
.shl => blk: {
|
|
||||||
const k = constInt(m, resolve(repl, b.rhs)) orelse break :blk 0;
|
|
||||||
if (k < 0 or k >= w) break :blk 0;
|
|
||||||
const sh: u6 = @intCast(k);
|
|
||||||
break :blk (knownZero(m, f, repl, n, b.lhs, w, d) << sh) | ((@as(u64, 1) << sh) - 1);
|
|
||||||
},
|
|
||||||
.lshr => blk: {
|
|
||||||
const k = constInt(m, resolve(repl, b.rhs)) orelse break :blk 0;
|
|
||||||
if (k < 0 or k >= w) break :blk 0;
|
|
||||||
const sh: u6 = @intCast(k);
|
|
||||||
break :blk (knownZero(m, f, repl, n, b.lhs, w, d) >> sh) | ~(mask >> sh);
|
|
||||||
},
|
|
||||||
else => 0,
|
|
||||||
},
|
|
||||||
.cast => |c| switch (c.op) {
|
|
||||||
.zext => blk: {
|
|
||||||
// (A phi promotion made has no instruction to read its
|
|
||||||
// type from yet.)
|
|
||||||
const src = resolve(repl, c.val);
|
|
||||||
if (src == .inst and src.inst >= n) break :blk 0;
|
|
||||||
const from = switch (m.types.items[typeOf(m, f, src)]) {
|
|
||||||
.int => |iw| iw,
|
|
||||||
else => break :blk 0,
|
|
||||||
};
|
|
||||||
const from_mask: u64 = if (from >= 64) ~@as(u64, 0) else (@as(u64, 1) << @intCast(from)) - 1;
|
|
||||||
break :blk knownZero(m, f, repl, n, c.val, from, d) | ~from_mask;
|
|
||||||
},
|
|
||||||
else => 0,
|
|
||||||
},
|
|
||||||
.select => |sl| knownZero(m, f, repl, n, sl.t, w, d) & knownZero(m, f, repl, n, sl.f, w, d),
|
|
||||||
else => 0,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `x & c` (`w` bits) when known bits decide it, as dxc's instcombine
|
|
||||||
/// does: 0 if every bit `c` keeps is known zero in `x`; `x` if every bit
|
|
||||||
/// it clears already is; and through `a | b` where `b` only has bits `c`
|
|
||||||
/// clears and `a` only bits it keeps, `a`. (Flags packed into one integer
|
|
||||||
/// with other fields, then tested.)
|
|
||||||
fn andKnown(m: *module.Module, f: *const module.Function, repl: []const ?Value, n: u32, x: Value, c: u64, w: u32, ty: TypeId) Allocator.Error!?Value {
|
|
||||||
const mask: u64 = if (w >= 64) ~@as(u64, 0) else (@as(u64, 1) << @intCast(w)) - 1;
|
|
||||||
const kz = knownZero(m, f, repl, n, x, w, 6);
|
|
||||||
if (c & ~kz & mask == 0) return try m.constant(.{ .ty = ty, .kind = .{ .int = 0 } });
|
|
||||||
if (~c & ~kz & mask == 0) return resolve(repl, x);
|
|
||||||
const xr = resolve(repl, x);
|
|
||||||
if (xr == .inst and xr.inst < n) {
|
|
||||||
const inst = f.insts.items[xr.inst];
|
|
||||||
if (inst.op == .binop and inst.op.binop.op == .@"or") {
|
|
||||||
const o = inst.op.binop;
|
|
||||||
const sides = [2][2]Value{ .{ o.lhs, o.rhs }, .{ o.rhs, o.lhs } };
|
|
||||||
for (sides) |ab| {
|
|
||||||
const kb = knownZero(m, f, repl, n, ab[1], w, 6);
|
|
||||||
const ka = knownZero(m, f, repl, n, ab[0], w, 6);
|
|
||||||
if (c & ~kb & mask == 0 and ~c & ~ka & mask == 0) return resolve(repl, ab[0]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A half, float or double constant of type `ty` with value `x` (rounded
|
|
||||||
/// to the type).
|
|
||||||
fn floatConst(m: *module.Module, ty: TypeId, x: f64) Allocator.Error!?Value {
|
|
||||||
const b: u64 = switch (m.types.items[ty]) {
|
|
||||||
.half => @as(u16, @bitCast(@as(f16, @floatCast(x)))),
|
|
||||||
.float => @as(u32, @bitCast(@as(f32, @floatCast(x)))),
|
|
||||||
.double => @bitCast(x),
|
|
||||||
else => return null,
|
|
||||||
};
|
|
||||||
return try m.constant(.{ .ty = ty, .kind = .{ .float_bits = b } });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `x op y` in `T`'s precision.
|
|
||||||
fn floatOp(comptime T: type, op: module.BinOp, x: f64, y: f64) ?f64 {
|
|
||||||
const a: T = @floatCast(x);
|
|
||||||
const c: T = @floatCast(y);
|
|
||||||
return @floatCast(switch (op) {
|
|
||||||
.add => a + c,
|
|
||||||
.sub => a - c,
|
|
||||||
.mul => a * c,
|
|
||||||
.sdiv => a / c,
|
|
||||||
.srem => if (c == 0 or std.math.isInf(a) or std.math.isNan(a) or std.math.isNan(c)) std.math.nan(T) else @rem(a, c),
|
|
||||||
else => return null,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Floating-point arithmetic on two constants, and the identities exact
|
|
||||||
/// in IEEE arithmetic (`x * 1`, `x / 1`, `x - 0`, `x + -0`), as dxc's
|
|
||||||
/// constant folding and instcombine fold them.
|
|
||||||
fn foldFloat(m: *module.Module, repl: []const ?Value, inst: Inst) Allocator.Error!?Value {
|
|
||||||
const b = inst.op.binop;
|
|
||||||
const is_float = switch (m.types.items[inst.ty]) {
|
|
||||||
.half, .float, .double => true,
|
|
||||||
else => false,
|
|
||||||
};
|
|
||||||
if (!is_float) return null;
|
|
||||||
const l = resolve(repl, b.lhs);
|
|
||||||
const r = resolve(repl, b.rhs);
|
|
||||||
const lc = constFloat(m, l);
|
|
||||||
const rc = constFloat(m, r);
|
|
||||||
if (lc != null and rc != null) {
|
|
||||||
const x = switch (m.types.items[inst.ty]) {
|
|
||||||
.half => floatOp(f16, b.op, lc.?, rc.?),
|
|
||||||
.float => floatOp(f32, b.op, lc.?, rc.?),
|
|
||||||
else => floatOp(f64, b.op, lc.?, rc.?),
|
|
||||||
} orelse return null;
|
|
||||||
return floatConst(m, inst.ty, x);
|
|
||||||
}
|
|
||||||
if (rc) |y| {
|
|
||||||
const neg_zero = y == 0 and std.math.signbit(y);
|
|
||||||
switch (b.op) {
|
|
||||||
.mul, .sdiv => if (y == 1) return l,
|
|
||||||
.sub => if (y == 0 and !neg_zero) return l,
|
|
||||||
.add => if (neg_zero) return l,
|
|
||||||
else => {},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (lc) |x| switch (b.op) {
|
|
||||||
.mul => if (x == 1) return r,
|
|
||||||
.add => if (x == 0 and std.math.signbit(x)) return r,
|
|
||||||
else => {},
|
|
||||||
};
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A dx.op call on constants, folded as dxc folds them (the operations
|
|
||||||
/// whose result does not depend on the GPU's precision, and the min / max
|
|
||||||
/// family).
|
|
||||||
fn foldDxOp(m: *module.Module, repl: []const ?Value, inst: Inst) Allocator.Error!?Value {
|
|
||||||
const c = inst.op.call;
|
|
||||||
if (!std.mem.startsWith(u8, m.functions.items[c.callee].name, "dx.op.")) return null;
|
|
||||||
if (c.args.len < 2) return null;
|
|
||||||
const opc = constInt(m, c.args[0]) orelse return null;
|
|
||||||
switch (opc) {
|
|
||||||
// FAbs, Saturate, Round_ne, Round_ni, Round_pi, Round_z, Sqrt
|
|
||||||
6, 7, 24, 26, 27, 28, 29 => {
|
|
||||||
if (c.args.len != 2) return null;
|
|
||||||
const x = constFloat(m, resolve(repl, c.args[1])) orelse return null;
|
|
||||||
if (std.math.isNan(x)) return null;
|
|
||||||
const y: f64 = switch (opc) {
|
|
||||||
6 => @abs(x),
|
|
||||||
7 => @min(@max(x, 0), 1),
|
|
||||||
24 => if (x < 0) return null else switch (m.types.items[inst.ty]) {
|
|
||||||
.half => @floatCast(@sqrt(@as(f16, @floatCast(x)))),
|
|
||||||
.float => @floatCast(@sqrt(@as(f32, @floatCast(x)))),
|
|
||||||
else => @sqrt(x),
|
|
||||||
},
|
|
||||||
// (Halves to even.)
|
|
||||||
26 => if (@abs(x - @trunc(x)) == 0.5) 2 * @round(x / 2) else @round(x),
|
|
||||||
27 => @floor(x),
|
|
||||||
28 => @ceil(x),
|
|
||||||
else => @trunc(x),
|
|
||||||
};
|
|
||||||
return floatConst(m, inst.ty, y);
|
|
||||||
},
|
|
||||||
// FMax, FMin
|
|
||||||
35, 36 => {
|
|
||||||
if (c.args.len != 3) return null;
|
|
||||||
const x = constFloat(m, resolve(repl, c.args[1])) orelse return null;
|
|
||||||
const y = constFloat(m, resolve(repl, c.args[2])) orelse return null;
|
|
||||||
if (std.math.isNan(x) or std.math.isNan(y)) return null;
|
|
||||||
return floatConst(m, inst.ty, if (opc == 35) @max(x, y) else @min(x, y));
|
|
||||||
},
|
|
||||||
// IMax, IMin, UMax, UMin
|
|
||||||
37, 38, 39, 40 => {
|
|
||||||
if (c.args.len != 3) return null;
|
|
||||||
const w: u32 = switch (m.types.items[inst.ty]) {
|
|
||||||
.int => |iw| iw,
|
|
||||||
else => return null,
|
|
||||||
};
|
|
||||||
const x = constInt(m, resolve(repl, c.args[1])) orelse return null;
|
|
||||||
const y = constInt(m, resolve(repl, c.args[2])) orelse return null;
|
|
||||||
// (Constants hold their value sign-extended: unsigned order is
|
|
||||||
// that of the w-bit patterns.)
|
|
||||||
const mask: u64 = if (w >= 64) ~@as(u64, 0) else (@as(u64, 1) << @intCast(w)) - 1;
|
|
||||||
const ux = @as(u64, @bitCast(x)) & mask;
|
|
||||||
const uy = @as(u64, @bitCast(y)) & mask;
|
|
||||||
const pick_x = switch (opc) {
|
|
||||||
37 => x >= y,
|
|
||||||
38 => x <= y,
|
|
||||||
39 => ux >= uy,
|
|
||||||
else => ux <= uy,
|
|
||||||
};
|
|
||||||
return if (pick_x) resolve(repl, c.args[1]) else resolve(repl, c.args[2]);
|
|
||||||
},
|
|
||||||
else => return null,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A half, float or double constant's value.
|
/// A half, float or double constant's value.
|
||||||
fn constFloat(m: *const module.Module, v: Value) ?f64 {
|
fn constFloat(m: *const module.Module, v: Value) ?f64 {
|
||||||
if (v != .constant) return null;
|
if (v != .constant) return null;
|
||||||
|
|
|
||||||
|
|
@ -5,13 +5,11 @@
|
||||||
//! Layout: a header (version, part count), part offsets, then each
|
//! Layout: a header (version, part count), part offsets, then each
|
||||||
//! non-empty part as (type, size) and its 4-byte aligned contents. Parts
|
//! non-empty part as (type, size) and its 4-byte aligned contents. Parts
|
||||||
//! come in the order dxc adds them: strings, resources, functions, index
|
//! come in the order dxc adds them: strings, resources, functions, index
|
||||||
//! arrays, raw bytes, subobjects, then the other record tables: work graph
|
//! arrays, raw bytes, subobjects, then the record tables of the extended
|
||||||
//! nodes (validator 1.8+) and the extended function properties (SM 6.10
|
//! function properties (SM 6.10 linear algebra).
|
||||||
//! linear algebra).
|
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
const shader = @import("shader.zig");
|
|
||||||
|
|
||||||
pub const null_ref: u32 = 0xffff_ffff;
|
pub const null_ref: u32 = 0xffff_ffff;
|
||||||
|
|
||||||
|
|
@ -26,8 +24,7 @@ pub const Resource = struct {
|
||||||
flags: u32 = 0,
|
flags: u32 = 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// RuntimeDataFunctionInfo3 (validator 1.10+; before, 2: without the
|
/// RuntimeDataFunctionInfo3 (validator 1.10+).
|
||||||
/// extended properties).
|
|
||||||
pub const Function = struct {
|
pub const Function = struct {
|
||||||
name: u32,
|
name: u32,
|
||||||
unmangled_name: u32,
|
unmangled_name: u32,
|
||||||
|
|
@ -47,14 +44,9 @@ pub const Function = struct {
|
||||||
extended_properties: u32 = null_ref,
|
extended_properties: u32 = null_ref,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The other record tables, by part type: work graph nodes (7..11) and
|
/// The extended function property tables, in part order (part types
|
||||||
/// the extended function properties (13..20).
|
/// 13..20).
|
||||||
pub const Ext = enum(u32) {
|
pub const Ext = enum(u32) {
|
||||||
node_ids = 7,
|
|
||||||
node_io_attribs,
|
|
||||||
node_func_attribs,
|
|
||||||
io_nodes,
|
|
||||||
node_shaders,
|
|
||||||
properties = 13,
|
properties = 13,
|
||||||
shapes,
|
shapes,
|
||||||
constructions,
|
constructions,
|
||||||
|
|
@ -67,10 +59,8 @@ pub const Ext = enum(u32) {
|
||||||
/// Record size in bytes.
|
/// Record size in bytes.
|
||||||
pub fn stride(t: Ext) usize {
|
pub fn stride(t: Ext) usize {
|
||||||
return switch (t) {
|
return switch (t) {
|
||||||
.node_shaders => 20,
|
|
||||||
.shapes => 12,
|
.shapes => 12,
|
||||||
.properties, .constructions, .wave_multiplies, .group_multiplies => 8,
|
.properties, .constructions, .wave_multiplies, .group_multiplies => 8,
|
||||||
.node_ids, .node_io_attribs, .node_func_attribs, .io_nodes => 8,
|
|
||||||
.thread_matvec, .outer_products, .accumulate_stores => 4,
|
.thread_matvec, .outer_products, .accumulate_stores => 4,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
@ -85,8 +75,7 @@ pub const Builder = struct {
|
||||||
functions: std.ArrayList([14]u32) = .empty,
|
functions: std.ArrayList([14]u32) = .empty,
|
||||||
raw: std.ArrayList(u8) = .empty,
|
raw: std.ArrayList(u8) = .empty,
|
||||||
subobjects: std.ArrayList([6]u32) = .empty,
|
subobjects: std.ArrayList([6]u32) = .empty,
|
||||||
/// By part type, from 7.
|
ext: [8]std.ArrayList(u8) = @splat(.empty),
|
||||||
ext: [14]std.ArrayList(u8) = @splat(.empty),
|
|
||||||
|
|
||||||
pub fn init(gpa: Allocator) Allocator.Error!Builder {
|
pub fn init(gpa: Allocator) Allocator.Error!Builder {
|
||||||
var b: Builder = .{ .gpa = gpa };
|
var b: Builder = .{ .gpa = gpa };
|
||||||
|
|
@ -126,10 +115,10 @@ pub const Builder = struct {
|
||||||
pub fn addFunction(b: *Builder, f: Function) Allocator.Error!void {
|
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);
|
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, .{
|
try b.functions.append(b.gpa, .{
|
||||||
f.name, f.unmangled_name, f.resources, f.function_dependencies,
|
f.name, f.unmangled_name, f.resources, f.function_dependencies,
|
||||||
f.shader_kind, f.payload_size, f.attribute_size, f.feature_info1,
|
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.feature_info2, f.shader_stage_flag, f.min_shader_target, packed_wave,
|
||||||
f.raw_shader_ref, f.extended_properties,
|
f.raw_shader_ref, f.extended_properties,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -143,7 +132,7 @@ pub const Builder = struct {
|
||||||
/// (record deduplication, validator 1.7+).
|
/// (record deduplication, validator 1.7+).
|
||||||
pub fn record(b: *Builder, t: Ext, rec: []const u8) Allocator.Error!u32 {
|
pub fn record(b: *Builder, t: Ext, rec: []const u8) Allocator.Error!u32 {
|
||||||
std.debug.assert(rec.len == t.stride());
|
std.debug.assert(rec.len == t.stride());
|
||||||
const tab = &b.ext[@backingInt(t) - 7];
|
const tab = &b.ext[@intFromEnum(t) - 13];
|
||||||
var at: usize = 0;
|
var at: usize = 0;
|
||||||
while (at < tab.items.len) : (at += rec.len) {
|
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);
|
if (std.mem.eql(u8, tab.items[at..][0..rec.len], rec)) return @intCast(at / rec.len);
|
||||||
|
|
@ -176,11 +165,7 @@ pub const Builder = struct {
|
||||||
try parts.append(b.gpa, .{ .ty = 3, .data = t });
|
try parts.append(b.gpa, .{ .ty = 3, .data = t });
|
||||||
}
|
}
|
||||||
if (b.functions.items.len > 0) {
|
if (b.functions.items.len > 0) {
|
||||||
const words: usize = if (shader.validatorAtLeast(1, 10)) 14 else 13;
|
const t = try table(b.gpa, 14, std.mem.sliceAsBytes(b.functions.items), b.functions.items.len);
|
||||||
const rows = try b.gpa.alloc(u32, words * b.functions.items.len);
|
|
||||||
defer b.gpa.free(rows);
|
|
||||||
for (b.functions.items, 0..) |f, k| @memcpy(rows[k * words ..][0..words], f[0..words]);
|
|
||||||
const t = try table(b.gpa, words, std.mem.sliceAsBytes(rows), b.functions.items.len);
|
|
||||||
try tables.append(b.gpa, t);
|
try tables.append(b.gpa, t);
|
||||||
try parts.append(b.gpa, .{ .ty = 4, .data = t });
|
try parts.append(b.gpa, .{ .ty = 4, .data = t });
|
||||||
}
|
}
|
||||||
|
|
@ -191,12 +176,8 @@ pub const Builder = struct {
|
||||||
try tables.append(b.gpa, t);
|
try tables.append(b.gpa, t);
|
||||||
try parts.append(b.gpa, .{ .ty = 6, .data = t });
|
try parts.append(b.gpa, .{ .ty = 6, .data = t });
|
||||||
}
|
}
|
||||||
// (dxc's table order: the node function attributes before the
|
for (b.ext, 13..) |rows, ty| if (rows.items.len > 0) {
|
||||||
// I/O attributes.)
|
const stride = @as(Ext, @enumFromInt(ty)).stride();
|
||||||
const order = [_]u32{ 7, 9, 8, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20 };
|
|
||||||
for (order) |ty| if (b.ext[ty - 7].items.len > 0) {
|
|
||||||
const rows = b.ext[ty - 7];
|
|
||||||
const stride = @as(Ext, @fromBackingInt(ty)).stride();
|
|
||||||
const t = try table(b.gpa, stride / 4, rows.items, rows.items.len / stride);
|
const t = try table(b.gpa, stride / 4, rows.items, rows.items.len / stride);
|
||||||
try tables.append(b.gpa, t);
|
try tables.append(b.gpa, t);
|
||||||
try parts.append(b.gpa, .{ .ty = @intCast(ty), .data = t });
|
try parts.append(b.gpa, .{ .ty = @intCast(ty), .data = t });
|
||||||
|
|
|
||||||
|
|
@ -71,16 +71,8 @@ pub const ComputeInfo = struct {
|
||||||
num_threads: [3]u32,
|
num_threads: [3]u32,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The validator version zdxc writes for (!dx.valver; matches the oracle
|
/// Validator version we claim in !dx.valver (matches the oracle dxc).
|
||||||
/// dxc). What its output looks like follows from it: PSVRuntimeInfo4 and
|
const valver = .{ 1, 11 };
|
||||||
/// RDAT's RuntimeDataFunctionInfo3 from 1.10. Testing with an older
|
|
||||||
/// validator means changing only this.
|
|
||||||
pub const validator: [2]u32 = .{ 1, 11 };
|
|
||||||
|
|
||||||
/// Whether the validator is at least `major.minor`.
|
|
||||||
pub fn validatorAtLeast(major: u32, minor: u32) bool {
|
|
||||||
return validator[0] > major or (validator[0] == major and validator[1] >= minor);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn buildEmptyCompute(gpa: Allocator, info: ComputeInfo) ![]u8 {
|
pub fn buildEmptyCompute(gpa: Allocator, info: ComputeInfo) ![]u8 {
|
||||||
var m = Module.init(gpa);
|
var m = Module.init(gpa);
|
||||||
|
|
@ -94,7 +86,7 @@ pub fn buildEmptyCompute(gpa: Allocator, info: ComputeInfo) ![]u8 {
|
||||||
// Metadata, in the same shape dxc emits.
|
// Metadata, in the same shape dxc emits.
|
||||||
const ident = try m.mdNode(&.{try m.mdString("zdxc 0.0.0")});
|
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 version = try m.mdNode(&.{ try m.mdI32(1), try m.mdI32(info.profile.minor) });
|
||||||
const val_ver = try m.mdNode(&.{ try m.mdI32(validator[0]), try m.mdI32(validator[1]) });
|
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 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 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 props = try m.mdNode(&.{ try m.mdI32(4), threads }); // kDxilNumThreadsTag
|
||||||
|
|
@ -151,8 +143,6 @@ pub const PsvInfo = struct {
|
||||||
/// The stage-specific PSVRuntimeInfo0 union.
|
/// The stage-specific PSVRuntimeInfo0 union.
|
||||||
stage_info: [16]u8 = @splat(0),
|
stage_info: [16]u8 = @splat(0),
|
||||||
num_threads: [3]u32 = .{ 0, 0, 0 },
|
num_threads: [3]u32 = .{ 0, 0, 0 },
|
||||||
/// Minimum and maximum expected wave lane counts (WaveSize).
|
|
||||||
wave_lanes: [2]u32 = .{ 0, 0xFFFFFFFF },
|
|
||||||
resources: []const ResourceBind = &.{},
|
resources: []const ResourceBind = &.{},
|
||||||
inputs: []const signature.Element = &.{},
|
inputs: []const signature.Element = &.{},
|
||||||
outputs: []const signature.Element = &.{},
|
outputs: []const signature.Element = &.{},
|
||||||
|
|
@ -169,7 +159,7 @@ pub fn psvCompute(gpa: Allocator, entry: []const u8, num_threads: [3]u32, resour
|
||||||
return psv(gpa, .{ .kind = .compute, .entry = entry, .num_threads = num_threads, .resources = resources });
|
return psv(gpa, .{ .kind = .compute, .entry = entry, .num_threads = num_threads, .resources = resources });
|
||||||
}
|
}
|
||||||
|
|
||||||
/// PSV0 with PSVRuntimeInfo4 (60 bytes; validator 1.10+) or 3 (52).
|
/// PSV0 with PSVRuntimeInfo4 (60 bytes), as produced for validator 1.11.
|
||||||
pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
|
pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
|
||||||
var buf: std.ArrayList(u8) = .empty;
|
var buf: std.ArrayList(u8) = .empty;
|
||||||
errdefer buf.deinit(gpa);
|
errdefer buf.deinit(gpa);
|
||||||
|
|
@ -179,12 +169,11 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
|
||||||
for (&out_vectors, 0..) |*v, s| v.* = signature.vectorsUsed(info.outputs, @intCast(s));
|
for (&out_vectors, 0..) |*v, s| v.* = signature.vectorsUsed(info.outputs, @intCast(s));
|
||||||
const pc_vectors = signature.vectorsUsed(info.patch_constants, 0);
|
const pc_vectors = signature.vectorsUsed(info.patch_constants, 0);
|
||||||
|
|
||||||
const info4 = validatorAtLeast(1, 10);
|
try w(&buf, gpa, 60); // sizeof(PSVRuntimeInfo4)
|
||||||
try w(&buf, gpa, if (info4) 60 else 52); // sizeof(PSVRuntimeInfo4 / 3)
|
|
||||||
// PSVRuntimeInfo0
|
// PSVRuntimeInfo0
|
||||||
try buf.appendSlice(gpa, &info.stage_info);
|
try buf.appendSlice(gpa, &info.stage_info);
|
||||||
try w(&buf, gpa, info.wave_lanes[0]); // MinimumExpectedWaveLaneCount
|
try w(&buf, gpa, 0); // MinimumExpectedWaveLaneCount
|
||||||
try w(&buf, gpa, info.wave_lanes[1]); // MaximumExpectedWaveLaneCount
|
try w(&buf, gpa, 0xFFFFFFFF); // MaximumExpectedWaveLaneCount
|
||||||
// PSVRuntimeInfo1: stage, UsesViewID, MaxVertexCount, element counts,
|
// PSVRuntimeInfo1: stage, UsesViewID, MaxVertexCount, element counts,
|
||||||
// vector counts.
|
// vector counts.
|
||||||
// (The MaxVertexCount union holds SigPatchConstOrPrimVectors for hull
|
// (The MaxVertexCount union holds SigPatchConstOrPrimVectors for hull
|
||||||
|
|
@ -232,7 +221,7 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
|
||||||
try w(&records, gpa, idx_off);
|
try w(&records, gpa, idx_off);
|
||||||
var cols_and_start: u8 = @intCast(e.cols);
|
var cols_and_start: u8 = @intCast(e.cols);
|
||||||
if (e.start_row != null) cols_and_start |= 0x40 | @as(u8, @intCast(e.start_col << 4));
|
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, @backingInt(e.kind), @intCast(e.comp.sigCompType()), @backingInt(e.interp), @intCast((e.stream & 3) << 4), 0 });
|
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);
|
const entry_off: u32 = @intCast(strings.items.len);
|
||||||
try strings.appendSlice(gpa, info.entry);
|
try strings.appendSlice(gpa, info.entry);
|
||||||
|
|
@ -241,11 +230,9 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
|
||||||
|
|
||||||
// PSVRuntimeInfo3: EntryFunctionName
|
// PSVRuntimeInfo3: EntryFunctionName
|
||||||
try w(&buf, gpa, entry_off);
|
try w(&buf, gpa, entry_off);
|
||||||
if (info4) {
|
// PSVRuntimeInfo4
|
||||||
// PSVRuntimeInfo4
|
try w(&buf, gpa, info.groupshared_bytes); // NumBytesGroupSharedMemory
|
||||||
try w(&buf, gpa, info.groupshared_bytes); // NumBytesGroupSharedMemory
|
try w(&buf, gpa, @intFromBool(linalg != null)); // Flags: LinAlgRuntimeInfoPresent
|
||||||
try w(&buf, gpa, @intFromBool(linalg != null)); // Flags: LinAlgRuntimeInfoPresent
|
|
||||||
}
|
|
||||||
|
|
||||||
try w(&buf, gpa, @intCast(info.resources.len));
|
try w(&buf, gpa, @intCast(info.resources.len));
|
||||||
if (info.resources.len > 0) {
|
if (info.resources.len > 0) {
|
||||||
|
|
|
||||||
|
|
@ -31,9 +31,6 @@ const none = std.math.maxInt(u32);
|
||||||
const max_trips = 256;
|
const max_trips = 256;
|
||||||
const max_loop_growth = 300;
|
const max_loop_growth = 300;
|
||||||
const max_growth = 65536;
|
const max_growth = 65536;
|
||||||
/// For `[unroll]` loops: dxc's limit on their iterations (its
|
|
||||||
/// DxilLoopUnroll), and no limit on their size but the function's.
|
|
||||||
const max_marked_trips = 1024;
|
|
||||||
|
|
||||||
/// Unrolls the qualifying loops of `func`, innermost first; true if any.
|
/// Unrolls the qualifying loops of `func`, innermost first; true if any.
|
||||||
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
|
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
|
||||||
|
|
@ -498,10 +495,6 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
// Innermost: no other loop's header inside.
|
// Innermost: no other loop's header inside.
|
||||||
for (loops.items) |other| if (other.h != h and lp.body.has(other.h)) continue :candidates;
|
for (loops.items) |other| if (other.h != h and lp.body.has(other.h)) continue :candidates;
|
||||||
try tried.put(a, h, {});
|
try tried.put(a, h, {});
|
||||||
// `[unroll]` (its back edge marked by the emitter).
|
|
||||||
const marked_loop = for (lp.latches) |l| {
|
|
||||||
if (insts[cfg.block_start[l + 1] - 1].md == .unroll) break true;
|
|
||||||
} else false;
|
|
||||||
|
|
||||||
// One way out: a conditional branch from one block, to one block.
|
// One way out: a conditional branch from one block, to one block.
|
||||||
var exiting: u32 = none;
|
var exiting: u32 = none;
|
||||||
|
|
@ -554,7 +547,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
while (true) {
|
while (true) {
|
||||||
const c = eval(m, f, &state, xcond, 0) orelse continue :candidates;
|
const c = eval(m, f, &state, xcond, 0) orelse continue :candidates;
|
||||||
if ((c & 1) != stay_on) break;
|
if ((c & 1) != stay_on) break;
|
||||||
if (states.items.len >= @as(usize, if (marked_loop) max_marked_trips else max_trips)) continue :candidates;
|
if (states.items.len >= max_trips) continue :candidates;
|
||||||
try states.append(a, try state.clone(a));
|
try states.append(a, try state.clone(a));
|
||||||
// Next values: what every latch passes back (the same).
|
// Next values: what every latch passes back (the same).
|
||||||
var next: std.AutoHashMapUnmanaged(u32, i64) = .empty;
|
var next: std.AutoHashMapUnmanaged(u32, i64) = .empty;
|
||||||
|
|
@ -577,7 +570,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
}
|
}
|
||||||
const trips = states.items.len;
|
const trips = states.items.len;
|
||||||
const growth = (trips + 1) * size;
|
const growth = (trips + 1) * size;
|
||||||
if ((!marked_loop and growth > max_loop_growth) or growth > budget.*) continue;
|
if (growth > max_loop_growth or growth > budget.*) continue;
|
||||||
budget.* -= growth;
|
budget.* -= growth;
|
||||||
try states.append(a, state); // the last pass, up to the exit
|
try states.append(a, state); // the last pass, up to the exit
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -41,8 +41,6 @@ pub const Parser = struct {
|
||||||
/// Name of the struct most recently parsed by parseStructDeclInto
|
/// Name of the struct most recently parsed by parseStructDeclInto
|
||||||
/// (synthesized for anonymous structs), for `typedef struct ...`.
|
/// (synthesized for anonymous structs), for `typedef struct ...`.
|
||||||
last_struct_name: []const u8 = "",
|
last_struct_name: []const u8 = "",
|
||||||
/// The last parseType read `const` after the type (`float const x`).
|
|
||||||
type_const: bool = false,
|
|
||||||
/// The qualifier words read by the last parseQualifiers call.
|
/// The qualifier words read by the last parseQualifiers call.
|
||||||
last_quals: []const ast.QualWord = &.{},
|
last_quals: []const ast.QualWord = &.{},
|
||||||
/// Qualifier words for the next parseDeclaratorsInto call.
|
/// Qualifier words for the next parseDeclaratorsInto call.
|
||||||
|
|
@ -412,8 +410,6 @@ pub const Parser = struct {
|
||||||
|
|
||||||
fn skipTypeAttrs(p: *const Parser, start: usize) usize {
|
fn skipTypeAttrs(p: *const Parser, start: usize) usize {
|
||||||
var i = start;
|
var i = start;
|
||||||
// `T const`: a type qualifier written after the type.
|
|
||||||
while (p.toks[i].isIdent("const")) i += 1;
|
|
||||||
if (!(p.toks[i].kind == .l_square and p.toks[i + 1].kind == .l_square)) return i;
|
if (!(p.toks[i].kind == .l_square and p.toks[i + 1].kind == .l_square)) return i;
|
||||||
var depth: u32 = 0;
|
var depth: u32 = 0;
|
||||||
while (true) : (i += 1) {
|
while (true) : (i += 1) {
|
||||||
|
|
@ -569,19 +565,10 @@ pub const Parser = struct {
|
||||||
t.pack_matrix = p.packMatrixAt(type_pos);
|
t.pack_matrix = p.packMatrixAt(type_pos);
|
||||||
if (norm != .none) t.norm = norm;
|
if (norm != .none) t.norm = norm;
|
||||||
if (words.items.len > 0) t.attr_words = words.items;
|
if (words.items.len > 0) t.attr_words = words.items;
|
||||||
p.type_const = false;
|
|
||||||
while (p.eatIdent("const")) p.type_const = true;
|
|
||||||
if (p.at(.l_square) and p.peek(1).kind == .l_square) t.attrs = try p.parseAttributes();
|
if (p.at(.l_square) and p.peek(1).kind == .l_square) t.attrs = try p.parseAttributes();
|
||||||
return t;
|
return t;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// parseType for a declaration: `const` after the type joins `quals`.
|
|
||||||
fn parseDeclType(p: *Parser, quals: *ast.Qualifiers) Error!*ast.TypeRef {
|
|
||||||
const t = try p.parseType();
|
|
||||||
if (p.type_const) quals.@"const" = true;
|
|
||||||
return t;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parseTypeInner(p: *Parser) Error!*ast.TypeRef {
|
fn parseTypeInner(p: *Parser) Error!*ast.TypeRef {
|
||||||
// An elaborated type: `struct S` names S (declaring it if needed).
|
// An elaborated type: `struct S` names S (declaring it if needed).
|
||||||
const elaborated = (p.atIdent("struct") or p.atIdent("class")) and p.peek(1).kind == .identifier and p.peek(2).kind != .l_brace and p.peek(2).kind != .colon;
|
const elaborated = (p.atIdent("struct") or p.atIdent("class")) and p.peek(1).kind == .identifier and p.peek(2).kind != .l_brace and p.peek(2).kind != .colon;
|
||||||
|
|
@ -848,9 +835,9 @@ pub const Parser = struct {
|
||||||
return out.append(p.arena, d);
|
return out.append(p.arena, d);
|
||||||
}
|
}
|
||||||
|
|
||||||
var quals = p.parseQualifiers();
|
const quals = p.parseQualifiers();
|
||||||
const words = p.last_quals;
|
const words = p.last_quals;
|
||||||
const ty = try p.parseDeclType(&quals);
|
const ty = try p.parseType();
|
||||||
p.decl_quals = words;
|
p.decl_quals = words;
|
||||||
const first = out.items.len;
|
const first = out.items.len;
|
||||||
try p.parseDeclaratorsInto(out, attrs, quals, template_params, ty, ctx);
|
try p.parseDeclaratorsInto(out, attrs, quals, template_params, ty, ctx);
|
||||||
|
|
@ -1312,9 +1299,9 @@ pub const Parser = struct {
|
||||||
if (p.atIdent("void") and p.peek(1).kind == .r_paren) _ = p.advance();
|
if (p.atIdent("void") and p.peek(1).kind == .r_paren) _ = p.advance();
|
||||||
while (!p.at(.r_paren)) {
|
while (!p.at(.r_paren)) {
|
||||||
const pattrs = try p.parseAttributes();
|
const pattrs = try p.parseAttributes();
|
||||||
var pquals = p.parseQualifiers();
|
const pquals = p.parseQualifiers();
|
||||||
const pwords = p.last_quals;
|
const pwords = p.last_quals;
|
||||||
const pty = try p.parseDeclType(&pquals);
|
const pty = try p.parseType();
|
||||||
var pname: []const u8 = "";
|
var pname: []const u8 = "";
|
||||||
var pname_loc = p.tok().loc;
|
var pname_loc = p.tok().loc;
|
||||||
if (p.at(.identifier) and !isReserved(p.tok().text)) {
|
if (p.at(.identifier) and !isReserved(p.tok().text)) {
|
||||||
|
|
@ -1520,8 +1507,8 @@ pub const Parser = struct {
|
||||||
/// `expr`, or `T name = init` (C++ condition declaration).
|
/// `expr`, or `T name = init` (C++ condition declaration).
|
||||||
fn parseCondition(p: *Parser) Error!struct { decl: ?*ast.Decl, cond: *ast.Expr } {
|
fn parseCondition(p: *Parser) Error!struct { decl: ?*ast.Decl, cond: *ast.Expr } {
|
||||||
if (!p.startsLocalDecl()) return .{ .decl = null, .cond = try p.parseExpr() };
|
if (!p.startsLocalDecl()) return .{ .decl = null, .cond = try p.parseExpr() };
|
||||||
var quals = p.parseQualifiers();
|
const quals = p.parseQualifiers();
|
||||||
const ty = try p.parseDeclType(&quals);
|
const ty = try p.parseType();
|
||||||
const name = try p.expectIdent("variable name");
|
const name = try p.expectIdent("variable name");
|
||||||
_ = try p.expect(.equal, "'='");
|
_ = try p.expect(.equal, "'='");
|
||||||
const init_expr = try p.parseAssign();
|
const init_expr = try p.parseAssign();
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,6 @@ const Allocator = std.mem.Allocator;
|
||||||
const ir = @import("ir.zig");
|
const ir = @import("ir.zig");
|
||||||
const types = @import("../sema/types.zig");
|
const types = @import("../sema/types.zig");
|
||||||
const opt = @import("opt.zig");
|
const opt = @import("opt.zig");
|
||||||
const split_resources = @import("split_resources.zig");
|
|
||||||
|
|
||||||
const Ref = ir.Ref;
|
const Ref = ir.Ref;
|
||||||
const BlockId = ir.BlockId;
|
const BlockId = ir.BlockId;
|
||||||
|
|
@ -74,41 +73,6 @@ pub fn run(m: *ir.Module) Error!void {
|
||||||
try markDead(m);
|
try markDead(m);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Inlines only the calls of functions that return a resource or a struct
|
|
||||||
/// holding one, in every kind of module (ray-tracing libraries included),
|
|
||||||
/// before resources are split out of structs: what such a function
|
|
||||||
/// returns can be an element of a resource array picked by an index it
|
|
||||||
/// computes (`bindless[NonUniformResourceIndex(i)]`), which no function
|
|
||||||
/// signature can pass back. dxc's legalization inlines everything.
|
|
||||||
pub fn runResourceReturns(m: *ir.Module) Error!void {
|
|
||||||
const a = m.arena;
|
|
||||||
const n = m.functions.items.len;
|
|
||||||
const shapes = try a.alloc(?Shape, n);
|
|
||||||
var any = false;
|
|
||||||
for (m.functions.items, shapes) |f, *sh| {
|
|
||||||
sh.* = .keep;
|
|
||||||
if (!isResource(m.types, f.ret) and !split_resources.holdsResources(m.types, f.ret)) continue;
|
|
||||||
const shape = try shapeOf(a, m, f);
|
|
||||||
sh.* = shape;
|
|
||||||
if (shape != .keep) any = true;
|
|
||||||
}
|
|
||||||
if (!any) return;
|
|
||||||
const done = try a.alloc(bool, n);
|
|
||||||
@memset(done, false);
|
|
||||||
var work: std.ArrayList(u32) = .empty;
|
|
||||||
for (m.entries.items) |e| {
|
|
||||||
try work.append(a, e.wrapper);
|
|
||||||
if (e.patch_wrapper) |pw| try work.append(a, pw);
|
|
||||||
}
|
|
||||||
try work.appendSlice(a, m.exports.items);
|
|
||||||
while (work.pop()) |fi| {
|
|
||||||
if (done[fi]) continue;
|
|
||||||
done[fi] = true;
|
|
||||||
try inlineCalls(m, m.functions.items[fi], shapes, &work);
|
|
||||||
}
|
|
||||||
try markDead(m);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How a function returns, for inlining it.
|
/// How a function returns, for inlining it.
|
||||||
const Shape = union(enum) {
|
const Shape = union(enum) {
|
||||||
/// Not inlinable.
|
/// Not inlinable.
|
||||||
|
|
|
||||||
|
|
@ -38,8 +38,7 @@ pub const BlockId = enum(u32) {
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Where a pointer points.
|
/// Where a pointer points.
|
||||||
/// (`node`: a work graph node record.)
|
pub const Space = enum { none, function, private, groupshared, resource, input, output, cbuffer, mesh, ray };
|
||||||
pub const Space = enum { none, function, private, groupshared, resource, input, output, cbuffer, mesh, ray, node };
|
|
||||||
|
|
||||||
/// Ray tracing shader storage an entry receives: the incoming payload,
|
/// Ray tracing shader storage an entry receives: the incoming payload,
|
||||||
/// the hit attributes and the incoming callable data.
|
/// the hit attributes and the incoming callable data.
|
||||||
|
|
@ -73,9 +72,6 @@ pub const Constant = union(enum) {
|
||||||
pub const Op = union(enum) {
|
pub const Op = union(enum) {
|
||||||
/// A scalar constant (or a vector of one constant, splatted).
|
/// A scalar constant (or a vector of one constant, splatted).
|
||||||
constant: Constant,
|
constant: Constant,
|
||||||
/// A node shader's input (`output` false) or its output `index`: the
|
|
||||||
/// node object (Entry.node's inputs / outputs).
|
|
||||||
node_io: struct { output: bool, index: u32 },
|
|
||||||
/// The function's `n`th parameter (a pointer for out / inout).
|
/// The function's `n`th parameter (a pointer for out / inout).
|
||||||
param: u32,
|
param: u32,
|
||||||
/// Pointer to a module global (resource, groupshared, static).
|
/// Pointer to a module global (resource, groupshared, static).
|
||||||
|
|
@ -360,8 +356,6 @@ pub const Stage = enum {
|
||||||
mesh,
|
mesh,
|
||||||
amplification,
|
amplification,
|
||||||
library,
|
library,
|
||||||
/// Work graph nodes (SM 6.8 libraries).
|
|
||||||
node,
|
|
||||||
raygeneration,
|
raygeneration,
|
||||||
intersection,
|
intersection,
|
||||||
anyhit,
|
anyhit,
|
||||||
|
|
@ -415,45 +409,6 @@ pub const OutputTopology = enum(u8) { point = 1, line = 2, triangle_cw = 3, tria
|
||||||
|
|
||||||
pub const MeshOutput = enum { vertices, primitives, indices };
|
pub const MeshOutput = enum { vertices, primitives, indices };
|
||||||
|
|
||||||
/// A node shader's properties (`[Shader("node")]`), from its attributes.
|
|
||||||
pub const NodeInfo = struct {
|
|
||||||
launch: Launch = .broadcasting,
|
|
||||||
is_program_entry: bool = false,
|
|
||||||
/// `[NodeID("name", index)]`; by default the function's name, 0.
|
|
||||||
id: NodeId,
|
|
||||||
local_root_arguments_table_index: ?u32 = null,
|
|
||||||
share_input_of: ?NodeId = null,
|
|
||||||
dispatch_grid: ?[3]u32 = null,
|
|
||||||
max_dispatch_grid: ?[3]u32 = null,
|
|
||||||
max_recursion_depth: ?u32 = null,
|
|
||||||
inputs: []const NodeIo = &.{},
|
|
||||||
outputs: []const NodeIo = &.{},
|
|
||||||
|
|
||||||
/// NodeLaunchType.
|
|
||||||
pub const Launch = enum(u32) { broadcasting = 1, coalescing = 2, thread = 3 };
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const NodeId = struct { name: []const u8, index: u32 = 0 };
|
|
||||||
|
|
||||||
/// One node input or output: a parameter of a node object type.
|
|
||||||
pub const NodeIo = struct {
|
|
||||||
kind: types.NodeKind,
|
|
||||||
/// The record type (void for empty inputs / outputs).
|
|
||||||
record: TypeId,
|
|
||||||
/// I/O flags beyond the kind: TrackRWInputSharing 0x100,
|
|
||||||
/// GloballyCoherent 0x200.
|
|
||||||
extra_flags: u32 = 0,
|
|
||||||
/// Outputs: `[NodeID]`, by default the parameter's name, 0.
|
|
||||||
output_id: ?NodeId = null,
|
|
||||||
max_records: ?u32 = null,
|
|
||||||
/// Outputs: the index of the output whose records these share.
|
|
||||||
max_records_shared_with: ?u32 = null,
|
|
||||||
/// Output arrays: `[NodeArraySize(n)]`, or maxInt for
|
|
||||||
/// `[UnboundedSparseNodes]`.
|
|
||||||
array_size: ?u32 = null,
|
|
||||||
allow_sparse_nodes: bool = false,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const MeshInfo = struct {
|
pub const MeshInfo = struct {
|
||||||
max_vertices: u32 = 0,
|
max_vertices: u32 = 0,
|
||||||
max_primitives: u32 = 0,
|
max_primitives: u32 = 0,
|
||||||
|
|
@ -481,14 +436,9 @@ pub const Entry = struct {
|
||||||
name: []const u8,
|
name: []const u8,
|
||||||
stage: Stage,
|
stage: Stage,
|
||||||
num_threads: [3]u32 = .{ 1, 1, 1 },
|
num_threads: [3]u32 = .{ 1, 1, 1 },
|
||||||
/// `[WaveSize(min[, max[, preferred]])]`: zeros where not given (no
|
|
||||||
/// attribute: min 0).
|
|
||||||
wave_size: [3]u32 = .{ 0, 0, 0 },
|
|
||||||
geometry: GeometryInfo = .{},
|
geometry: GeometryInfo = .{},
|
||||||
tess: TessInfo = .{},
|
tess: TessInfo = .{},
|
||||||
mesh: MeshInfo = .{},
|
mesh: MeshInfo = .{},
|
||||||
/// Node shaders.
|
|
||||||
node: ?NodeInfo = null,
|
|
||||||
inputs: std.ArrayList(SigElement) = .empty,
|
inputs: std.ArrayList(SigElement) = .empty,
|
||||||
outputs: std.ArrayList(SigElement) = .empty,
|
outputs: std.ArrayList(SigElement) = .empty,
|
||||||
/// Patch constants: written by the hull shader's patch constant
|
/// Patch constants: written by the hull shader's patch constant
|
||||||
|
|
@ -533,9 +483,8 @@ pub const SpirvExt = struct {
|
||||||
pub const SpirvInst = struct {
|
pub const SpirvInst = struct {
|
||||||
opcode: u32,
|
opcode: u32,
|
||||||
set: ?[]const u8 = null,
|
set: ?[]const u8 = null,
|
||||||
/// Values, pointers (`[[vk::ext_reference]]`), literal words, types,
|
/// Values, pointers (`[[vk::ext_reference]]`) or literal words.
|
||||||
/// or the id of an OpString (printf's format).
|
operands: []const union(enum) { value: Ref, literal: u32, type: TypeId },
|
||||||
operands: []const union(enum) { value: Ref, literal: u32, type: TypeId, string: []const u8 },
|
|
||||||
capabilities: []const u32 = &.{},
|
capabilities: []const u32 = &.{},
|
||||||
extensions: []const []const u8 = &.{},
|
extensions: []const []const u8 = &.{},
|
||||||
};
|
};
|
||||||
|
|
@ -709,7 +658,6 @@ fn dumpInst(m: *const Module, f: *const Function, r: Ref, w: *std.Io.Writer) !vo
|
||||||
.float => |v| try w.print("const {d}", .{v}),
|
.float => |v| try w.print("const {d}", .{v}),
|
||||||
},
|
},
|
||||||
.param => |p| try w.print("param {d}", .{p}),
|
.param => |p| try w.print("param {d}", .{p}),
|
||||||
.node_io => |x| try w.print("node_{s} {d}", .{ if (x.output) "output" else "input", x.index }),
|
|
||||||
.global => |g| try w.print("global @{d}", .{g}),
|
.global => |g| try w.print("global @{d}", .{g}),
|
||||||
.local_var => try w.writeAll("local_var"),
|
.local_var => try w.writeAll("local_var"),
|
||||||
.load => |p| try w.print("load %{d}", .{p.index()}),
|
.load => |p| try w.print("load %{d}", .{p.index()}),
|
||||||
|
|
|
||||||
260
src/ir/lower.zig
260
src/ir/lower.zig
|
|
@ -73,21 +73,11 @@ pub fn lowerUnit(arena: Allocator, s: *Sema, opts: Options) Error!ir.Module {
|
||||||
/// The stage a `[shader("...")]` attribute names.
|
/// The stage a `[shader("...")]` attribute names.
|
||||||
fn stageNamed(name: []const u8) ?ir.Stage {
|
fn stageNamed(name: []const u8) ?ir.Stage {
|
||||||
const names = [_]struct { []const u8, ir.Stage }{
|
const names = [_]struct { []const u8, ir.Stage }{
|
||||||
.{ "node", .node },
|
.{ "vertex", .vertex }, .{ "pixel", .pixel }, .{ "geometry", .geometry },
|
||||||
.{ "vertex", .vertex },
|
.{ "hull", .hull }, .{ "domain", .domain }, .{ "compute", .compute },
|
||||||
.{ "pixel", .pixel },
|
.{ "mesh", .mesh }, .{ "amplification", .amplification }, .{ "raygeneration", .raygeneration },
|
||||||
.{ "geometry", .geometry },
|
.{ "intersection", .intersection }, .{ "anyhit", .anyhit }, .{ "closesthit", .closesthit },
|
||||||
.{ "hull", .hull },
|
.{ "miss", .miss }, .{ "callable", .callable },
|
||||||
.{ "domain", .domain },
|
|
||||||
.{ "compute", .compute },
|
|
||||||
.{ "mesh", .mesh },
|
|
||||||
.{ "amplification", .amplification },
|
|
||||||
.{ "raygeneration", .raygeneration },
|
|
||||||
.{ "intersection", .intersection },
|
|
||||||
.{ "anyhit", .anyhit },
|
|
||||||
.{ "closesthit", .closesthit },
|
|
||||||
.{ "miss", .miss },
|
|
||||||
.{ "callable", .callable },
|
|
||||||
};
|
};
|
||||||
for (names) |t| if (std.ascii.eqlIgnoreCase(name, t[0])) return t[1];
|
for (names) |t| if (std.ascii.eqlIgnoreCase(name, t[0])) return t[1];
|
||||||
return null;
|
return null;
|
||||||
|
|
@ -328,10 +318,10 @@ const Lowerer = struct {
|
||||||
fn subobjects(l: *Lowerer) Error!void {
|
fn subobjects(l: *Lowerer) Error!void {
|
||||||
const Kind = ir.Subobject.Kind;
|
const Kind = ir.Subobject.Kind;
|
||||||
const kinds = [_]struct { []const u8, Kind }{
|
const kinds = [_]struct { []const u8, Kind }{
|
||||||
.{ "StateObjectConfig", .state_object_config }, .{ "GlobalRootSignature", .global_root_signature },
|
.{ "StateObjectConfig", .state_object_config }, .{ "GlobalRootSignature", .global_root_signature },
|
||||||
.{ "LocalRootSignature", .local_root_signature }, .{ "SubobjectToExportsAssociation", .subobject_to_exports_association },
|
.{ "LocalRootSignature", .local_root_signature }, .{ "SubobjectToExportsAssociation", .subobject_to_exports_association },
|
||||||
.{ "RaytracingShaderConfig", .raytracing_shader_config }, .{ "RaytracingPipelineConfig", .raytracing_pipeline_config },
|
.{ "RaytracingShaderConfig", .raytracing_shader_config }, .{ "RaytracingPipelineConfig", .raytracing_pipeline_config },
|
||||||
.{ "TriangleHitGroup", .hit_group }, .{ "ProceduralPrimitiveHitGroup", .hit_group },
|
.{ "TriangleHitGroup", .hit_group }, .{ "ProceduralPrimitiveHitGroup", .hit_group },
|
||||||
.{ "RaytracingPipelineConfig1", .raytracing_pipeline_config1 },
|
.{ "RaytracingPipelineConfig1", .raytracing_pipeline_config1 },
|
||||||
};
|
};
|
||||||
// (Builtin objects are static globals.)
|
// (Builtin objects are static globals.)
|
||||||
|
|
@ -1080,13 +1070,6 @@ const Lowerer = struct {
|
||||||
const idx = try l.indexValue(x.index, bt.resource.kind.indexDims());
|
const idx = try l.indexValue(x.index, bt.resource.kind.indexDims());
|
||||||
return l.b.add(.{ .op = .{ .res_load = .{ .res = res, .index = idx } }, .ty = try l.concrete(e.ty) });
|
return l.b.add(.{ .op = .{ .res_load = .{ .res = res, .index = idx } }, .ty = try l.concrete(e.ty) });
|
||||||
}
|
}
|
||||||
if (bt == .node) {
|
|
||||||
if (bt.node.kind.isArray()) return l.b.load(try l.nodeRecordPtr(e));
|
|
||||||
// An output of an outputs array: the node object.
|
|
||||||
const obj = try l.rvalue(x.base);
|
|
||||||
const idx = try l.converted(x.index, try t.scalar(.uint));
|
|
||||||
return l.b.add(.{ .op = .{ .access = .{ .base = obj, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = e.ty });
|
|
||||||
}
|
|
||||||
if (isAddressable(l.s, x.base)) return l.b.load(try l.lvalue(e));
|
if (isAddressable(l.s, x.base)) return l.b.load(try l.lvalue(e));
|
||||||
const base = try l.rvalue(x.base);
|
const base = try l.rvalue(x.base);
|
||||||
if (l.s.evalInt(x.index)) |k| return l.b.add(.{ .op = .{ .extract = .{ .agg = base, .index = @intCast(k) } }, .ty = try l.concrete(e.ty) });
|
if (l.s.evalInt(x.index)) |k| return l.b.add(.{ .op = .{ .extract = .{ .agg = base, .index = @intCast(k) } }, .ty = try l.concrete(e.ty) });
|
||||||
|
|
@ -1394,7 +1377,6 @@ const Lowerer = struct {
|
||||||
fn call(l: *Lowerer, e: *ast.Expr, callee: *ast.Expr, args: []const *ast.Expr) Error!Ref {
|
fn call(l: *Lowerer, e: *ast.Expr, callee: *ast.Expr, args: []const *ast.Expr) Error!Ref {
|
||||||
const r = l.s.resolution(e) orelse return l.fail(e, "this call");
|
const r = l.s.resolution(e) orelse return l.fail(e, "this call");
|
||||||
const ret_ty = try l.concrete(e.ty);
|
const ret_ty = try l.concrete(e.ty);
|
||||||
if (r == .node_record) return l.b.load(try l.nodeRecordPtr(e));
|
|
||||||
switch (r) {
|
switch (r) {
|
||||||
.function => |f| {
|
.function => |f| {
|
||||||
if (!f.defined and hasAttr(f.decl.attrs, "vk::ext_instruction")) return l.spirvInstCall(e, f, args, ret_ty);
|
if (!f.defined and hasAttr(f.decl.attrs, "vk::ext_instruction")) return l.spirvInstCall(e, f, args, ret_ty);
|
||||||
|
|
@ -1430,49 +1412,49 @@ const Lowerer = struct {
|
||||||
/// A call to `f` with `base_expr` as the object of a method (null:
|
/// A call to `f` with `base_expr` as the object of a method (null:
|
||||||
/// the current `this`, or no object).
|
/// the current `this`, or no object).
|
||||||
fn methodCall(l: *Lowerer, f: *const semamod.Function, fi: u32, base_expr: ?*ast.Expr, args: []const *ast.Expr, ret_ty: TypeId) Error!Ref {
|
fn methodCall(l: *Lowerer, f: *const semamod.Function, fi: u32, base_expr: ?*ast.Expr, args: []const *ast.Expr, ret_ty: TypeId) Error!Ref {
|
||||||
var object: ?Ref = null;
|
var object: ?Ref = null;
|
||||||
var write_back: ?Ref = null;
|
var write_back: ?Ref = null;
|
||||||
const owner_ty = if (isMethod(f)) try l.s.types.intern(.{ .@"struct" = f.owner.? }) else TypeTable.void_type;
|
const owner_ty = if (isMethod(f)) try l.s.types.intern(.{ .@"struct" = f.owner.? }) else TypeTable.void_type;
|
||||||
if (base_expr) |base| {
|
if (base_expr) |base| {
|
||||||
const direct = if (isAddressable(l.s, base)) try l.lvalue(base) else null;
|
const direct = if (isAddressable(l.s, base)) try l.lvalue(base) else null;
|
||||||
const plain = if (direct) |p| l.b.f.inst(p).op == .local_var or l.b.f.inst(p).op == .param else false;
|
const plain = if (direct) |p| l.b.f.inst(p).op == .local_var or l.b.f.inst(p).op == .param else false;
|
||||||
if (direct != null and plain and base.ty == owner_ty) {
|
if (direct != null and plain and base.ty == owner_ty) {
|
||||||
object = direct;
|
object = direct;
|
||||||
} else {
|
} else {
|
||||||
// Through a function-local copy of the method's own
|
// Through a function-local copy of the method's own
|
||||||
// struct (a base prefix of derived objects), written
|
// struct (a base prefix of derived objects), written
|
||||||
// back afterwards to writable storage.
|
// back afterwards to writable storage.
|
||||||
const tmp = try l.b.add(.{ .op = .local_var, .ty = owner_ty, .ptr = .function });
|
const tmp = try l.b.add(.{ .op = .local_var, .ty = owner_ty, .ptr = .function });
|
||||||
var whole = if (direct) |p| try l.b.load(p) else try l.rvalue(base);
|
var whole = if (direct) |p| try l.b.load(p) else try l.rvalue(base);
|
||||||
var whole_ty = base.ty;
|
var whole_ty = base.ty;
|
||||||
if (l.s.types.get(base.ty) == .resource) {
|
if (l.s.types.get(base.ty) == .resource) {
|
||||||
// A method of ConstantBuffer<S>'s S: on a copy of S.
|
// A method of ConstantBuffer<S>'s S: on a copy of S.
|
||||||
whole_ty = l.s.types.get(base.ty).resource.elem;
|
whole_ty = l.s.types.get(base.ty).resource.elem;
|
||||||
whole = try l.convert(whole, whole_ty);
|
whole = try l.convert(whole, whole_ty);
|
||||||
}
|
}
|
||||||
try l.b.store(tmp, try l.basePrefix(whole, whole_ty, owner_ty));
|
try l.b.store(tmp, try l.basePrefix(whole, whole_ty, owner_ty));
|
||||||
object = tmp;
|
object = tmp;
|
||||||
if (direct) |p| switch (l.b.f.inst(p).ptr) {
|
if (direct) |p| switch (l.b.f.inst(p).ptr) {
|
||||||
.function, .private, .groupshared => write_back = p,
|
.function, .private, .groupshared => write_back = p,
|
||||||
else => {},
|
else => {},
|
||||||
};
|
};
|
||||||
}
|
|
||||||
}
|
|
||||||
const res = try l.userCall(f, fi, args, ret_ty, object);
|
|
||||||
if (write_back) |p| {
|
|
||||||
const updated = try l.b.load(object.?);
|
|
||||||
if (base_expr.?.ty == owner_ty) {
|
|
||||||
try l.b.store(p, updated);
|
|
||||||
} else {
|
|
||||||
// Only the base's fields.
|
|
||||||
for (l.s.types.get(owner_ty).@"struct".fields.items, 0..) |fld, k| {
|
|
||||||
const idx = try l.b.constInt(try l.types().scalar(.uint), @intCast(k));
|
|
||||||
const fp = try l.b.add(.{ .op = .{ .access = .{ .base = p, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = fld.type, .ptr = l.b.f.inst(p).ptr });
|
|
||||||
try l.b.store(fp, try l.b.add(.{ .op = .{ .extract = .{ .agg = updated, .index = @intCast(k) } }, .ty = fld.type }));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
const res = try l.userCall(f, fi, args, ret_ty, object);
|
||||||
return res;
|
if (write_back) |p| {
|
||||||
|
const updated = try l.b.load(object.?);
|
||||||
|
if (base_expr.?.ty == owner_ty) {
|
||||||
|
try l.b.store(p, updated);
|
||||||
|
} else {
|
||||||
|
// Only the base's fields.
|
||||||
|
for (l.s.types.get(owner_ty).@"struct".fields.items, 0..) |fld, k| {
|
||||||
|
const idx = try l.b.constInt(try l.types().scalar(.uint), @intCast(k));
|
||||||
|
const fp = try l.b.add(.{ .op = .{ .access = .{ .base = p, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = fld.type, .ptr = l.b.f.inst(p).ptr });
|
||||||
|
try l.b.store(fp, try l.b.add(.{ .op = .{ .extract = .{ .agg = updated, .index = @intCast(k) } }, .ty = fld.type }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An overloaded operator: a method call on the first operand.
|
/// An overloaded operator: a method call on the first operand.
|
||||||
|
|
@ -1565,16 +1547,6 @@ const Lowerer = struct {
|
||||||
};
|
};
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
// printf: NonSemantic.DebugPrintf's DebugPrintf (opcode 1)
|
|
||||||
// with the format as an OpString (SPIR-V only).
|
|
||||||
if (std.mem.eql(u8, name, "printf") and l.s.opts.spirv and args.len >= 1 and args[0].kind == .string_lit) {
|
|
||||||
const p = try l.arena.create(ir.SpirvInst);
|
|
||||||
const ops = try l.arena.alloc(@typeInfo(@TypeOf(p.operands)).pointer.child, args.len);
|
|
||||||
ops[0] = .{ .string = try stringContents(l.arena, args[0].kind.string_lit) };
|
|
||||||
for (ops[1..], args[1..]) |*o, a| o.* = .{ .value = try l.converted(a, try l.concrete(a.ty)) };
|
|
||||||
p.* = .{ .opcode = 1, .set = "NonSemantic.DebugPrintf", .operands = ops, .extensions = try l.arena.dupe([]const u8, &.{"SPV_KHR_non_semantic_info"}) };
|
|
||||||
return l.b.add(.{ .op = .{ .spirv_inst = p }, .ty = TypeTable.void_type });
|
|
||||||
}
|
|
||||||
if (std.mem.eql(u8, name, "DispatchMesh") and args.len == 4) {
|
if (std.mem.eql(u8, name, "DispatchMesh") and args.len == 4) {
|
||||||
// The payload goes by reference (a groupshared
|
// The payload goes by reference (a groupshared
|
||||||
// variable).
|
// variable).
|
||||||
|
|
@ -1782,22 +1754,7 @@ const Lowerer = struct {
|
||||||
return l.b.add(.{ .op = .{ .global = g }, .ty = glob.ty, .ptr = glob.space });
|
return l.b.add(.{ .op = .{ .global = g }, .ty = glob.ty, .ptr = glob.space });
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A node record: `obj.Get()`, `obj.Get(i)` or `obj[i]` (an element
|
|
||||||
/// of the node object, in node record memory).
|
|
||||||
fn nodeRecordPtr(l: *Lowerer, e: *ast.Expr) Error!Ref {
|
|
||||||
const t = l.types();
|
|
||||||
const obj_expr, const index: ?*ast.Expr = switch (e.kind) {
|
|
||||||
.call => |c| .{ c.callee.kind.member.base, if (c.args.len > 0) c.args[0] else null },
|
|
||||||
.index => |x| .{ x.base, x.index },
|
|
||||||
else => return l.fail(e, "this node record"),
|
|
||||||
};
|
|
||||||
const obj = try l.rvalue(obj_expr);
|
|
||||||
const idx = if (index) |i| try l.converted(i, try t.scalar(.uint)) else try l.b.constInt(try t.scalar(.uint), 0);
|
|
||||||
return l.b.add(.{ .op = .{ .access = .{ .base = obj, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = e.ty, .ptr = .node });
|
|
||||||
}
|
|
||||||
|
|
||||||
fn lvalue(l: *Lowerer, e: *ast.Expr) Error!Ref {
|
fn lvalue(l: *Lowerer, e: *ast.Expr) Error!Ref {
|
||||||
if (l.s.resolution(e)) |r| if (r == .node_record) return l.nodeRecordPtr(e);
|
|
||||||
const t = l.types();
|
const t = l.types();
|
||||||
// A resource inside a global struct: its own global.
|
// A resource inside a global struct: its own global.
|
||||||
if (e.kind == .member or e.kind == .index) if (l.uniformPath(e)) |up| if (layout.isOpaque(t, e.ty)) return l.leafGlobal(up.v, up.path, e.ty);
|
if (e.kind == .member or e.kind == .index) if (l.uniformPath(e)) |up| if (layout.isOpaque(t, e.ty)) return l.leafGlobal(up.v, up.path, e.ty);
|
||||||
|
|
@ -2464,97 +2421,6 @@ const Lowerer = struct {
|
||||||
entry.patch_wrapper = wrapper;
|
entry.patch_wrapper = wrapper;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A node shader's properties: its attributes and its node object
|
|
||||||
/// parameters (inputs, then outputs, in parameter order).
|
|
||||||
fn nodeInfo(l: *Lowerer, f: *const semamod.Function) Error!ir.NodeInfo {
|
|
||||||
const eqi = std.ascii.eqlIgnoreCase;
|
|
||||||
var info: ir.NodeInfo = .{ .id = .{ .name = f.name } };
|
|
||||||
for (f.decl.attrs) |a| {
|
|
||||||
if (eqi(a.name, "nodelaunch") and a.args.len == 1 and a.args[0].kind == .string_lit) {
|
|
||||||
const v = try stringContents(l.arena, a.args[0].kind.string_lit);
|
|
||||||
if (eqi(v, "coalescing")) info.launch = .coalescing else if (eqi(v, "thread")) info.launch = .thread else info.launch = .broadcasting;
|
|
||||||
} else if (eqi(a.name, "nodeisprogramentry")) {
|
|
||||||
info.is_program_entry = true;
|
|
||||||
} else if (eqi(a.name, "nodeid")) {
|
|
||||||
if (try l.nodeId(a)) |id| info.id = id;
|
|
||||||
} else if (eqi(a.name, "nodelocalrootargumentstableindex") and a.args.len == 1) {
|
|
||||||
info.local_root_arguments_table_index = l.attrUint(a.args[0]);
|
|
||||||
} else if (eqi(a.name, "nodeshareinputof")) {
|
|
||||||
info.share_input_of = try l.nodeId(a);
|
|
||||||
} else if (eqi(a.name, "nodedispatchgrid") and a.args.len == 3) {
|
|
||||||
info.dispatch_grid = .{ l.attrUint(a.args[0]), l.attrUint(a.args[1]), l.attrUint(a.args[2]) };
|
|
||||||
} else if (eqi(a.name, "nodemaxdispatchgrid") and a.args.len == 3) {
|
|
||||||
info.max_dispatch_grid = .{ l.attrUint(a.args[0]), l.attrUint(a.args[1]), l.attrUint(a.args[2]) };
|
|
||||||
} else if (eqi(a.name, "nodemaxrecursiondepth") and a.args.len == 1) {
|
|
||||||
info.max_recursion_depth = l.attrUint(a.args[0]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var inputs: std.ArrayList(ir.NodeIo) = .empty;
|
|
||||||
var outputs: std.ArrayList(ir.NodeIo) = .empty;
|
|
||||||
var out_names: std.ArrayList([]const u8) = .empty;
|
|
||||||
// MaxRecordsSharedWith names a later output too: resolved after.
|
|
||||||
var shared: std.ArrayList(struct { out: usize, name: []const u8 }) = .empty;
|
|
||||||
for (f.decl.params, f.params) |pd, p| {
|
|
||||||
const nt = switch (l.s.types.get(p.type)) {
|
|
||||||
.node => |x| x,
|
|
||||||
else => continue,
|
|
||||||
};
|
|
||||||
var io: ir.NodeIo = .{ .kind = nt.kind, .record = nt.elem };
|
|
||||||
if (pd.quals.globallycoherent) io.extra_flags |= 0x200;
|
|
||||||
if (nt.elem != TypeTable.void_type and l.trackRwInputSharing(nt.elem)) io.extra_flags |= 0x100;
|
|
||||||
if (!nt.kind.isInput()) io.output_id = .{ .name = pd.name };
|
|
||||||
for (pd.attrs) |a| {
|
|
||||||
if (eqi(a.name, "maxrecords") and a.args.len == 1) {
|
|
||||||
io.max_records = l.attrUint(a.args[0]);
|
|
||||||
} else if (eqi(a.name, "nodeid")) {
|
|
||||||
if (try l.nodeId(a)) |id| io.output_id = id;
|
|
||||||
} else if (eqi(a.name, "nodearraysize") and a.args.len == 1) {
|
|
||||||
io.array_size = l.attrUint(a.args[0]);
|
|
||||||
} else if (eqi(a.name, "unboundedsparsenodes")) {
|
|
||||||
io.array_size = std.math.maxInt(u32);
|
|
||||||
io.allow_sparse_nodes = true;
|
|
||||||
} else if (eqi(a.name, "allowsparsenodes")) {
|
|
||||||
io.allow_sparse_nodes = true;
|
|
||||||
} else if (eqi(a.name, "maxrecordssharedwith") and a.args.len == 1 and a.args[0].kind == .name) {
|
|
||||||
try shared.append(l.arena, .{ .out = outputs.items.len, .name = a.args[0].kind.name.last() });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (nt.kind.isInput()) {
|
|
||||||
try inputs.append(l.arena, io);
|
|
||||||
} else {
|
|
||||||
try outputs.append(l.arena, io);
|
|
||||||
try out_names.append(l.arena, pd.name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (shared.items) |sh| {
|
|
||||||
for (out_names.items, 0..) |n, k| if (std.mem.eql(u8, n, sh.name)) {
|
|
||||||
outputs.items[sh.out].max_records_shared_with = @intCast(k);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
info.inputs = inputs.items;
|
|
||||||
info.outputs = outputs.items;
|
|
||||||
return info;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `[NodeID("name"[, index])]`, `[NodeShareInputOf(...)]`.
|
|
||||||
fn nodeId(l: *Lowerer, a: ast.Attribute) Error!?ir.NodeId {
|
|
||||||
if (a.args.len < 1 or a.args[0].kind != .string_lit) return null;
|
|
||||||
return .{ .name = try stringContents(l.arena, a.args[0].kind.string_lit), .index = if (a.args.len > 1) l.attrUint(a.args[1]) else 0 };
|
|
||||||
}
|
|
||||||
|
|
||||||
fn attrUint(l: *Lowerer, e: *const ast.Expr) u32 {
|
|
||||||
return @intCast(std.math.clamp(l.s.evalInt(e) orelse 0, 0, std.math.maxInt(u32)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A record struct declared `[NodeTrackRWInputSharing]`.
|
|
||||||
fn trackRwInputSharing(l: *Lowerer, record: TypeId) bool {
|
|
||||||
const info = switch (l.s.types.get(record)) {
|
|
||||||
.@"struct" => |s| s,
|
|
||||||
else => return false,
|
|
||||||
};
|
|
||||||
return l.s.structHasAttr(info, "nodetrackrwinputsharing");
|
|
||||||
}
|
|
||||||
|
|
||||||
fn buildEntry(l: *Lowerer, f: *const semamod.Function, main: u32, opts: Options) Error!void {
|
fn buildEntry(l: *Lowerer, f: *const semamod.Function, main: u32, opts: Options) Error!void {
|
||||||
const inits = try l.staticInits();
|
const inits = try l.staticInits();
|
||||||
var entry: ir.Entry = .{ .func = main, .name = opts.entry, .stage = opts.stage, .ext = try l.spirvExt(f.decl.attrs) };
|
var entry: ir.Entry = .{ .func = main, .name = opts.entry, .stage = opts.stage, .ext = try l.spirvExt(f.decl.attrs) };
|
||||||
|
|
@ -2563,9 +2429,6 @@ const Lowerer = struct {
|
||||||
if (std.ascii.eqlIgnoreCase(a.name, "numthreads") and a.args.len == 3) {
|
if (std.ascii.eqlIgnoreCase(a.name, "numthreads") and a.args.len == 3) {
|
||||||
for (a.args, 0..) |arg, i| entry.num_threads[i] = @intCast(@max(1, l.s.evalInt(arg) orelse 1));
|
for (a.args, 0..) |arg, i| entry.num_threads[i] = @intCast(@max(1, l.s.evalInt(arg) orelse 1));
|
||||||
}
|
}
|
||||||
if (std.ascii.eqlIgnoreCase(a.name, "wavesize") and a.args.len >= 1 and a.args.len <= 3) {
|
|
||||||
for (a.args, 0..) |arg, i| entry.wave_size[i] = @intCast(@max(0, l.s.evalInt(arg) orelse 0));
|
|
||||||
}
|
|
||||||
if (std.ascii.eqlIgnoreCase(a.name, "maxvertexcount") and a.args.len == 1) entry.geometry.max_vertex_count = @intCast(@max(1, l.s.evalInt(a.args[0]) orelse 1));
|
if (std.ascii.eqlIgnoreCase(a.name, "maxvertexcount") and a.args.len == 1) entry.geometry.max_vertex_count = @intCast(@max(1, l.s.evalInt(a.args[0]) orelse 1));
|
||||||
if (std.ascii.eqlIgnoreCase(a.name, "instance") and a.args.len == 1) entry.geometry.instance_count = @intCast(@max(1, l.s.evalInt(a.args[0]) orelse 1));
|
if (std.ascii.eqlIgnoreCase(a.name, "instance") and a.args.len == 1) entry.geometry.instance_count = @intCast(@max(1, l.s.evalInt(a.args[0]) orelse 1));
|
||||||
if (std.ascii.eqlIgnoreCase(a.name, "RootSignature") and a.args.len == 1 and a.args[0].kind == .string_lit) entry.root_signature = try stringContents(l.arena, a.args[0].kind.string_lit);
|
if (std.ascii.eqlIgnoreCase(a.name, "RootSignature") and a.args.len == 1 and a.args[0].kind == .string_lit) entry.root_signature = try stringContents(l.arena, a.args[0].kind.string_lit);
|
||||||
|
|
@ -2595,25 +2458,14 @@ const Lowerer = struct {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
if (opts.stage == .amplification) entry.mesh.payload = l.mesh_payload;
|
if (opts.stage == .amplification) entry.mesh.payload = l.mesh_payload;
|
||||||
if (opts.stage == .node) entry.node = try l.nodeInfo(f);
|
|
||||||
const tess = opts.stage == .hull or opts.stage == .domain;
|
const tess = opts.stage == .hull or opts.stage == .domain;
|
||||||
if (tess) l.tessAttributes(f, &entry);
|
if (tess) l.tessAttributes(f, &entry);
|
||||||
// Hull shaders: where the control point inputs start.
|
// Hull shaders: where the control point inputs start.
|
||||||
var cp_first: ?u32 = null;
|
var cp_first: ?u32 = null;
|
||||||
var node_in: u32 = 0;
|
|
||||||
var node_out: u32 = 0;
|
|
||||||
for (f.decl.params, f.params, 0..) |pd, p, i| {
|
for (f.decl.params, f.params, 0..) |pd, p, i| {
|
||||||
if (l.s.types.get(p.type) == .stream) continue;
|
if (l.s.types.get(p.type) == .stream) continue;
|
||||||
n_args += 1;
|
n_args += 1;
|
||||||
const q = pd.quals;
|
const q = pd.quals;
|
||||||
if (l.s.types.get(p.type) == .node) {
|
|
||||||
const output = !l.s.types.get(p.type).node.kind.isInput();
|
|
||||||
const index = if (output) node_out else node_in;
|
|
||||||
if (output) node_out += 1 else node_in += 1;
|
|
||||||
args[i] = try l.b.add(.{ .op = .{ .node_io = .{ .output = output, .index = index } }, .ty = p.type });
|
|
||||||
locals[i] = args[i];
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (opts.stage == .mesh and (q.vertices or q.indices or q.primitives) and l.s.types.get(p.type) == .array) {
|
if (opts.stage == .mesh and (q.vertices or q.indices or q.primitives) and l.s.types.get(p.type) == .array) {
|
||||||
// Output arrays: stores through them write the outputs.
|
// Output arrays: stores through them write the outputs.
|
||||||
const arr = l.s.types.get(p.type).array;
|
const arr = l.s.types.get(p.type).array;
|
||||||
|
|
@ -2856,11 +2708,11 @@ fn packOffset(v: *const Variable) ?u32 {
|
||||||
fn imageFormatNamed(name: ?[]const u8) ?u32 {
|
fn imageFormatNamed(name: ?[]const u8) ?u32 {
|
||||||
const n = name orelse return null;
|
const n = name orelse return null;
|
||||||
const names = [_][]const u8{
|
const names = [_][]const u8{
|
||||||
"unknown", "rgba32f", "rgba16f", "r32f", "rgba8", "rgba8snorm", "rg32f", "rg16f",
|
"unknown", "rgba32f", "rgba16f", "r32f", "rgba8", "rgba8snorm", "rg32f", "rg16f",
|
||||||
"r11g11b10f", "r16f", "rgba16", "rgb10a2", "rg16", "rg8", "r16", "r8",
|
"r11g11b10f", "r16f", "rgba16", "rgb10a2", "rg16", "rg8", "r16", "r8",
|
||||||
"rgba16snorm", "rg16snorm", "rg8snorm", "r16snorm", "r8snorm", "rgba32i", "rgba16i", "rgba8i",
|
"rgba16snorm", "rg16snorm", "rg8snorm", "r16snorm", "r8snorm", "rgba32i", "rgba16i", "rgba8i",
|
||||||
"r32i", "rg32i", "rg16i", "rg8i", "r16i", "r8i", "rgba32ui", "rgba16ui",
|
"r32i", "rg32i", "rg16i", "rg8i", "r16i", "r8i", "rgba32ui", "rgba16ui",
|
||||||
"rgba8ui", "r32ui", "rgb10a2ui", "rg32ui", "rg16ui", "rg8ui", "r16ui", "r8ui",
|
"rgba8ui", "r32ui", "rgb10a2ui", "rg32ui", "rg16ui", "rg8ui", "r16ui", "r8ui",
|
||||||
"r64ui", "r64i",
|
"r64ui", "r64i",
|
||||||
};
|
};
|
||||||
for (names, 0..) |x, k| if (std.ascii.eqlIgnoreCase(x, n)) return @intCast(k);
|
for (names, 0..) |x, k| if (std.ascii.eqlIgnoreCase(x, n)) return @intCast(k);
|
||||||
|
|
@ -2896,6 +2748,7 @@ pub fn isObject(t: *TypeTable, ty: TypeId) bool {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
fn semanticOf(sems: []const ast.Semantic) ?[]const u8 {
|
fn semanticOf(sems: []const ast.Semantic) ?[]const u8 {
|
||||||
for (sems) |sem| if (sem.kind == .semantic) return sem.values[0];
|
for (sems) |sem| if (sem.kind == .semantic) return sem.values[0];
|
||||||
return null;
|
return null;
|
||||||
|
|
@ -2989,7 +2842,6 @@ fn signExtend(v: u64, bits: u8) i64 {
|
||||||
/// Whether `e` designates storage (a variable, or a part of one) rather
|
/// Whether `e` designates storage (a variable, or a part of one) rather
|
||||||
/// than a temporary such as an operator call's result.
|
/// than a temporary such as an operator call's result.
|
||||||
fn isAddressable(s: *const Sema, e: *const ast.Expr) bool {
|
fn isAddressable(s: *const Sema, e: *const ast.Expr) bool {
|
||||||
if (s.resolution(e)) |r| if (r == .node_record) return true;
|
|
||||||
return switch (e.kind) {
|
return switch (e.kind) {
|
||||||
.name, .this => true,
|
.name, .this => true,
|
||||||
.member => |m| isAddressable(s, m.base),
|
.member => |m| isAddressable(s, m.base),
|
||||||
|
|
|
||||||
|
|
@ -181,7 +181,7 @@ fn mapRefs(a: Allocator, xs: []const Ref, ctx: anytype) Allocator.Error![]const
|
||||||
/// `op` with every operand passed through `ctx.map`.
|
/// `op` with every operand passed through `ctx.map`.
|
||||||
pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
|
pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
|
||||||
return switch (op) {
|
return switch (op) {
|
||||||
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef, .node_io => op,
|
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef => op,
|
||||||
.load => |p| .{ .load = ctx.map(p) },
|
.load => |p| .{ .load = ctx.map(p) },
|
||||||
.store => |x| .{ .store = .{ .ptr = ctx.map(x.ptr), .value = ctx.map(x.value) } },
|
.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) } },
|
.access => |x| .{ .access = .{ .base = ctx.map(x.base), .indices = try mapRefs(a, x.indices, ctx) } },
|
||||||
|
|
@ -207,7 +207,7 @@ pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
|
||||||
const ops = try a.dupe(@typeInfo(@TypeOf(x.operands)).pointer.child, x.operands);
|
const ops = try a.dupe(@typeInfo(@TypeOf(x.operands)).pointer.child, x.operands);
|
||||||
for (ops) |*o| switch (o.*) {
|
for (ops) |*o| switch (o.*) {
|
||||||
.value => |*v| v.* = ctx.map(v.*),
|
.value => |*v| v.* = ctx.map(v.*),
|
||||||
.literal, .type, .string => {},
|
.literal, .type => {},
|
||||||
};
|
};
|
||||||
const n = try a.create(ir.SpirvInst);
|
const n = try a.create(ir.SpirvInst);
|
||||||
n.* = x.*;
|
n.* = x.*;
|
||||||
|
|
@ -227,7 +227,7 @@ pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
|
||||||
/// allocating.
|
/// allocating.
|
||||||
pub fn eachOperand(op: Op, ctx: anytype) void {
|
pub fn eachOperand(op: Op, ctx: anytype) void {
|
||||||
switch (op) {
|
switch (op) {
|
||||||
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef, .node_io => {},
|
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef => {},
|
||||||
.load => |p| ctx.use(p),
|
.load => |p| ctx.use(p),
|
||||||
.store => |x| {
|
.store => |x| {
|
||||||
ctx.use(x.ptr);
|
ctx.use(x.ptr);
|
||||||
|
|
@ -278,7 +278,7 @@ pub fn eachOperand(op: Op, ctx: anytype) void {
|
||||||
.heap_resource => |h| ctx.use(h.index),
|
.heap_resource => |h| ctx.use(h.index),
|
||||||
.spirv_inst => |x| for (x.operands) |o| switch (o) {
|
.spirv_inst => |x| for (x.operands) |o| switch (o) {
|
||||||
.value => |v| ctx.use(v),
|
.value => |v| ctx.use(v),
|
||||||
.literal, .type, .string => {},
|
.literal, .type => {},
|
||||||
},
|
},
|
||||||
.patch_output => |x| ctx.use(x.value),
|
.patch_output => |x| ctx.use(x.value),
|
||||||
.phi => |ps| for (ps) |pp| ctx.use(pp.value),
|
.phi => |ps| for (ps) |pp| ctx.use(pp.value),
|
||||||
|
|
|
||||||
|
|
@ -189,8 +189,6 @@ const Pass = struct {
|
||||||
if (info.done) return;
|
if (info.done) return;
|
||||||
info.done = true;
|
info.done = true;
|
||||||
const f = p.m.functions.items[fi];
|
const f = p.m.functions.items[fi];
|
||||||
// (Inlined everywhere: not emitted.)
|
|
||||||
if (f.dead) return;
|
|
||||||
// Callees first: their returns may be resources.
|
// Callees first: their returns may be resources.
|
||||||
for (f.insts.items) |inst| if (inst.op == .call) try p.function(inst.op.call.func);
|
for (f.insts.items) |inst| if (inst.op == .call) try p.function(inst.op.call.func);
|
||||||
|
|
||||||
|
|
@ -211,10 +209,7 @@ const Pass = struct {
|
||||||
const n_old = f.insts.items.len;
|
const n_old = f.insts.items.len;
|
||||||
const ret_holds = holdsResources(p.t, f.ret) or isOpaque(p.t, f.ret);
|
const ret_holds = holdsResources(p.t, f.ret) or isOpaque(p.t, f.ret);
|
||||||
|
|
||||||
// Definitions before uses: inlining leaves a call's continuation
|
for (f.blocks.items, 0..) |*blk, bi| {
|
||||||
// ahead of the callee's blocks.
|
|
||||||
for (try reversePostorder(p.a, f)) |bi| {
|
|
||||||
const blk = &f.blocks.items[bi];
|
|
||||||
var out: std.ArrayList(Ref) = .empty;
|
var out: std.ArrayList(Ref) = .empty;
|
||||||
for (blk.insts.items) |r| {
|
for (blk.insts.items) |r| {
|
||||||
const old = f.insts.items[r.index()];
|
const old = f.insts.items[r.index()];
|
||||||
|
|
@ -426,6 +421,7 @@ const Pass = struct {
|
||||||
.@"switch" => |sw| blk.term = .{ .@"switch" = .{ .value = mp.map(sw.value), .default = sw.default, .cases = sw.cases } },
|
.@"switch" => |sw| blk.term = .{ .@"switch" = .{ .value = mp.map(sw.value), .default = sw.default, .cases = sw.cases } },
|
||||||
else => {},
|
else => {},
|
||||||
}
|
}
|
||||||
|
_ = bi;
|
||||||
}
|
}
|
||||||
_ = n_old;
|
_ = n_old;
|
||||||
// What each out / inout resource holds when the function returns:
|
// What each out / inout resource holds when the function returns:
|
||||||
|
|
@ -484,42 +480,6 @@ const Pass = struct {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/// `f`'s blocks in reverse postorder from the entry (each block after its
|
|
||||||
/// dominators), then any unreachable ones in list order.
|
|
||||||
fn reversePostorder(a: Allocator, f: *const ir.Function) Allocator.Error![]const u32 {
|
|
||||||
const n = f.blocks.items.len;
|
|
||||||
const seen = try a.alloc(bool, n);
|
|
||||||
@memset(seen, false);
|
|
||||||
var post: std.ArrayList(u32) = try .initCapacity(a, n);
|
|
||||||
// (block, whether its successors were pushed)
|
|
||||||
var stack: std.ArrayList(struct { b: u32, expanded: bool }) = .empty;
|
|
||||||
if (n > 0) try stack.append(a, .{ .b = 0, .expanded = false });
|
|
||||||
while (stack.pop()) |it| {
|
|
||||||
if (it.expanded) {
|
|
||||||
post.appendAssumeCapacity(it.b);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (seen[it.b]) continue;
|
|
||||||
seen[it.b] = true;
|
|
||||||
try stack.append(a, .{ .b = it.b, .expanded = true });
|
|
||||||
const succs: []const ir.BlockId = switch (f.blocks.items[it.b].term) {
|
|
||||||
.br => |t| &.{t},
|
|
||||||
.cond_br => |c| &.{ c.@"else", c.then },
|
|
||||||
.@"switch" => |sw| blk: {
|
|
||||||
const out = try a.alloc(ir.BlockId, sw.cases.len + 1);
|
|
||||||
for (sw.cases, 0..) |c, i| out[sw.cases.len - 1 - i] = c.block;
|
|
||||||
out[sw.cases.len] = sw.default;
|
|
||||||
break :blk out;
|
|
||||||
},
|
|
||||||
else => &.{},
|
|
||||||
};
|
|
||||||
for (succs) |sb| if (sb != .none and !seen[sb.index()]) try stack.append(a, .{ .b = @intCast(sb.index()), .expanded = false });
|
|
||||||
}
|
|
||||||
std.mem.reverse(u32, post.items);
|
|
||||||
for (0..n) |bi| if (!seen[bi]) post.appendAssumeCapacity(@intCast(bi));
|
|
||||||
return post.items;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Splits every function's resource-holding aggregates (SPIR-V only).
|
/// Splits every function's resource-holding aggregates (SPIR-V only).
|
||||||
pub fn run(a: Allocator, m: *ir.Module, diags: *diag.Diagnostics) Error!void {
|
pub fn run(a: Allocator, m: *ir.Module, diags: *diag.Diagnostics) Error!void {
|
||||||
var any = false;
|
var any = false;
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
//! zdxc: an HLSL 2018 / 2021 compiler targeting DXIL and SPIR-V.
|
//! zdxc: an HLSL 2021 compiler targeting DXIL and SPIR-V.
|
||||||
|
|
||||||
pub const diag = @import("diag.zig");
|
pub const diag = @import("diag.zig");
|
||||||
pub const options = @import("options.zig");
|
pub const options = @import("options.zig");
|
||||||
|
|
|
||||||
|
|
@ -197,16 +197,6 @@ const Bindings = struct {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Bind `name` to `v` unless it is bound to a smaller value.
|
|
||||||
fn lower(b: *Bindings, name: []const u8, v: u16) void {
|
|
||||||
if (std.fmt.parseInt(u16, name, 10)) |_| return else |_| {}
|
|
||||||
for (b.names[0..b.n], b.values[0..b.n]) |k, *old| if (std.mem.eql(u8, k, name)) {
|
|
||||||
old.* = @min(old.*, v);
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
_ = b.bind(name, v);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Bind or check; false on conflict.
|
/// Bind or check; false on conflict.
|
||||||
fn bind(b: *Bindings, name: []const u8, v: u16) bool {
|
fn bind(b: *Bindings, name: []const u8, v: u16) bool {
|
||||||
if (b.get(name)) |old| return old == v;
|
if (b.get(name)) |old| return old == v;
|
||||||
|
|
@ -231,7 +221,6 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
|
||||||
.resource => |r| r.elem,
|
.resource => |r| r.elem,
|
||||||
.stream => |s| s.elem,
|
.stream => |s| s.elem,
|
||||||
.patch => |p| p.elem,
|
.patch => |p| p.elem,
|
||||||
.node => |x| x.elem,
|
|
||||||
else => TypeTable.error_type,
|
else => TypeTable.error_type,
|
||||||
} else TypeTable.error_type;
|
} else TypeTable.error_type;
|
||||||
|
|
||||||
|
|
@ -264,66 +253,12 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
|
||||||
}
|
}
|
||||||
|
|
||||||
var bindings: Bindings = .{};
|
var bindings: Bindings = .{};
|
||||||
// A vector size (`c` of `numeric<c>`) shared by several arguments takes
|
|
||||||
// the widest of them, scalars splatting to it, as in dxc: `dot(1, v)`
|
|
||||||
// is a dot product of v's size, not v truncated to a scalar.
|
|
||||||
{
|
|
||||||
var syms: [8][]const u8 = undefined;
|
|
||||||
var widest: [8]u16 = undefined;
|
|
||||||
var ok: [8]bool = undefined;
|
|
||||||
var ns: usize = 0;
|
|
||||||
for (args[0..it.params.len], 1..) |a, i| {
|
|
||||||
const ls = if (specs[i].dims.len > 0) specs[i] else specs[layout_group[i]];
|
|
||||||
if (ls.any_layout or ls.dims.len != 1) continue;
|
|
||||||
const sym = ls.dims[0];
|
|
||||||
if (std.fmt.parseInt(u16, sym, 10)) |_| continue else |_| {}
|
|
||||||
const sh = t.shape(a.ty) orelse continue;
|
|
||||||
const len: u16 = switch (sh.kind) {
|
|
||||||
.scalar => 1,
|
|
||||||
.vector => sh.cols,
|
|
||||||
else => continue,
|
|
||||||
};
|
|
||||||
const k = for (syms[0..ns], 0..) |s, j| {
|
|
||||||
if (std.mem.eql(u8, s, sym)) break j;
|
|
||||||
} else blk: {
|
|
||||||
if (ns == syms.len) break :blk null;
|
|
||||||
syms[ns] = sym;
|
|
||||||
widest[ns] = len;
|
|
||||||
ok[ns] = true;
|
|
||||||
ns += 1;
|
|
||||||
break :blk ns - 1;
|
|
||||||
} orelse continue;
|
|
||||||
// (Vectors of two different sizes: left to the usual binding,
|
|
||||||
// which converts to the first.)
|
|
||||||
if (len != 1 and widest[k] != 1 and len != widest[k]) ok[k] = false;
|
|
||||||
widest[k] = @max(widest[k], len);
|
|
||||||
}
|
|
||||||
for (syms[0..ns], widest[0..ns], ok[0..ns]) |s, w, good| if (good and w > 1) {
|
|
||||||
_ = bindings.bind(s, w);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
for (args[0..it.params.len], 1..) |a, i| {
|
for (args[0..it.params.len], 1..) |a, i| {
|
||||||
// (Also arguments whose layout links to a `<>` one.)
|
// (Also arguments whose layout links to a `<>` one.)
|
||||||
if (!specs[i].any_layout and !specs[layout_group[i]].any_layout) continue;
|
if (!specs[i].any_layout and !specs[layout_group[i]].any_layout) continue;
|
||||||
const sh = t.shape(a.ty) orelse 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;
|
if (bindings.any_shape == null or sh.count() > bindings.any_shape.?.count()) bindings.any_shape = sh;
|
||||||
}
|
}
|
||||||
// A dimension shared by several arguments (`dot(numeric<c>,
|
|
||||||
// numeric<c>)`, mul's `numeric<r, c>` and `numeric<c>`) is the
|
|
||||||
// smallest one: dxc truncates the larger arguments (with a warning).
|
|
||||||
// Scalars splat and do not bind it.
|
|
||||||
for (args[0..it.params.len], 1..) |a, i| {
|
|
||||||
const ls = if (specs[i].dims.len > 0) specs[i] else specs[layout_group[i]];
|
|
||||||
const sh = t.shape(a.ty) orelse continue;
|
|
||||||
switch (ls.dims.len) {
|
|
||||||
1 => if (sh.kind == .vector) bindings.lower(ls.dims[0], sh.cols),
|
|
||||||
2 => if (sh.kind == .matrix) {
|
|
||||||
bindings.lower(ls.dims[0], sh.rows);
|
|
||||||
bindings.lower(ls.dims[1], sh.cols);
|
|
||||||
},
|
|
||||||
else => {},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var sum: u32 = 0;
|
var sum: u32 = 0;
|
||||||
var worst: u32 = 0;
|
var worst: u32 = 0;
|
||||||
const out_params = try sema.arena.alloc(bool, args.len);
|
const out_params = try sema.arena.alloc(bool, args.len);
|
||||||
|
|
@ -386,12 +321,6 @@ fn paramType(
|
||||||
|
|
||||||
// Non-numeric classes.
|
// Non-numeric classes.
|
||||||
const base = if (cs.special == .none) cs.base else s.base;
|
const base = if (cs.special == .none) cs.base else s.base;
|
||||||
// NodeOutput's Get{Thread,Group}NodeOutputRecords: records of the
|
|
||||||
// output's record type.
|
|
||||||
if (i == 0 and obj_elem != TypeTable.error_type) {
|
|
||||||
const records: ?types.NodeKind = if (std.mem.eql(u8, base, "ThreadNodeOutputRecords")) .thread_output_records else if (std.mem.eql(u8, base, "GroupNodeOutputRecords")) .group_output_records else null;
|
|
||||||
if (records) |k| return try t.intern(.{ .node = .{ .kind = k, .elem = obj_elem } });
|
|
||||||
}
|
|
||||||
if (!std.mem.eql(u8, base, "void") and !isNumericClass(base)) {
|
if (!std.mem.eql(u8, base, "void") and !isNumericClass(base)) {
|
||||||
// Objects (samplers are checked) and classes zdxc does not model
|
// Objects (samplers are checked) and classes zdxc does not model
|
||||||
// (HitObject, node records, LinAlg...): unconstrained.
|
// (HitObject, node records, LinAlg...): unconstrained.
|
||||||
|
|
|
||||||
|
|
@ -89,9 +89,6 @@ pub const Resolution = union(enum) {
|
||||||
/// A bitfield member (`this_bitfield`: named without `this.`).
|
/// A bitfield member (`this_bitfield`: named without `this.`).
|
||||||
bitfield: types.Bitfield,
|
bitfield: types.Bitfield,
|
||||||
this_bitfield: types.Bitfield,
|
this_bitfield: types.Bitfield,
|
||||||
/// A node object's record: `Get()`, `Get(i)` or `[i]` (lowered as an
|
|
||||||
/// element of the object).
|
|
||||||
node_record,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const Param = struct {
|
pub const Param = struct {
|
||||||
|
|
@ -99,10 +96,6 @@ pub const Param = struct {
|
||||||
type: TypeId,
|
type: TypeId,
|
||||||
dir: enum { in, out, inout },
|
dir: enum { in, out, inout },
|
||||||
has_default: bool,
|
has_default: bool,
|
||||||
/// A template instance's default argument that does not convert to
|
|
||||||
/// the parameter's type: an error only where a call uses it (C++
|
|
||||||
/// instantiates default arguments on use).
|
|
||||||
bad_default: bool = false,
|
|
||||||
/// `groupshared` parameter (SM 6.8 groupshared arguments).
|
/// `groupshared` parameter (SM 6.8 groupshared arguments).
|
||||||
groupshared: bool = false,
|
groupshared: bool = false,
|
||||||
};
|
};
|
||||||
|
|
@ -1359,18 +1352,6 @@ pub const Sema = struct {
|
||||||
// Any other builtin object (RayQuery, node records, vk:: types...).
|
// Any other builtin object (RayQuery, node records, vk:: types...).
|
||||||
// vk::ext_result_id<T>: a T (an inline instruction's result).
|
// vk::ext_result_id<T>: a T (an inline instruction's result).
|
||||||
if (eql(n, "ext_result_id") and args.len == 1) return try s.typeArg(args[0]) orelse TypeTable.error_type;
|
if (eql(n, "ext_result_id") and args.len == 1) return try s.typeArg(args[0]) orelse TypeTable.error_type;
|
||||||
// Work graph node objects: their record type.
|
|
||||||
if (types.NodeKind.named(n)) |kind| {
|
|
||||||
var elem: TypeId = TypeTable.void_type;
|
|
||||||
if (kind.templated()) {
|
|
||||||
if (args.len == 0) {
|
|
||||||
s.err(t.loc, "'{s}' requires a record type template argument", .{n});
|
|
||||||
return TypeTable.error_type;
|
|
||||||
}
|
|
||||||
elem = try s.typeArg(args[0]) orelse return TypeTable.error_type;
|
|
||||||
}
|
|
||||||
return s.types.intern(.{ .node = .{ .kind = kind, .elem = elem } });
|
|
||||||
}
|
|
||||||
if (isOtherBuiltinObject(n)) {
|
if (isOtherBuiltinObject(n)) {
|
||||||
var elem: TypeId = TypeTable.void_type;
|
var elem: TypeId = TypeTable.void_type;
|
||||||
if (eql(n, "RayQuery")) {
|
if (eql(n, "RayQuery")) {
|
||||||
|
|
@ -1567,15 +1548,6 @@ pub const Sema = struct {
|
||||||
// ------------------------------------------------------------------
|
// ------------------------------------------------------------------
|
||||||
// Constant evaluation (array sizes, case labels, template arguments)
|
// Constant evaluation (array sizes, case labels, template arguments)
|
||||||
|
|
||||||
/// Whether struct `info` was declared with attribute `name` (any case).
|
|
||||||
pub fn structHasAttr(s: *const Sema, info: *const types.StructInfo, name: []const u8) bool {
|
|
||||||
_ = s;
|
|
||||||
const ss: *const StructSema = @ptrCast(@alignCast(info.sema orelse return false));
|
|
||||||
if (ss.decl.kind != .@"struct") return false;
|
|
||||||
for (ss.decl.kind.@"struct".attrs) |a| if (std.ascii.eqlIgnoreCase(a.name, name)) return true;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn evalInt(s: *Sema, e: *const ast.Expr) ?i64 {
|
pub fn evalInt(s: *Sema, e: *const ast.Expr) ?i64 {
|
||||||
return switch (s.evalConst(e) orelse return null) {
|
return switch (s.evalConst(e) orelse return null) {
|
||||||
.int => |v| v,
|
.int => |v| v,
|
||||||
|
|
@ -2194,13 +2166,6 @@ pub const Sema = struct {
|
||||||
if (last_shader) |kept| {
|
if (last_shader) |kept| {
|
||||||
if (!eql(kept, stage)) s.err(a.loc, "shader attribute type '{s}' conflicts with shader attribute type '{s}'", .{ stage, kept });
|
if (!eql(kept, stage)) s.err(a.loc, "shader attribute type '{s}' conflicts with shader attribute type '{s}'", .{ stage, kept });
|
||||||
} else last_shader = stage;
|
} else last_shader = stage;
|
||||||
} else if (std.ascii.eqlIgnoreCase(a.name, "nodelaunch") and a.args.len == 1 and a.args[0].kind == .string_lit) {
|
|
||||||
// (Exactly these: dxc compares case-sensitively.)
|
|
||||||
const lit = a.args[0].kind.string_lit;
|
|
||||||
const v = if (lit.len >= 2) lit[1 .. lit.len - 1] else lit;
|
|
||||||
if (!eql(v, "broadcasting") and !eql(v, "coalescing") and !eql(v, "thread")) {
|
|
||||||
s.err(a.args[0].loc, "attribute 'NodeLaunch' must have one of these values: broadcasting,coalescing,thread", .{});
|
|
||||||
}
|
|
||||||
} else if (std.ascii.eqlIgnoreCase(a.name, "wavesize")) {
|
} else if (std.ascii.eqlIgnoreCase(a.name, "wavesize")) {
|
||||||
if (last_wavesize) |kept| {
|
if (last_wavesize) |kept| {
|
||||||
var same = kept.args.len == a.args.len;
|
var same = kept.args.len == a.args.len;
|
||||||
|
|
@ -2525,16 +2490,7 @@ pub const Sema = struct {
|
||||||
.has_default = p.init != null,
|
.has_default = p.init != null,
|
||||||
.groupshared = p.quals.groupshared,
|
.groupshared = p.quals.groupshared,
|
||||||
};
|
};
|
||||||
if (p.init) |init_e| {
|
if (p.init) |init_e| _ = try s.checkInitializer(pt, init_e);
|
||||||
if (s.instance_depth > 0) {
|
|
||||||
const m = s.diags.mark();
|
|
||||||
_ = try s.checkInitializer(pt, init_e);
|
|
||||||
if (s.diags.error_count != m.errors) {
|
|
||||||
s.diags.rollback(m);
|
|
||||||
out.bad_default = true;
|
|
||||||
}
|
|
||||||
} else _ = try s.checkInitializer(pt, init_e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
const func = try s.arena.create(Function);
|
const func = try s.arena.create(Function);
|
||||||
func.* = .{ .name = name, .decl = f, .loc = d.loc, .ret = ret, .params = params, .defined = f.body != null, .owner = owner };
|
func.* = .{ .name = name, .decl = f, .loc = d.loc, .ret = ret, .params = params, .defined = f.body != null, .owner = owner };
|
||||||
|
|
@ -3598,17 +3554,6 @@ pub const Sema = struct {
|
||||||
return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } };
|
return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } };
|
||||||
},
|
},
|
||||||
.stream, .patch => return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } },
|
.stream, .patch => return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } },
|
||||||
.node => |x| {
|
|
||||||
// Get: the record (records objects); the rest from the
|
|
||||||
// intrinsics table.
|
|
||||||
const known = (eql(name, "Get") and x.kind.hasRecords()) or
|
|
||||||
if (methodNamespace(s.types.get(b.ty))) |ns| s.intrinsic_db.hasMethod(ns, name) else false;
|
|
||||||
if (!known) {
|
|
||||||
s.err(name_loc, "no member named '{s}' in '{s}'", .{ name, s.typeName(b.ty) });
|
|
||||||
return err_typed;
|
|
||||||
}
|
|
||||||
return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } };
|
|
||||||
},
|
|
||||||
else => {
|
else => {
|
||||||
s.err(name_loc, "member reference base type '{s}' is not a structure", .{s.typeName(b.ty)});
|
s.err(name_loc, "member reference base type '{s}' is not a structure", .{s.typeName(b.ty)});
|
||||||
return err_typed;
|
return err_typed;
|
||||||
|
|
@ -3652,16 +3597,6 @@ pub const Sema = struct {
|
||||||
};
|
};
|
||||||
return .{ .ty = try s.types.vector(m.elem, m.cols), .lvalue = b.lvalue, .read_only = b.read_only };
|
return .{ .ty = try s.types.vector(m.elem, m.cols), .lvalue = b.lvalue, .read_only = b.read_only };
|
||||||
},
|
},
|
||||||
.node => |x| {
|
|
||||||
// Records of a records array; an output of an outputs array.
|
|
||||||
if (x.kind.isArray()) {
|
|
||||||
s.record(e, .node_record);
|
|
||||||
return .{ .ty = x.elem, .lvalue = true, .read_only = !x.kind.writable() };
|
|
||||||
}
|
|
||||||
if (x.kind.outputElement()) |k| return rvalue(try s.types.intern(.{ .node = .{ .kind = k, .elem = x.elem } }));
|
|
||||||
s.err(e.loc, "type '{s}' does not provide a subscript operator", .{s.typeName(b.ty)});
|
|
||||||
return err_typed;
|
|
||||||
},
|
|
||||||
.resource => |r| {
|
.resource => |r| {
|
||||||
if (r.kind.indexDims() == 0 or r.elem == TypeTable.void_type) {
|
if (r.kind.indexDims() == 0 or r.elem == TypeTable.void_type) {
|
||||||
if (r.kind == .other) return err_typed;
|
if (r.kind == .other) return err_typed;
|
||||||
|
|
@ -3789,25 +3724,6 @@ pub const Sema = struct {
|
||||||
if (sym != .functions) return err_typed;
|
if (sym != .functions) return err_typed;
|
||||||
return rvalue(s.resolveUserCall(e, sym.functions, arg_types, callee));
|
return rvalue(s.resolveUserCall(e, sym.functions, arg_types, callee));
|
||||||
},
|
},
|
||||||
.node => |x| if (eql(m.name, "Get")) {
|
|
||||||
// The record (`Get(i)`: of several).
|
|
||||||
const most: usize = if (x.kind.isArray()) 1 else 0;
|
|
||||||
if (arg_types.len > most) {
|
|
||||||
s.err(e.loc, "too many arguments to function call, expected at most {d}, have {d}", .{ most, arg_types.len });
|
|
||||||
return err_typed;
|
|
||||||
}
|
|
||||||
if (arg_types.len == 1 and s.conversionCost(arg_types[0].ty, try s.types.scalar(.uint)) == null) {
|
|
||||||
s.err(e.loc, "no matching member function for call to 'Get'", .{});
|
|
||||||
return err_typed;
|
|
||||||
}
|
|
||||||
s.record(e, .node_record);
|
|
||||||
return .{ .ty = x.elem, .lvalue = true, .read_only = !x.kind.writable() };
|
|
||||||
} else {
|
|
||||||
const ns = methodNamespace(s.types.get(m.object)) orelse return err_typed;
|
|
||||||
const r = try s.intrinsic_db.resolve(s, e.loc, ns, m.name, m.object, arg_types, null);
|
|
||||||
if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params, .object = m.object } });
|
|
||||||
return rvalue(r.ret);
|
|
||||||
},
|
|
||||||
else => {
|
else => {
|
||||||
var explicit: ?TypeId = null;
|
var explicit: ?TypeId = null;
|
||||||
if (template_args.len > 0) explicit = try s.typeArg(template_args[0]);
|
if (template_args.len > 0) explicit = try s.typeArg(template_args[0]);
|
||||||
|
|
@ -3856,17 +3772,7 @@ pub const Sema = struct {
|
||||||
var explicit: ?TypeId = null;
|
var explicit: ?TypeId = null;
|
||||||
if (template_args.len > 0) explicit = try s.typeArg(template_args[0]);
|
if (template_args.len > 0) explicit = try s.typeArg(template_args[0]);
|
||||||
const r = try s.intrinsic_db.resolve(s, e.loc, if (s.opts.spirv and isVkQualified(callee)) "VkIntrinsics" else "Intrinsics", name, null, arg_types, explicit);
|
const r = try s.intrinsic_db.resolve(s, e.loc, if (s.opts.spirv and isVkQualified(callee)) "VkIntrinsics" else "Intrinsics", name, null, arg_types, explicit);
|
||||||
if (r.ok) {
|
if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } });
|
||||||
s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } });
|
|
||||||
// `dot(float4, float3)`: the longer argument is truncated.
|
|
||||||
for (arg_types, r.params[0..@min(arg_types.len, r.params.len)], 0..) |a, pt, i| {
|
|
||||||
const as = s.types.shape(a.ty) orelse continue;
|
|
||||||
const ps = s.types.shape(pt) orelse continue;
|
|
||||||
if (as.kind == .scalar or ps.kind == .scalar or (ps.rows >= as.rows and ps.cols >= as.cols)) continue;
|
|
||||||
const loc = if (e.kind == .call and i < e.kind.call.args.len) startLoc(e.kind.call.args[i]) else a.loc;
|
|
||||||
s.warn(loc, "conversion", "implicit truncation of vector type", .{});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return rvalue(r.ret);
|
return rvalue(r.ret);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -3920,10 +3826,6 @@ pub const Sema = struct {
|
||||||
s.err(a.loc, "cannot bind non-lvalue argument to {s} parameter", .{if (f.params[i].dir == .out) "out" else "inout"});
|
s.err(a.loc, "cannot bind non-lvalue argument to {s} parameter", .{if (f.params[i].dir == .out) "out" else "inout"});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (f.params[@min(args.len, f.params.len)..]) |p| if (p.bad_default) {
|
|
||||||
s.err(callee.loc, "cannot initialize a parameter of type '{s}' with its default argument", .{s.typeName(p.type)});
|
|
||||||
return TypeTable.error_type;
|
|
||||||
};
|
|
||||||
if (s.current_fn) |caller| caller.callees.append(s.arena, f) catch {};
|
if (s.current_fn) |caller| caller.callees.append(s.arena, f) catch {};
|
||||||
s.record(e, .{ .function = f });
|
s.record(e, .{ .function = f });
|
||||||
s.ensureBody(f) catch {};
|
s.ensureBody(f) catch {};
|
||||||
|
|
@ -4165,9 +4067,6 @@ pub fn parseIntLiteral(text: []const u8) ?i64 {
|
||||||
if (digits.len > 2 and digits[0] == '0' and (digits[1] == 'x' or digits[1] == 'X')) {
|
if (digits.len > 2 and digits[0] == '0' and (digits[1] == 'x' or digits[1] == 'X')) {
|
||||||
base = 16;
|
base = 16;
|
||||||
body = digits[2..];
|
body = digits[2..];
|
||||||
} else if (isBinaryLiteral(digits)) {
|
|
||||||
base = 2;
|
|
||||||
body = digits[2..];
|
|
||||||
} else if (digits.len > 1 and digits[0] == '0') {
|
} else if (digits.len > 1 and digits[0] == '0') {
|
||||||
base = 8;
|
base = 8;
|
||||||
body = digits[1..];
|
body = digits[1..];
|
||||||
|
|
@ -4187,11 +4086,6 @@ pub fn parseFloatLiteral(text: []const u8) ?f64 {
|
||||||
/// dxc's `.#INF`): where the suffix starts and whether it is floating.
|
/// dxc's `.#INF`): where the suffix starts and whether it is floating.
|
||||||
fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = false } {
|
fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = false } {
|
||||||
var i: usize = 0;
|
var i: usize = 0;
|
||||||
if (isBinaryLiteral(text)) {
|
|
||||||
i = 2;
|
|
||||||
while (i < text.len and (text[i] == '0' or text[i] == '1')) i += 1;
|
|
||||||
return .{ .end = i, .float = false };
|
|
||||||
}
|
|
||||||
const hex = text.len > 1 and text[0] == '0' and (text[1] == 'x' or text[1] == 'X');
|
const hex = text.len > 1 and text[0] == '0' and (text[1] == 'x' or text[1] == 'X');
|
||||||
if (hex) i = 2;
|
if (hex) i = 2;
|
||||||
const isDigit = struct {
|
const isDigit = struct {
|
||||||
|
|
@ -4220,24 +4114,6 @@ fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = f
|
||||||
return .{ .end = i, .float = float };
|
return .{ .end = i, .float = float };
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `0b101`: a binary integer literal (clang accepts them in HLSL).
|
|
||||||
/// Where an expression's text starts (clang's getBeginLoc): `i` in `i.T`.
|
|
||||||
fn startLoc(e: *const ast.Expr) Loc {
|
|
||||||
return switch (e.kind) {
|
|
||||||
.member => |m| startLoc(m.base),
|
|
||||||
.index => |x| startLoc(x.base),
|
|
||||||
.binary => |b| startLoc(b.lhs),
|
|
||||||
.assign => |b| startLoc(b.lhs),
|
|
||||||
.conditional => |c| startLoc(c.cond),
|
|
||||||
.call => |c| startLoc(c.callee),
|
|
||||||
else => e.loc,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
fn isBinaryLiteral(text: []const u8) bool {
|
|
||||||
return text.len > 2 and text[0] == '0' and (text[1] == 'b' or text[1] == 'B') and (text[2] == '0' or text[2] == '1');
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `f16` / `f32` / `f64` (any case) at the end of a float literal.
|
/// `f16` / `f32` / `f64` (any case) at the end of a float literal.
|
||||||
fn fixedFloatSuffix(text: []const u8) ?[]const u8 {
|
fn fixedFloatSuffix(text: []const u8) ?[]const u8 {
|
||||||
if (text.len < 4) return null;
|
if (text.len < 4) return null;
|
||||||
|
|
@ -4452,15 +4328,6 @@ fn methodNamespace(t: types.Type) ?[]const u8 {
|
||||||
.constant_buffer, .texture_buffer, .raytracing_acceleration_structure => null,
|
.constant_buffer, .texture_buffer, .raytracing_acceleration_structure => null,
|
||||||
.other => if (std.mem.eql(u8, r.name, "RayQuery")) "RayQueryMethods" else if (std.mem.eql(u8, r.name, "SubpassInput")) "VkSubpassInputMethods" else if (std.mem.eql(u8, r.name, "SubpassInputMS")) "VkSubpassInputMSMethods" else null,
|
.other => if (std.mem.eql(u8, r.name, "RayQuery")) "RayQueryMethods" else if (std.mem.eql(u8, r.name, "SubpassInput")) "VkSubpassInputMethods" else if (std.mem.eql(u8, r.name, "SubpassInputMS")) "VkSubpassInputMSMethods" else null,
|
||||||
},
|
},
|
||||||
.node => |x| switch (x.kind) {
|
|
||||||
.empty_input => "EmptyNodeInputMethods",
|
|
||||||
.rw_dispatch_input => "RWDispatchNodeInputRecordMethods",
|
|
||||||
.group_input, .rw_group_input => "GroupNodeInputRecordsMethods",
|
|
||||||
.output => "NodeOutputMethods",
|
|
||||||
.empty_output => "EmptyNodeOutputMethods",
|
|
||||||
.thread_output_records, .group_output_records => "GroupOrThreadNodeOutputRecordsMethods",
|
|
||||||
else => null,
|
|
||||||
},
|
|
||||||
else => null,
|
else => null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -527,110 +527,6 @@ pub const Type = union(enum) {
|
||||||
/// `__builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(c, m, n, use,
|
/// `__builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(c, m, n, use,
|
||||||
/// scope)]]` (SM 6.10): an opaque matrix handle.
|
/// scope)]]` (SM 6.10): an opaque matrix handle.
|
||||||
linalg: LinAlgMatrix,
|
linalg: LinAlgMatrix,
|
||||||
/// A work graph node input, output or output record object
|
|
||||||
/// (`DispatchNodeInputRecord<T>`, `NodeOutput<T>`, ...): `elem` is the
|
|
||||||
/// record type (void for the empty ones).
|
|
||||||
node: struct { kind: NodeKind, elem: TypeId },
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Work graph node object types, as DXC's NodeIOKind.
|
|
||||||
pub const NodeKind = enum {
|
|
||||||
dispatch_input,
|
|
||||||
rw_dispatch_input,
|
|
||||||
group_input,
|
|
||||||
rw_group_input,
|
|
||||||
thread_input,
|
|
||||||
rw_thread_input,
|
|
||||||
empty_input,
|
|
||||||
output,
|
|
||||||
output_array,
|
|
||||||
empty_output,
|
|
||||||
empty_output_array,
|
|
||||||
thread_output_records,
|
|
||||||
group_output_records,
|
|
||||||
|
|
||||||
pub const names = [_]struct { []const u8, NodeKind }{
|
|
||||||
.{ "DispatchNodeInputRecord", .dispatch_input }, .{ "RWDispatchNodeInputRecord", .rw_dispatch_input },
|
|
||||||
.{ "GroupNodeInputRecords", .group_input }, .{ "RWGroupNodeInputRecords", .rw_group_input },
|
|
||||||
.{ "ThreadNodeInputRecord", .thread_input }, .{ "RWThreadNodeInputRecord", .rw_thread_input },
|
|
||||||
.{ "EmptyNodeInput", .empty_input }, .{ "NodeOutput", .output },
|
|
||||||
.{ "NodeOutputArray", .output_array }, .{ "EmptyNodeOutput", .empty_output },
|
|
||||||
.{ "EmptyNodeOutputArray", .empty_output_array }, .{ "ThreadNodeOutputRecords", .thread_output_records },
|
|
||||||
.{ "GroupNodeOutputRecords", .group_output_records },
|
|
||||||
};
|
|
||||||
|
|
||||||
pub fn named(n: []const u8) ?NodeKind {
|
|
||||||
for (names) |e| if (std.mem.eql(u8, e[0], n)) return e[1];
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn name(k: NodeKind) []const u8 {
|
|
||||||
for (names) |e| if (e[1] == k) return e[0];
|
|
||||||
unreachable;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// NodeIOFlags: input 0x1, output 0x2, read-write 0x4, empty 0x8,
|
|
||||||
/// array 0x10; record granularity thread 0x20, group 0x40, dispatch
|
|
||||||
/// 0x60.
|
|
||||||
pub fn ioFlags(k: NodeKind) u32 {
|
|
||||||
return switch (k) {
|
|
||||||
.dispatch_input => 0x61,
|
|
||||||
.rw_dispatch_input => 0x65,
|
|
||||||
.group_input => 0x41,
|
|
||||||
.rw_group_input => 0x45,
|
|
||||||
.thread_input => 0x21,
|
|
||||||
.rw_thread_input => 0x25,
|
|
||||||
.empty_input => 0x9,
|
|
||||||
.output => 0x6,
|
|
||||||
.output_array => 0x16,
|
|
||||||
.empty_output => 0xA,
|
|
||||||
.empty_output_array => 0x1A,
|
|
||||||
.thread_output_records => 0x26,
|
|
||||||
.group_output_records => 0x46,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn isInput(k: NodeKind) bool {
|
|
||||||
return k.ioFlags() & 1 != 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Objects holding records (Get and, for the group ones, indexing).
|
|
||||||
pub fn hasRecords(k: NodeKind) bool {
|
|
||||||
return switch (k) {
|
|
||||||
.dispatch_input, .rw_dispatch_input, .group_input, .rw_group_input, .thread_input, .rw_thread_input, .thread_output_records, .group_output_records => true,
|
|
||||||
else => false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Several records: `Get(i)` and `[i]` (dxc's IsArray).
|
|
||||||
pub fn isArray(k: NodeKind) bool {
|
|
||||||
return switch (k) {
|
|
||||||
.group_input, .rw_group_input, .thread_output_records, .group_output_records => true,
|
|
||||||
else => false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An array of outputs: `[i]` is one.
|
|
||||||
pub fn outputElement(k: NodeKind) ?NodeKind {
|
|
||||||
return switch (k) {
|
|
||||||
.output_array => .output,
|
|
||||||
.empty_output_array => .empty_output,
|
|
||||||
else => null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Records that may be written.
|
|
||||||
pub fn writable(k: NodeKind) bool {
|
|
||||||
return k.ioFlags() & 4 != 0 and k.hasRecords();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the type takes a record type argument.
|
|
||||||
pub fn templated(k: NodeKind) bool {
|
|
||||||
return switch (k) {
|
|
||||||
.empty_input, .empty_output, .empty_output_array => false,
|
|
||||||
else => true,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const LinAlgMatrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u32 };
|
pub const LinAlgMatrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u32 };
|
||||||
|
|
@ -701,7 +597,6 @@ pub const TypeTable = struct {
|
||||||
.texture_view => |v| .{ .tag = 14, .a = v.texture, .b = @backingInt(v.kind) },
|
.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 },
|
.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)) },
|
.spirv => |x| .{ .tag = 15, .a = (@as(u64, x.opcode) << 32) | x.size, .b = std.hash.Wyhash.hash(x.alignment, std.mem.sliceAsBytes(x.operands)) },
|
||||||
.node => |x| .{ .tag = 17, .a = @backingInt(x.kind), .b = x.elem },
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -883,7 +778,6 @@ pub const TypeTable = struct {
|
||||||
.triangle => "TriangleStream",
|
.triangle => "TriangleStream",
|
||||||
}, try t.format(gpa, s.elem), ""),
|
}, 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})),
|
.patch => |p| templateName(gpa, if (p.output) "OutputPatch" else "InputPatch", try t.format(gpa, p.elem), try std.fmt.allocPrint(gpa, ", {d}", .{p.count})),
|
||||||
.node => |x| if (x.kind.templated()) templateName(gpa, x.kind.name(), try t.format(gpa, x.elem), "") else x.kind.name(),
|
|
||||||
.descriptor_heap => |h| if (h.sampler) "SamplerDescriptorHeap" else "ResourceDescriptorHeap",
|
.descriptor_heap => |h| if (h.sampler) "SamplerDescriptorHeap" else "ResourceDescriptorHeap",
|
||||||
.dynamic_resource => "<dynamic resource>",
|
.dynamic_resource => "<dynamic resource>",
|
||||||
.texture_view => |v| std.fmt.allocPrint(gpa, "{s}::{s}", .{ try t.format(gpa, v.texture), switch (v.kind) {
|
.texture_view => |v| std.fmt.allocPrint(gpa, "{s}::{s}", .{ try t.format(gpa, v.texture), switch (v.kind) {
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,6 @@ pub const Id = u32;
|
||||||
pub const Op = enum(u16) {
|
pub const Op = enum(u16) {
|
||||||
undef = 1,
|
undef = 1,
|
||||||
source = 3,
|
source = 3,
|
||||||
string = 7,
|
|
||||||
name = 5,
|
name = 5,
|
||||||
member_name = 6,
|
member_name = 6,
|
||||||
extension = 10,
|
extension = 10,
|
||||||
|
|
@ -260,8 +259,6 @@ pub const Section = enum {
|
||||||
memory_model,
|
memory_model,
|
||||||
entry_points,
|
entry_points,
|
||||||
execution_modes,
|
execution_modes,
|
||||||
/// OpString (before OpSource and the names).
|
|
||||||
debug_strings,
|
|
||||||
debug_names,
|
debug_names,
|
||||||
annotations,
|
annotations,
|
||||||
types_globals,
|
types_globals,
|
||||||
|
|
|
||||||
|
|
@ -202,10 +202,6 @@ const Emitter = struct {
|
||||||
used_bindings: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty,
|
used_bindings: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty,
|
||||||
spec_ids: std.AutoHashMapUnmanaged(u32, Id) = .empty,
|
spec_ids: std.AutoHashMapUnmanaged(u32, Id) = .empty,
|
||||||
ext_imports: std.StringHashMapUnmanaged(Id) = .empty,
|
ext_imports: std.StringHashMapUnmanaged(Id) = .empty,
|
||||||
string_ids: std.StringHashMapUnmanaged(Id) = .empty,
|
|
||||||
/// Reads of resource locals nothing assigns: the resource of the same
|
|
||||||
/// type each stands in with where it is used.
|
|
||||||
undef_resources: std.AutoHashMapUnmanaged(u32, Id) = .empty,
|
|
||||||
/// Flattened resource arrays: a variable per element.
|
/// Flattened resource arrays: a variable per element.
|
||||||
flat_vars: std.AutoHashMapUnmanaged(u32, []const Id) = .empty,
|
flat_vars: std.AutoHashMapUnmanaged(u32, []const Id) = .empty,
|
||||||
flat_iface: std.ArrayList(Id) = .empty,
|
flat_iface: std.ArrayList(Id) = .empty,
|
||||||
|
|
@ -841,30 +837,12 @@ const Emitter = struct {
|
||||||
.value => |r| e.val(r),
|
.value => |r| e.val(r),
|
||||||
.literal => |w| w,
|
.literal => |w| w,
|
||||||
.type => |t| try e.typeId(t),
|
.type => |t| try e.typeId(t),
|
||||||
.string => |str| try e.stringId(str),
|
|
||||||
});
|
});
|
||||||
const op: Op = if (x.set != null) .ext_inst else @enumFromInt(@as(u16, @intCast(x.opcode)));
|
const op: Op = if (x.set != null) .ext_inst else @enumFromInt(@as(u16, @intCast(x.opcode)));
|
||||||
try e.b.emit(.functions, op, words.items);
|
try e.b.emit(.functions, op, words.items);
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A declared resource global of type `ty`.
|
|
||||||
fn anyGlobalOf(e: *Emitter, ty: TypeId) ?u32 {
|
|
||||||
for (e.m.globals.items, 0..) |g, gi| {
|
|
||||||
if (g.ty == ty and g.space == .resource and e.global_vars[gi] != 0) return @intCast(gi);
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An OpString of `str` (made once).
|
|
||||||
fn stringId(e: *Emitter, str: []const u8) Error!Id {
|
|
||||||
if (e.string_ids.get(str)) |id| return id;
|
|
||||||
const id = e.b.newId();
|
|
||||||
try e.b.emitWithString(.debug_strings, .string, &.{id}, str, &.{});
|
|
||||||
try e.string_ids.put(e.arena, str, id);
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An OpExtInstImport of `name` (made once).
|
/// An OpExtInstImport of `name` (made once).
|
||||||
fn extInstImport(e: *Emitter, name: []const u8) Error!Id {
|
fn extInstImport(e: *Emitter, name: []const u8) Error!Id {
|
||||||
if (std.mem.eql(u8, name, "GLSL.std.450")) {
|
if (std.mem.eql(u8, name, "GLSL.std.450")) {
|
||||||
|
|
@ -1111,7 +1089,6 @@ const Emitter = struct {
|
||||||
.miss => 5317,
|
.miss => 5317,
|
||||||
.callable => 5318,
|
.callable => 5318,
|
||||||
.library => return e.unsupported("library targets are not supported", .{}),
|
.library => return e.unsupported("library targets are not supported", .{}),
|
||||||
.node => return e.unsupported("work graph nodes are not supported in SPIR-V", .{}),
|
|
||||||
};
|
};
|
||||||
const wrapper = e.func_ids[entry.wrapper];
|
const wrapper = e.func_ids[entry.wrapper];
|
||||||
const name = if (e.m.entries.items.len == 1) e.vk.entry_name orelse entry.name else entry.name;
|
const name = if (e.m.entries.items.len == 1) e.vk.entry_name orelse entry.name else entry.name;
|
||||||
|
|
@ -2395,9 +2372,7 @@ const Emitter = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn val(e: *Emitter, r: Ref) Id {
|
fn val(e: *Emitter, r: Ref) Id {
|
||||||
const v = e.vals[r.index()];
|
return e.vals[r.index()];
|
||||||
if (v == 0) if (e.undef_resources.get(r.index())) |stand_in| return stand_in;
|
|
||||||
return v;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn compOf(e: *Emitter, ty: TypeId) Scalar {
|
fn compOf(e: *Emitter, ty: TypeId) Scalar {
|
||||||
|
|
@ -2410,7 +2385,6 @@ const Emitter = struct {
|
||||||
const ri = r.index();
|
const ri = r.index();
|
||||||
switch (i.op) {
|
switch (i.op) {
|
||||||
.constant, .param, .local_var => {},
|
.constant, .param, .local_var => {},
|
||||||
.node_io => return e.unsupported("work graph nodes are not supported in SPIR-V", .{}),
|
|
||||||
.spec_constant => |k| e.vals[ri] = try e.specConstant(k),
|
.spec_constant => |k| e.vals[ri] = try e.specConstant(k),
|
||||||
.spirv_inst => |x| e.vals[ri] = try e.spirvInst(x, i.ty),
|
.spirv_inst => |x| e.vals[ri] = try e.spirvInst(x, i.ty),
|
||||||
.ray_incoming => |k| e.vals[ri] = try e.rayVar(switch (k) {
|
.ray_incoming => |k| e.vals[ri] = try e.rayVar(switch (k) {
|
||||||
|
|
@ -2462,28 +2436,7 @@ const Emitter = struct {
|
||||||
try e.indexed_loads.put(e.arena, @intCast(ri), .{ .global = il.global, .indices = idx, .types = il.index_types, .nonuniform = il.nonuniform });
|
try e.indexed_loads.put(e.arena, @intCast(ri), .{ .global = il.global, .indices = idx, .types = il.index_types, .nonuniform = il.nonuniform });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (e.val(p) == 0 and f.inst(p).op == .local_var) {
|
if (e.val(p) == 0 and f.inst(p).op == .local_var) return e.unsupported("a resource local read before it is assigned", .{});
|
||||||
// A resource local nothing assigns (a struct copied
|
|
||||||
// with a resource member left unset, read where dxc's
|
|
||||||
// legalization folds the read away): its value is
|
|
||||||
// undefined, so any resource of its type will do.
|
|
||||||
// An OpUndef pointer would break logical addressing.
|
|
||||||
// Copies (`res = this`) pass the undefined value on
|
|
||||||
// without assigning it; the first real use takes the
|
|
||||||
// stand-in.
|
|
||||||
const only_copies = for (f.insts.items) |x| {
|
|
||||||
if (x.op != .store or x.op.store.ptr != p) continue;
|
|
||||||
const v = f.inst(x.op.store.value);
|
|
||||||
if (v.op != .load or f.inst(v.op.load).op != .local_var) break false;
|
|
||||||
} else true;
|
|
||||||
if (only_copies) if (e.anyGlobalOf(i.ty)) |g| {
|
|
||||||
if (e.spv_minor >= 4) try e.useVar(e.global_vars[g]);
|
|
||||||
e.vals[ri] = 0;
|
|
||||||
try e.undef_resources.put(e.arena, @intCast(ri), e.global_vars[g]);
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
return e.unsupported("a resource local read before it is assigned", .{});
|
|
||||||
}
|
|
||||||
e.vals[ri] = e.val(p);
|
e.vals[ri] = e.val(p);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -2520,8 +2473,6 @@ const Emitter = struct {
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Copying an undefined resource assigns nothing.
|
|
||||||
if (target.op == .local_var and e.undef_resources.contains(s.value.index())) return;
|
|
||||||
if (target.op == .local_var and isResourceType(e.t, target.ty)) {
|
if (target.op == .local_var and isResourceType(e.t, target.ty)) {
|
||||||
const old = e.vals[s.ptr.index()];
|
const old = e.vals[s.ptr.index()];
|
||||||
if (old != 0 and old != e.val(s.value)) return e.unsupported("assigning different resources to one variable is not supported yet", .{});
|
if (old != 0 and old != e.val(s.value)) return e.unsupported("assigning different resources to one variable is not supported yet", .{});
|
||||||
|
|
@ -4325,20 +4276,12 @@ const Emitter = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn globalOf(e: *Emitter, r: Ref) ?u32 {
|
fn globalOf(e: *Emitter, r: Ref) ?u32 {
|
||||||
return e.globalOfDepth(r, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// (Copies between resource locals can form cycles: give up after
|
|
||||||
/// `max_depth` steps.)
|
|
||||||
fn globalOfDepth(e: *Emitter, r: Ref, depth: u32) ?u32 {
|
|
||||||
const max_depth = 256;
|
|
||||||
if (depth > max_depth) return null;
|
|
||||||
const i = e.f.inst(r);
|
const i = e.f.inst(r);
|
||||||
return switch (i.op) {
|
return switch (i.op) {
|
||||||
.global => |g| g,
|
.global => |g| g,
|
||||||
.load => |p| e.globalOfDepth(p, depth + 1),
|
.load => |p| e.globalOf(p),
|
||||||
.local_var => for (e.f.insts.items) |inst| {
|
.local_var => for (e.f.insts.items) |inst| {
|
||||||
if (inst.op == .store and inst.op.store.ptr == r) break e.globalOfDepth(inst.op.store.value, depth + 1);
|
if (inst.op == .store and inst.op.store.ptr == r) break e.globalOf(inst.op.store.value);
|
||||||
} else null,
|
} else null,
|
||||||
// A specialized parameter: the global it is bound to.
|
// A specialized parameter: the global it is bound to.
|
||||||
.param => |pi| blk: {
|
.param => |pi| blk: {
|
||||||
|
|
|
||||||
|
|
@ -23,9 +23,6 @@ pub const Stage = enum {
|
||||||
promote,
|
promote,
|
||||||
sccp,
|
sccp,
|
||||||
unroll,
|
unroll,
|
||||||
cse,
|
|
||||||
/// Block merging, bypassing and if-conversion (dxil/cfg.zig).
|
|
||||||
cfg,
|
|
||||||
bitcode,
|
bitcode,
|
||||||
container,
|
container,
|
||||||
spirv,
|
spirv,
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue