Compare commits

..

No commits in common. "main" and "unreal-engine" have entirely different histories.

59 changed files with 462 additions and 4862 deletions

View File

@ -3,7 +3,6 @@ name: Cross-platform builds
on:
push:
branches: [main]
tags: ['v*']
workflow_dispatch:
permissions:
@ -24,13 +23,12 @@ jobs:
include:
- name: windows-x86_64
target: x86_64-windows-gnu
archive: zip
- name: linux-x86_64
target: x86_64-linux-gnu.2.28
archive: tar.gz
- name: macos-aarch64
target: aarch64-macos.13.0
archive: zip
- name: macos-x86_64
target: x86_64-macos.13.0
steps:
- name: Check out source
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
@ -50,50 +48,16 @@ jobs:
-Dcpu=baseline
--prefix zig-out/${{ matrix.name }}
- name: Package Linux build
if: matrix.archive == 'tar.gz'
# A tar archive preserves executable permissions inside the uploaded ZIP.
- name: Package build
run: >-
tar -czf zdxc-${{ matrix.name }}.tar.gz
-C zig-out/${{ matrix.name }} bin lib include
- name: Package Windows and macOS builds
if: matrix.archive == 'zip'
working-directory: zig-out/${{ matrix.name }}
run: zip -r ../../zdxc-${{ matrix.name }}.zip bin lib include
- name: Upload build
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: zdxc-${{ matrix.name }}
path: zdxc-${{ matrix.name }}.${{ matrix.archive }}
path: zdxc-${{ matrix.name }}.tar.gz
if-no-files-found: error
retention-days: 14
release:
name: Publish release binaries
needs: build
if: startsWith(github.ref, 'refs/tags/v') && !contains(github.ref, '-rc')
runs-on: ubuntu-24.04
timeout-minutes: 10
permissions:
contents: write
steps:
- name: Download all platform bundles
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
pattern: zdxc-*
path: artifacts
merge-multiple: true
- name: Create or update GitHub Release
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
TAG: ${{ github.ref_name }}
run: |
if gh release view "$TAG" >/dev/null 2>&1; then
gh release upload "$TAG" artifacts/*.tar.gz artifacts/*.zip --clobber
else
gh release create "$TAG" artifacts/*.tar.gz artifacts/*.zip \
--verify-tag --title "zdxc $TAG" --generate-notes
fi

26
LICENSE
View File

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

View File

@ -1,5 +1,5 @@
<p align="center">
<img src="docs/assets/logo.svg" width="100" alt="zdxc" />
<img src="docs/assets/logo.svg" width="320" alt="zdxc" />
</p>
<p align="center">
@ -7,21 +7,21 @@
</p>
<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 align="center">
<a href="https://zdxc.org">zdxc.org</a> ·
<a href="#quick-start">Quick start</a> ·
<a href="https://zdxc.org/manual.html">Manual</a> ·
<a href="docs/manual/">Manual source</a>
<a href="docs/dropin.md">DXC drop-in</a> ·
<a href="docs/c-api.md">C API</a> ·
<a href="docs/batch.md">Batch compilation</a>
</p>
---
zdxc is an HLSL compiler written from scratch in Zig. It supports HLSL 2018
and 2021, emits DXIL and SPIR-V, supports DXC-style command lines, and
provides a DXC-compatible COM interface for existing engine integrations.
zdxc is an HLSL 2021 compiler written from scratch in Zig. It emits DXIL and
SPIR-V, supports DXC-style command lines, and provides a DXC-compatible COM
interface for existing engine integrations.
Use it as a development drop-in replacement for DXC, link its small C API directly,
or import it as a Zig module. The compiler has no package dependencies and
@ -29,7 +29,7 @@ signs its own DXIL, so there is no separate `dxil.dll` to ship.
| Fast iteration | Small footprint | Easy to embed |
| :--- | :--- | :--- |
| About **15× faster compilation** in the Hyperion benchmark. | **4.2 MB** Windows drop-in, compared with **19.3 MB** for DXC plus its DXIL library. | A **static library** by default, with a C API and a native Zig module. |
| About **14× faster compilation** in the Hyperion benchmark below. | **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
@ -54,39 +54,76 @@ zig-out/bin/zdxc -spirv -T ps_6_0 -E main shader.hlsl -Fo shader.spv
The build installs the compiler in `zig-out/bin/`, the library in
`zig-out/lib/`, and the public header in `zig-out/include/`.
## Documentation and downloads
### Automated builds
Read the [manual on zdxc.org](https://zdxc.org/manual.html) for command-line
options, batch compilation, the C API, DXC drop-in support, and Zig integration.
The [manual Markdown sources](docs/manual/) live in this repository.
Pushes to `main` run the [cross-platform build workflow](.github/workflows/build.yml)
with Zig 0.17.0. It cross-compiles ReleaseFast builds on Linux for Windows x86-64,
Linux x86-64 (glibc 2.28 or newer), and macOS 13 or newer on both Apple Silicon
and Intel. Each artifact contains the CLI, static C library, header, and DXC
drop-in. These are build checks; they do not run the binaries on each target OS.
For an existing DXC integration, build the drop-in executable and shared library:
Download the `.tar.gz` bundles from a successful run's **Artifacts** section
on [GitHub Actions](https://github.com/peterino2/zdxc/actions). Artifacts are
retained for 14 days. The workflow can also be started manually.
## Use it your way
### Replace DXC in an existing integration
```sh
zig build dropin -Doptimize=ReleaseFast
```
Download Windows, Linux, and macOS bundles from a successful run's **Artifacts**
section on [GitHub Actions](https://github.com/peterino2/zdxc/actions).
Each bundle includes the CLI, static C library, header, and DXC drop-in.
This builds `dxc` and the platform's `dxcompiler` shared library. Place them
where your application looks for DXC. The library exports `DxcCreateInstance`
and `DxcCreateInstance2`, including support for `IDxcCompiler3::Compile`.
See the [case studies](https://zdxc.org/case-studies.html) for benchmark
measurements and methodology. In Hyperion's Windows DXIL cook, zdxc's compile
step was **15.5× faster** and the complete shader cook was **2.5× faster**;
Unreal Engine 5.8's editor compiled its 11,156 startup shaders **4.3× faster**.
See the [drop-in guide](docs/dropin.md) for supported interfaces and behavior.
### Link the compiler into your application
The default build produces a static library with a [small C API](docs/c-api.md).
Pass source and options in; get compiled objects and diagnostics back in
memory. Supply an include callback to integrate with your own filesystem.
Prefer a shared library? Build with `-Dlinkage=dynamic`. Zig projects can
import the `zdxc` module and supply an allocator directly to the compilation
API.
### Compile a whole batch
```sh
zig-out/bin/zdxc --job=shaders.json
```
Compile many shaders in one process, with parallel workers and output files
specified per job. See the [batch guide](docs/batch.md) for the JSON format
and threading options.
## Performance in an engine
In a Windows DXIL benchmark, Hyperion cooked Glide's 2,688 shader assets
using either DXC or zdxc through the engine's existing compiler interface.
The machine used a Ryzen 9 7900 with 24 threads; the DXC version was 1.8.2505.
| Measurement | DXC | zdxc | Speedup |
| :--- | ---: | ---: | ---: |
| Complete shader cook, wall time | 58.9 s | 23.2 s | **2.5×** |
| Compile step, summed across workers | 241.3 s | 17.4 s | **13.9×** |
| Median compile call | 12.6 ms | 1.0 ms | **12.7×**¹ |
¹ Ratios use the unrounded measurements.
These are measurements of one engine workload, not a universal speedup.
The complete cook includes preprocessing and asset processing, so its
improvement is smaller than the compile step's. Both builds rendered the
same tested scene; compilation throughput is separate from GPU performance.
## Status
zdxc is **alpha software**. HLSL 2021 is the default; use `-HV 2018` for
HLSL 2018 shaders. DXIL supports work graph node shaders in `lib_6_8`
libraries, SM 6.8 `Barrier()`, and `[WaveSize]` metadata. Work graph nodes
are not supported by the SPIR-V backend. See the
[command-line guide](docs/manual/03-command-line.md) for examples.
DXC compatibility is still being developed; not every interface or feature
is implemented.
The [drop-in manual](https://zdxc.org/manual.html#section-dxc-drop-in) documents
the current interface coverage.
zdxc is **alpha software**, focused on HLSL 2021 (`-HV 2021`). DXC compatibility
is still being developed; not every DXC interface or feature is implemented.
The [drop-in guide](docs/dropin.md) documents the current interface coverage.
To run the unit tests:

View File

@ -1,5 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 72" fill="none">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 232 72" fill="none">
<title>zdxc — tiny directx shader compiler</title>
<style>
.wordmark { stroke: #111110; }
@media (prefers-color-scheme: dark) { .wordmark { stroke: #f4f4ee; } }
</style>
<rect x="4" y="4" width="64" height="64" rx="12" fill="#111110"/>
<path d="M20 20h32v8L32 44h20v8H20v-8l20-16H20Z" fill="#f4f4ee"/>
<path class="wordmark" d="M90 30h24L90 54h24M146 18v36h-22V30h22M158 30l24 24m0-24-24 24M214 30h-20v24h20" stroke-width="5" stroke-linecap="square" stroke-linejoin="miter"/>
</svg>

Before

Width:  |  Height:  |  Size: 271 B

After

Width:  |  Height:  |  Size: 579 B

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,5 @@
/*
* zdxc: an HLSL 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
* default) or dynamically (-Dlinkage=dynamic); it needs nothing besides

View File

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

View File

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

View File

@ -11,7 +11,6 @@ const container = zdxc.dxil.container;
const front = zdxc.front;
const options = zdxc.options;
const FileSystem = front.source.FileSystem;
const stats = zdxc.stats;
pub const Request = struct {
/// dxc command-line options, without the program name: "-T", "ps_6_0",
@ -372,9 +371,7 @@ fn parseArgs(ctx: *Ctx, arena: std.mem.Allocator, args: []const []const u8) !?Op
}
fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
const za = stats.begin(.args);
const opts = try parseArgs(ctx, arena, ctx.req.args) orelse return;
za.end();
ctx.result.object_name = opts.output;
ctx.result.root_signature_name = opts.rootsig_output;
ctx.result.preprocessed_name = opts.pp_output;
@ -448,18 +445,13 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
});
var out: Io.Writer.Allocating = .init(arena);
var module: ?zdxc.ir.ir.Module = null;
const zp = stats.begin(.preprocess);
const opened = try pp.enterMainFile(input);
if (opened) {
if (opts.preprocess) {
try front.pp_print.print(&pp, &out.writer);
zp.end();
} else {
var parser = try front.parser.Parser.fromPreprocessor(arena, &diags, &pp);
zp.end();
const zparse = stats.begin(.parse);
const tu = try parser.parseTranslationUnit();
zparse.end();
if (opts.dump_ast) try front.ast_dump.dumpUnit(ctx.stdout, tu);
if (!opts.parse) {
const is_lib = if (profile) |p| p.kind == .library else true;
@ -475,10 +467,8 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
});
// About one resolution per expression: reserve rather
// than grow, which leaves every old buffer in the arena.
const zs = stats.begin(.sema);
try sema.resolutions.ensureTotalCapacity(arena, parser.toks.len);
try sema.checkUnit(tu);
zs.end();
if (!opts.sema and !diags.hasErrors() and profile != null) {
const stage: zdxc.ir.ir.Stage = switch (profile.?.kind) {
.vertex => .vertex,
@ -491,12 +481,10 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
.amplification => .amplification,
else => .library,
};
const zl = stats.begin(.lower);
module = zdxc.ir.lower.lowerUnit(arena, &sema, .{ .entry = opts.entry, .stage = stage }) catch |e| switch (e) {
error.Unsupported => null,
else => |x| return x,
};
zl.end();
if (module) |*mm| {
mm.native_16bit = opts.enable_16bit;
mm.row_major = opts.row_major;
@ -522,13 +510,8 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
if (opts.parse or opts.sema) return;
if (profile == null) return ctx.fail("missing -T <profile>", .{});
if (module) |*m| {
const zo = stats.begin(.ir_opt);
try zdxc.ir.opt.run(arena, m);
zo.end();
const zv = stats.begin(.spirv);
defer if (opts.spirv) zv.end();
if (opts.spirv) {
try zdxc.ir.inline_calls.runResourceReturns(m);
zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
@ -563,15 +546,13 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
if (opts.rootsig_define) |macro| if (m.entries.items.len == 1) {
m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed;
};
const 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 => {
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
return error.CompileFailed;
},
else => |x| return x,
};
zd.end();
try ctx.needOutput(opts);
ctx.result.object = dxil_out.object;
ctx.result.reflection = dxil_out.reflection;

View File

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

View File

@ -14,7 +14,6 @@
//! does (test/dropin in the development repo compares the two).
const std = @import("std");
const BumpArena = @import("zdxc").BumpArena;
const builtin = @import("builtin");
const zdxc = @import("zdxc");
const compile = zdxc.compile;
@ -112,8 +111,6 @@ const IID_IDxcIncludeHandler = GUID.parse("7f61fc7d-950d-467f-b3e3-3c02fb49187c"
const IID_IDxcOperationResult = GUID.parse("cedb484a-d4e9-445a-b991-ca21ca157dc2");
const IID_IDxcResult = GUID.parse("58346cda-dde7-4497-9461-6f87af5e0659");
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_IDxcVersionInfo = GUID.parse("b04f5b50-2059-4f12-a8ff-a1e0cde1cc7e");
@ -741,18 +738,6 @@ const Compiler3Vtbl = extern struct {
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 {
unknown: UnknownVtbl,
GetVersion: *const fn (This, ?*u32, ?*u32) callconv(cc) HRESULT,
@ -762,17 +747,8 @@ const VersionInfoVtbl = extern struct {
const Compiler = struct {
compiler: Iface(Compiler3Vtbl) = .{ .vtbl = &compiler_vtbl },
version: Iface(VersionInfoVtbl) = .{ .vtbl = &version_vtbl },
legacy: Iface(Compiler2Vtbl) = .{ .vtbl = &legacy_vtbl },
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 = .{
.unknown = .{ .QueryInterface = queryInterface, .AddRef = addRef, .Release = release },
.Compile = compileFn,
@ -793,8 +769,6 @@ const Compiler = struct {
&c.compiler
else if (iid.eql(IID_IDxcVersionInfo))
&c.version
else if (iid.eql(IID_IDxcCompiler) or iid.eql(IID_IDxcCompiler2))
&c.legacy
else
null;
if (p == null) {
@ -859,92 +833,13 @@ const Compiler = struct {
_ = put(out, null);
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
/// gives its blocks back to the OS (smp_allocator maps 64 KiB and up
/// directly), and faulting fresh pages in again costs more than the compile
/// on many threads. What a thread keeps is capped at `retain_limit`.
threadlocal var thread_arena: ?BumpArena = null;
threadlocal var thread_arena: ?std.heap.ArenaAllocator = null;
const retain_limit = 64 << 20;
fn run(source: *const Buffer, wargs: []const ?[*:0]const WCHAR, include: ?*anyopaque) error{ OutOfMemory, InvalidArgument }!*Result {
@ -955,17 +850,11 @@ fn run(source: *const Buffer, wargs: []const ?[*:0]const WCHAR, include: ?*anyop
const args = try a.alloc([]const u8, wargs.len);
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 &.{};
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 threaded: std.Io.Threaded = .init_single_threaded;
var req: compile.Request = .{
.args = args,
.source = text,
.source_name = source_name,
.source = try decodeText(a, bytes, source.encoding),
.io = threaded.io(),
.fs = NoFs.fileSystem(),
.compat_notes = false,

View File

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

View File

@ -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, &copy, k);
if (k.failed) return error.OutOfMemory;
return k.buf.items;
}
};
/// Replaces `func`'s repeated computations; true if any.
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
const zone = stats.begin(.cse);
defer zone.end();
const f = &m.functions.items[func];
const insts = f.insts.items;
const n: u32 = @intCast(insts.len);
const nb = f.num_blocks;
if (n == 0 or nb == 0) return false;
const block_start = try a.alloc(u32, nb + 1);
{
var b: u32 = 0;
block_start[0] = 0;
for (insts, 0..) |inst, i| if (isTerminator(inst)) {
if (b >= nb) return false;
b += 1;
block_start[b] = @intCast(i + 1);
};
if (b != nb or block_start[nb] != n) return false;
}
// Successors, predecessors.
const succ_off = try a.alloc(u32, nb + 1);
var succs: std.ArrayList(u32) = .empty;
for (0..nb) |b| {
succ_off[b] = @intCast(succs.items.len);
switch (insts[block_start[b + 1] - 1].op) {
.br => |br| {
try succs.append(a, br.then);
if (br.@"else") |e| try succs.append(a, e);
},
.@"switch" => |sw| {
try succs.append(a, sw.default);
for (sw.cases) |c| try succs.append(a, c.block);
},
else => {},
}
}
succ_off[nb] = @intCast(succs.items.len);
const pred_off = try a.alloc(u32, nb + 1);
@memset(pred_off, 0);
for (succs.items) |s| pred_off[s + 1] += 1;
for (1..nb + 1) |b| pred_off[b] += pred_off[b - 1];
const preds = try a.alloc(u32, succs.items.len);
{
const fill = try a.dupe(u32, pred_off[0..nb]);
for (0..nb) |b| for (succs.items[succ_off[b]..succ_off[b + 1]]) |s| {
preds[fill[s]] = @intCast(b);
fill[s] += 1;
};
}
// Reverse postorder, then immediate dominators (Cooper, Harvey and
// Kennedy).
const rpo_index = try a.alloc(u32, nb);
@memset(rpo_index, none);
const rpo = try a.alloc(u32, nb);
var nr: u32 = 0;
{
const post = try a.alloc(u32, nb);
var np: u32 = 0;
const seen = try a.alloc(bool, nb);
@memset(seen, false);
const Frame = struct { b: u32, next: u32 };
var stack: std.ArrayList(Frame) = .empty;
try stack.append(a, .{ .b = 0, .next = succ_off[0] });
seen[0] = true;
while (stack.items.len > 0) {
const top = &stack.items[stack.items.len - 1];
if (top.next < succ_off[top.b + 1]) {
const s = succs.items[top.next];
top.next += 1;
if (!seen[s]) {
seen[s] = true;
try stack.append(a, .{ .b = s, .next = succ_off[s] });
}
} else {
post[np] = top.b;
np += 1;
_ = stack.pop();
}
}
for (0..np) |k| {
rpo[k] = post[np - 1 - k];
rpo_index[rpo[k]] = @intCast(k);
}
nr = np;
}
const idom = try a.alloc(u32, nb);
@memset(idom, none);
idom[0] = 0;
{
var changed = true;
while (changed) {
changed = false;
for (rpo[1..nr]) |b| {
var new: u32 = none;
for (preds[pred_off[b]..pred_off[b + 1]]) |p| {
if (idom[p] == none) continue;
if (new == none) {
new = p;
continue;
}
var x = p;
var y = new;
while (x != y) {
while (rpo_index[x] > rpo_index[y]) x = idom[x];
while (rpo_index[y] > rpo_index[x]) y = idom[y];
}
new = x;
}
if (new != idom[b]) {
idom[b] = new;
changed = true;
}
}
}
}
// Dominator tree children, in reverse postorder.
const child_off = try a.alloc(u32, nb + 1);
@memset(child_off, 0);
for (rpo[1..nr]) |b| child_off[idom[b] + 1] += 1;
for (1..nb + 1) |b| child_off[b] += child_off[b - 1];
const children = try a.alloc(u32, if (nr > 0) nr - 1 else 0);
{
const fill = try a.dupe(u32, child_off[0..nb]);
for (rpo[1..nr]) |b| {
children[fill[idom[b]]] = b;
fill[idom[b]] += 1;
}
}
const repl = try a.alloc(?Value, n);
@memset(repl, null);
// The keys of the instructions available (in the dominating blocks),
// to the instruction.
var table: std.StringHashMapUnmanaged(u32) = .empty;
var added: std.ArrayList([]const u8) = .empty;
var key: Key = .{ .a = a, .repl = repl };
var found = false;
const Frame = struct { b: u32, next: u32, mark: usize };
var stack: std.ArrayList(Frame) = .empty;
try stack.append(a, .{ .b = 0, .next = child_off[0], .mark = 0 });
var entered = true;
while (stack.items.len > 0) {
const top = &stack.items[stack.items.len - 1];
if (entered) {
entered = false;
top.mark = added.items.len;
for (block_start[top.b]..block_start[top.b + 1]) |i| {
const inst = insts[i];
if (!eligible(m, inst)) continue;
// (The key is built in one buffer, and kept only if new.)
const gop = try table.getOrPut(a, try key.build(inst));
if (gop.found_existing) {
repl[i] = .{ .inst = gop.value_ptr.* };
found = true;
} else {
gop.key_ptr.* = try a.dupe(u8, key.buf.items);
gop.value_ptr.* = @intCast(i);
try added.append(a, gop.key_ptr.*);
}
}
}
if (top.next < child_off[top.b + 1]) {
const c = children[top.next];
top.next += 1;
try stack.append(a, .{ .b = c, .next = child_off[c], .mark = 0 });
entered = true;
} else {
for (added.items[top.mark..]) |k| _ = table.remove(k);
added.shrinkRetainingCapacity(top.mark);
_ = stack.pop();
}
}
if (!found) return false;
// Renumber without the replaced instructions.
const index = try a.alloc(u32, n);
var count: u32 = 0;
for (0..n) |i| {
index[i] = count;
if (repl[i] == null) count += 1;
}
const Map = struct {
repl: []const ?Value,
index: []const u32,
pub fn visit(ctx: *@This(), v: Value, _: promote.Role) Value {
var x = v;
while (x == .inst) {
const r = ctx.repl[x.inst] orelse break;
x = r;
}
return if (x == .inst) .{ .inst = ctx.index[x.inst] } else x;
}
};
var map: Map = .{ .repl = repl, .index = index };
const ma = m.allocator();
var out: std.ArrayList(Inst) = .empty;
try out.ensureTotalCapacityPrecise(ma, count);
for (insts, 0..) |inst, i| {
if (repl[i] != null) continue;
var copy = inst;
try promote.operands(true, ma, &copy, &map);
out.appendAssumeCapacity(copy);
}
f.insts = out;
return true;
}

File diff suppressed because it is too large Load Diff

View File

@ -191,22 +191,6 @@ pub fn analyze(m: *const module.Module, f: *const module.Function, o: Options) I
fl |= bit.requires_group;
info.mask &= stage_group;
},
// Barrier by memory type, UAV or node record: groupshared memory
// (not as part of ALL_MEMORY, which may drop it) or group
// sync / scope semantics need a group (as dxc's
// BarrierRequiresGroup).
244, 245, 246 => if (args.len > 2) {
var needs = false;
if (code == 244) if (constInt(m, args[1])) |mem| {
const kept = if (mem == 0xF) mem & ~@as(i64, 2) else mem;
needs = kept & 2 != 0;
};
if (constInt(m, args[2])) |sem| needs = needs or sem & 3 != 0;
if (needs) {
fl |= bit.requires_group;
info.mask &= stage_group;
}
},
else => {},
}
}

View File

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

View File

@ -15,7 +15,6 @@
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const stats = @import("../stats.zig");
const Value = module.Value;
const Inst = module.Inst;
@ -23,14 +22,14 @@ const TypeId = module.TypeId;
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;
/// Visits each operand of `inst` (with the way it is used) through
/// `ctx.visit(value, role) Value`. With `write`, the results replace the
/// 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 {
fn one(c: anytype, v: *Value, role: Role) void {
const r = c.visit(v.*, role);
@ -124,9 +123,6 @@ fn isScalar(m: *const module.Module, ty: TypeId) bool {
/// `dyn` maps the dynamically indexed getelementptrs into locals to the
/// components [lo, hi) they can reach; one missing from it can reach all.
pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashMapUnmanaged(u32, [2]u32)) Allocator.Error!void {
const zone = stats.begin(.promote);
stats.add(.promote_runs, 1);
defer zone.end();
const f = &m.functions.items[func];
const insts = f.insts.items;
const n: u32 = @intCast(insts.len);
@ -137,25 +133,15 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
// per edge, so a switch's repeated target counts once per case).
const block_start = try a.alloc(u32, nb + 1);
const block_of = try a.alloc(u32, n);
// The allocas, getelementptrs, and loads and stores, in order: the
// passes over just those walk these, not every instruction.
var allocas: std.ArrayList(u32) = .empty;
var geps: std.ArrayList(u32) = .empty;
var mems: std.ArrayList(u32) = .empty;
{
var b: u32 = 0;
block_start[0] = 0;
for (insts, 0..) |inst, i| {
if (b >= nb) return; // not the block layout this pass expects
block_of[i] = b;
switch (inst.op) {
.alloca => try allocas.append(a, @intCast(i)),
.gep => try geps.append(a, @intCast(i)),
.load, .store => try mems.append(a, @intCast(i)),
else => if (isTerminator(inst)) {
if (isTerminator(inst)) {
b += 1;
block_start[b] = @intCast(i + 1);
},
}
}
if (b != nb) return;
@ -281,9 +267,8 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
@memset(var_base, none);
const elem_ty = try a.alloc(TypeId, n);
const direct = try a.alloc(bool, n);
for (allocas.items) |i| {
const x = insts[i].op.alloca;
switch (m.types.items[x.elem]) {
for (insts, 0..) |inst, i| switch (inst.op) {
.alloca => |x| switch (m.types.items[x.elem]) {
.array => |arr| if (isScalar(m, arr.elem) and arr.len > 0) {
var_base[i] = 0;
elem_ty[i] = arr.elem;
@ -294,8 +279,9 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
elem_ty[i] = x.elem;
direct[i] = true;
},
}
}
},
else => {},
};
// getelementptrs of candidates: the alloca and the element they
// address (`none` for a dynamic index, which pins its range).
const gep_alloca = try a.alloc(u32, n);
@ -325,9 +311,8 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
};
// (Code no path reaches, such as loops unrolling left behind, does
// not count.)
for (geps.items) |i| if (rpo_index[block_of[i]] != none) {
const g = insts[i].op.gep;
if (g.ptr == .inst and var_base[g.ptr.inst] != none and insts[g.ptr.inst].op == .alloca) {
for (insts, 0..) |inst, i| if (rpo_index[block_of[i]] != none) switch (inst.op) {
.gep => |g| if (g.ptr == .inst and var_base[g.ptr.inst] != none and insts[g.ptr.inst].op == .alloca) {
const al = g.ptr.inst;
if (direct[al]) {
var_base[al] = none;
@ -337,20 +322,20 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
if (k) |kk| {
gep_alloca[i] = al;
gep_k[i] = kk;
} else if (dyn.contains(i) and g.indices.len == 2 and constInt(m, g.indices[0]) == 0) {
} else if (dyn.contains(@intCast(i)) and g.indices.len == 2 and constInt(m, g.indices[0]) == 0) {
gep_alloca[i] = al;
gep_k[i] = none;
} else var_base[al] = none;
}
},
else => {},
};
{
var scan: Scan = .{ .insts = insts, .var_base = var_base, .direct = direct, .gep_alloca = gep_alloca };
for (insts, 0..) |*inst, i| if (rpo_index[block_of[i]] != none) try operands(false, a, inst, &scan);
}
// Loads and stores must move whole elements of the element type.
for (mems.items) |i| {
for (insts, 0..) |inst, i| {
if (rpo_index[block_of[i]] == none) continue;
const inst = insts[i];
const ptr, const ty = switch (inst.op) {
.load => |x| .{ x.ptr, inst.ty },
.store => |x| .{ x.ptr, typeOf(m, f, x.val) },
@ -363,16 +348,14 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
// Variables.
var nv: u32 = 0;
for (allocas.items) |i| {
const inst = insts[i];
if (var_base[i] == none) continue;
for (insts, 0..) |inst, i| {
if (inst.op != .alloca or var_base[i] == none) continue;
var_base[i] = nv;
nv += if (direct[i]) 1 else @intCast(m.types.items[inst.op.alloca.elem].array.len);
}
const var_ty = try a.alloc(TypeId, nv);
for (allocas.items) |i| {
const inst = insts[i];
if (var_base[i] == none) continue;
for (insts, 0..) |inst, i| {
if (inst.op != .alloca or var_base[i] == none) continue;
const len: u32 = if (direct[i]) 1 else @intCast(m.types.items[inst.op.alloca.elem].array.len);
@memset(var_ty[var_base[i]..][0..len], elem_ty[i]);
}
@ -382,12 +365,12 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
@memset(pinned, false);
const keep = try a.alloc(bool, n);
@memset(keep, false);
for (geps.items) |i| {
if (gep_alloca[i] == none or gep_k[i] != none) continue;
for (insts, 0..) |inst, i| {
if (inst.op != .gep or gep_alloca[i] == none or gep_k[i] != none) continue;
const al = gep_alloca[i];
if (var_base[al] == none) continue;
const len: u32 = @intCast(m.types.items[insts[al].op.alloca.elem].array.len);
const r = dyn.get(i).?;
const r = dyn.get(@intCast(i)).?;
const lo = @min(r[0], len);
const hi = @min(r[1], len);
@memset(pinned[var_base[al] + lo .. var_base[al] + hi], true);
@ -396,11 +379,11 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
// The variable an instruction loads or stores, or `none`.
const access = try a.alloc(u32, n);
@memset(access, none);
for (mems.items) |i| {
const ptr = switch (insts[i].op) {
for (insts, 0..) |inst, i| {
const ptr = switch (inst.op) {
.load => |x| x.ptr,
.store => |x| x.ptr,
else => unreachable,
else => continue,
};
if (ptr != .inst) continue;
const p = ptr.inst;
@ -417,19 +400,19 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
@memset(first_block, none);
const global = try a.alloc(bool, nv);
@memset(global, false);
for (mems.items) |i| {
for (insts, 0..) |inst, i| {
const v = access[i];
if (v == none) continue;
if (first_block[v] == none) {
first_block[v] = block_of[i];
if (insts[i].op == .load) global[v] = true;
if (inst.op == .load) global[v] = true;
} else if (first_block[v] != block_of[i]) global[v] = true;
}
const Def = struct { v: u32, b: u32 };
var defs: std.ArrayList(Def) = .empty;
for (mems.items) |i| {
for (insts, 0..) |inst, i| {
const v = access[i];
if (v == none or insts[i].op != .store or !global[v] or rpo_index[block_of[i]] == none) continue;
if (v == none or inst.op != .store or !global[v] or rpo_index[block_of[i]] == none) continue;
try defs.append(a, .{ .v = v, .b = block_of[i] });
}
std.sort.pdq(Def, defs.items, {}, struct {
@ -569,8 +552,8 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
filled[j] += 1;
}
}
for (mems.items) |i| {
if (access[i] != none and insts[i].op == .load and repl[i] == null)
for (insts, 0..) |inst, i| {
if (access[i] != none and inst.op == .load and repl[i] == null)
repl[i] = try Zero.get(a, m, &zeros, var_ty[access[i]]);
}
@ -625,18 +608,17 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
// The instructions that go: promoted allocas, their getelementptrs,
// loads and stores.
const removed = try a.alloc(bool, n);
@memset(removed, false);
for (allocas.items) |i| removed[i] = var_base[i] != none and !keep[i];
for (geps.items) |i| removed[i] = gep_alloca[i] != none and var_base[gep_alloca[i]] != none and gep_k[i] != none and !pinned[var_base[gep_alloca[i]] + gep_k[i]];
for (mems.items) |i| removed[i] = access[i] != none;
for (insts, 0..) |inst, i| removed[i] = switch (inst.op) {
.alloca => var_base[i] != none and !keep[i],
.gep => gep_alloca[i] != none and var_base[gep_alloca[i]] != none and gep_k[i] != none and !pinned[var_base[gep_alloca[i]] + gep_k[i]],
.load, .store => access[i] != none,
else => false,
};
// What stays: instructions with effects, and what they read,
// transitively; new phis likewise. (The loads promotion leaves dead,
// such as copies of arguments never read, go too.)
const live = try a.alloc(bool, n + np);
// (What has effects, worked out once for every round.)
var effects: std.ArrayList(u32) = .empty;
for (insts, 0..) |inst, i| if (!removed[i] and hasEffects(m, inst)) try effects.append(a, @intCast(i));
while (true) {
@memset(live, false);
{
@ -661,9 +643,9 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
}
};
var mark: Mark = .{ .repl = repl, .live = live, .removed = removed, .work = &work, .a = a };
for (effects.items) |i| if (reach[block_of[i]] or i == block_start[block_of[i] + 1] - 1) {
for (insts, 0..) |inst, i| if (!removed[i] and hasEffects(m, inst) and (reach[block_of[i]] or i == block_start[block_of[i] + 1] - 1)) {
live[i] = true;
try work.append(a, i);
try work.append(a, @intCast(i));
};
while (work.pop()) |x| {
if (x < n) {
@ -823,44 +805,15 @@ fn foldConstantBranches(a: Allocator, m: *module.Module, insts: []Inst, block_st
else => 0,
};
}
/// Whether each entry of `ins` (from `ins[x].block`) is one of the
/// edges to `t` there still are: the k-th entry from a block is,
/// if the block has more than k edges to `t`. `seen` and `edges_to`
/// are per-block scratch (0 and `none`), left as they were.
fn keeps(s: @This(), ins: []const Edge, t: u32, seen: []u32, edges_to: []u32, out: []bool) void {
for (ins, out) |in, *o| {
if (edges_to[in.block] == none) edges_to[in.block] = s.count(in.block, t);
o.* = seen[in.block] < edges_to[in.block];
seen[in.block] += 1;
}
for (ins) |in| {
seen[in.block] = 0;
edges_to[in.block] = none;
}
/// Whether entry `x` of `ins` (from `ins[x].block`) is one of the
/// edges there still are.
fn keeps(s: @This(), ins: []const Edge, x: usize, t: u32) bool {
var before: u32 = 0;
for (ins[0..x]) |in| before += @intFromBool(in.block == ins[x].block);
return before < s.count(ins[x].block, t);
}
};
const edges: Edges = .{ .insts = insts, .block_start = block_start, .reach = reach };
const seen = try a.alloc(u32, nb);
@memset(seen, 0);
const edges_to = try a.alloc(u32, nb);
@memset(edges_to, none);
var kept: std.ArrayList(bool) = .empty;
// Edges into each block from reachable ones. A phi has an entry per
// edge, and folding only takes edges away: one with that many entries
// lost none.
const into = try a.alloc(u32, nb);
@memset(into, 0);
for (0..nb) |p| if (reach[p]) switch (insts[block_start[p + 1] - 1].op) {
.br => |br| {
into[br.then] += 1;
if (br.@"else") |e| into[e] += 1;
},
.@"switch" => |sw| {
into[sw.default] += 1;
for (sw.cases) |cs| into[cs.block] += 1;
},
else => {},
};
for (0..nb) |b| {
const t: u32 = @intCast(b);
const last = block_start[b + 1] - 1;
@ -871,15 +824,12 @@ fn foldConstantBranches(a: Allocator, m: *module.Module, insts: []Inst, block_st
var i = block_start[b];
while (i < last and insts[i].op == .phi) : (i += 1) {
const old = insts[i].op.phi.incoming;
if (old.len == into[b]) continue;
kept.clearRetainingCapacity();
try kept.resize(a, old.len);
edges.keeps(old, t, seen, edges_to, kept.items);
const keep = std.mem.count(bool, kept.items, &.{true});
var keep: usize = 0;
for (0..old.len) |x| keep += @intFromBool(edges.keeps(old, x, t));
if (keep == old.len) continue;
const new = try m.allocator().alloc(Edge, keep);
var k: usize = 0;
for (old, kept.items) |in, kp| if (kp) {
for (old, 0..) |in, x| if (edges.keeps(old, x, t)) {
new[k] = in;
k += 1;
};
@ -888,13 +838,9 @@ fn foldConstantBranches(a: Allocator, m: *module.Module, insts: []Inst, block_st
for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| {
// (Kept entries move down; each is checked against those
// before it in the original order.)
const ins = incoming[j];
if (ins.len == into[b]) continue;
kept.clearRetainingCapacity();
try kept.resize(a, ins.len);
edges.keeps(ins, t, seen, edges_to, kept.items);
const orig = try a.dupe(Edge, incoming[j]);
var k: usize = 0;
for (ins, kept.items) |in, kp| if (kp) {
for (orig, 0..) |in, x| if (edges.keeps(orig, x, t)) {
incoming[j][k] = in;
k += 1;
};
@ -1088,7 +1034,6 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
return null;
},
.binop => |b| {
if (try foldFloat(m, repl, inst)) |v| return v;
const w = S.intWidth(m, inst.ty) orelse return null;
const l = resolve(repl, b.lhs);
const r = resolve(repl, b.rhs);
@ -1128,10 +1073,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,
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;
},
.cmp => |c| {
@ -1164,30 +1105,9 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(t) } });
}
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;
// Each side's possible values: a constant, or selects and phis
// of constants (`(c ? 2 : 1) == 3` is false, as dxc's
// instcombine finds); the same answer for every pair folds.
var lv: Cands = .{};
var rv: Cands = .{};
if (!lv.add(m, f, repl, n, l, 2) or !rv.add(m, f, repl, n, r, 2)) return null;
var result: ?bool = null;
for (lv.vals[0..lv.len]) |lk| for (rv.vals[0..rv.len]) |rk| {
const x = S.bits(lk, w);
const y = S.bits(rk, w);
const x = S.bits(constInt(m, l) orelse return null, w);
const y = S.bits(constInt(m, r) orelse return null, w);
const sx = S.stored(x, w);
const sy = S.stored(y, w);
const t = switch (c.pred) {
@ -1202,12 +1122,8 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
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| {
const t = resolve(repl, sl.t);
const fv = resolve(repl, sl.f);
@ -1280,240 +1196,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 } });
}
/// 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.
fn constFloat(m: *const module.Module, v: Value) ?f64 {
if (v != .constant) return null;

View File

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

View File

@ -8,7 +8,6 @@
//! ZRFL part holding the rest as JSON.
const std = @import("std");
const BumpArena = @import("../BumpArena.zig");
const Allocator = std.mem.Allocator;
const container = @import("container.zig");
@ -195,7 +194,7 @@ test "encode and decode" {
};
const blob = try encode(a, r, &.{});
defer a.free(blob);
var arena: BumpArena = .init(a);
var arena: std.heap.ArenaAllocator = .init(a);
defer arena.deinit();
const view = try container.parse(arena.allocator(), blob);
const back = try decode(arena.allocator(), view.find(part) orelse return error.TestUnexpectedResult);

View File

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

View File

@ -12,7 +12,6 @@
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const stats = @import("../stats.zig");
const unroll = @import("unroll.zig");
const Value = module.Value;
@ -102,8 +101,6 @@ fn successors(term: Inst) Succs {
/// Runs the propagation on `func`; true if it changed anything.
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
const zone = stats.begin(.sccp);
defer zone.end();
const f = &m.functions.items[func];
const insts = f.insts.items;
const n: u32 = @intCast(insts.len);

View File

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

View File

@ -15,7 +15,6 @@
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const stats = @import("../stats.zig");
const promote = @import("promote.zig");
const Value = module.Value;
@ -31,14 +30,9 @@ const none = std.math.maxInt(u32);
const max_trips = 256;
const max_loop_growth = 300;
const max_growth = 65536;
/// For `[unroll]` loops: dxc's limit on their iterations (its
/// DxilLoopUnroll), and no limit on their size but the function's.
const max_marked_trips = 1024;
/// Unrolls the qualifying loops of `func`, innermost first; true if any.
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
const zone = stats.begin(.unroll);
defer zone.end();
var budget: usize = max_growth;
var tried: std.AutoHashMapUnmanaged(u32, void) = .empty;
var any = false;
@ -52,76 +46,15 @@ const Cfg = struct {
succs: [][]u32,
preds: [][]u32,
idom: []u32,
/// Each reachable block's interval in a depth-first walk of the
/// dominator tree (`none` for unreachable blocks): `d` dominates `b`
/// when `b`'s interval is inside `d`'s.
dom_pre: []u32,
dom_post: []u32,
fn dominates(c: *const Cfg, d: u32, b: u32) bool {
if (d == b) return true;
if (c.dom_pre[d] == none or c.dom_pre[b] == none) return false;
return c.dom_pre[d] <= c.dom_pre[b] and c.dom_post[b] <= c.dom_post[d];
var x = b;
while (true) {
if (x == d) return true;
const p = c.idom[x];
if (p == none or p == x) return false;
x = p;
}
};
/// Numbers the dominator tree's blocks in and out of a depth-first walk.
fn domIntervals(a: Allocator, idom: []const u32) Allocator.Error!struct { []u32, []u32 } {
const nb = idom.len;
// Children lists, packed: block b's are kids[first[b]..first[b + 1]].
const first = try a.alloc(u32, nb + 1);
@memset(first, 0);
for (idom, 0..) |p, b| if (p != none and p != b) {
first[p + 1] += 1;
};
for (1..nb + 1) |k| first[k] += first[k - 1];
const fill = try a.dupe(u32, first[0..nb]);
const kids = try a.alloc(u32, first[nb]);
for (idom, 0..) |p, b| if (p != none and p != b) {
kids[fill[p]] = @intCast(b);
fill[p] += 1;
};
const pre = try a.alloc(u32, nb);
const post = try a.alloc(u32, nb);
@memset(pre, none);
@memset(post, none);
if (nb == 0) return .{ pre, post };
var clock: u32 = 0;
// `next` reuses fill: the next child to visit.
@memcpy(fill, first[0..nb]);
var stack: std.ArrayList(u32) = .empty;
try stack.append(a, 0);
pre[0] = clock;
clock += 1;
while (stack.items.len > 0) {
const b = stack.items[stack.items.len - 1];
if (fill[b] < first[b + 1]) {
const k = kids[fill[b]];
fill[b] += 1;
pre[k] = clock;
clock += 1;
try stack.append(a, k);
} else {
post[b] = clock;
clock += 1;
_ = stack.pop();
}
}
return .{ pre, post };
}
/// A loop's blocks: a bit per block of the function, and the list in
/// block order.
const Body = struct {
bits: []u64,
blocks: []const u32,
fn has(b: Body, x: u32) bool {
return b.bits[x >> 6] >> @intCast(x & 63) & 1 != 0;
}
fn add(b: *Body, x: u32) void {
b.bits[x >> 6] |= @as(u64, 1) << @intCast(x & 63);
}
};
@ -146,43 +79,27 @@ fn buildCfg(a: Allocator, f: *const module.Function) Allocator.Error!?Cfg {
}
}
if (b != nb) return null;
// Successors (each once) and predecessors, packed: each block's are a
// slice of one array.
var succ_flat: std.ArrayList(u32) = .empty;
try succ_flat.ensureTotalCapacity(a, 2 * nb);
const succ_off = try a.alloc(u32, nb + 1);
const succs = try a.alloc([]u32, nb);
var pred_lists = try a.alloc(std.ArrayList(u32), nb);
for (pred_lists) |*p| p.* = .empty;
for (0..nb) |bi| {
const start = succ_flat.items.len;
succ_off[bi] = @intCast(start);
var s: std.ArrayList(u32) = .empty;
switch (insts[block_start[bi + 1] - 1].op) {
.br => |br| {
try succ_flat.append(a, br.then);
if (br.@"else") |e| if (e != br.then) try succ_flat.append(a, e);
try s.append(a, br.then);
if (br.@"else") |e| if (e != br.then) try s.append(a, e);
},
.@"switch" => |sw| {
try succ_flat.append(a, sw.default);
for (sw.cases) |c| if (std.mem.indexOfScalar(u32, succ_flat.items[start..], c.block) == null) try succ_flat.append(a, c.block);
try s.append(a, sw.default);
for (sw.cases) |c| if (std.mem.indexOfScalar(u32, s.items, c.block) == null) try s.append(a, c.block);
},
else => {},
}
}
succ_off[nb] = @intCast(succ_flat.items.len);
const succs = try a.alloc([]u32, nb);
for (succs, 0..) |*sl, bi| sl.* = succ_flat.items[succ_off[bi]..succ_off[bi + 1]];
const pred_off = try a.alloc(u32, nb + 1);
@memset(pred_off, 0);
for (succ_flat.items) |t| pred_off[t + 1] += 1;
for (1..nb + 1) |k| pred_off[k] += pred_off[k - 1];
const pred_flat = try a.alloc(u32, succ_flat.items.len);
{
const fill = try a.dupe(u32, pred_off[0..nb]);
for (0..nb) |bi| for (succs[bi]) |t| {
pred_flat[fill[t]] = @intCast(bi);
fill[t] += 1;
};
succs[bi] = s.items;
for (s.items) |t| try pred_lists[t].append(a, @intCast(bi));
}
const preds = try a.alloc([]u32, nb);
for (preds, 0..) |*pl, bi| pl.* = pred_flat[pred_off[bi]..pred_off[bi + 1]];
for (preds, pred_lists) |*p, l| p.* = l.items;
// Reverse postorder, then Cooper, Harvey and Kennedy's dominators.
const order = try a.alloc(u32, nb);
@ -245,8 +162,7 @@ fn buildCfg(a: Allocator, f: *const module.Function) Allocator.Error!?Cfg {
}
}
}
const pre, const post = try domIntervals(a, idom);
return .{ .nb = nb, .block_start = block_start, .succs = succs, .preds = preds, .idom = idom, .dom_pre = pre, .dom_post = post };
return .{ .nb = nb, .block_start = block_start, .succs = succs, .preds = preds, .idom = idom };
}
fn constInt(m: *const module.Module, v: Value) ?i64 {
@ -366,7 +282,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
// Loops: headers with back edges (from blocks they dominate), and
// their blocks.
const Loop = struct { h: u32, body: Body, latches: []u32 };
const Loop = struct { h: u32, body: []bool, latches: []u32 };
var loops: std.ArrayList(Loop) = .empty;
for (0..nb) |hb| {
const h: u32 = @intCast(hb);
@ -374,30 +290,16 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
var latches: std.ArrayList(u32) = .empty;
for (cfg.preds[h]) |p| if (cfg.idom[p] != none and cfg.dominates(h, p)) try latches.append(a, p);
if (latches.items.len == 0) continue;
const bits = try a.alloc(u64, (nb + 63) / 64);
@memset(bits, 0);
var body: Body = .{ .bits = bits, .blocks = &.{} };
body.add(h);
var count: usize = 1;
const body = try a.alloc(bool, nb);
@memset(body, false);
body[h] = true;
var stack: std.ArrayList(u32) = .empty;
try stack.appendSlice(a, latches.items);
while (stack.pop()) |x| {
if (body.has(x)) continue;
body.add(x);
count += 1;
if (body[x]) continue;
body[x] = true;
for (cfg.preds[x]) |p| if (cfg.idom[p] != none) try stack.append(a, p);
}
// The blocks in order, from the bits.
const blocks = try a.alloc(u32, count);
var k: usize = 0;
for (bits, 0..) |word, wi| {
var w = word;
while (w != 0) : (w &= w - 1) {
blocks[k] = @intCast(wi * 64 + @ctz(w));
k += 1;
}
}
body.blocks = blocks;
try loops.append(a, .{ .h = h, .body = body, .latches = latches.items });
}
@ -407,14 +309,10 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
// that block; their blocks are left unreachable for promotion to drop.
// (Nested ones too: an outer loop whose inner loops do nothing.)
const loop_inst = try a.alloc(bool, insts.len);
@memset(loop_inst, false);
// (The loop whose instructions loop_inst marks, cleared for the next.)
var marked: ?Body = null;
dead: for (loops.items) |lp| {
if (marked) |mk| for (mk.blocks) |bb| @memset(loop_inst[cfg.block_start[bb]..cfg.block_start[bb + 1]], false);
marked = null;
var exit: u32 = none;
for (lp.body.blocks) |bb| {
for (0..nb) |bb| {
if (!lp.body[bb]) continue;
for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| switch (insts[i].op) {
.br, .@"switch" => {},
.ret, .@"unreachable", .store, .atomicrmw, .cmpxchg => continue :dead,
@ -424,14 +322,14 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
},
else => {},
};
for (cfg.succs[bb]) |s| if (!lp.body.has(s)) {
for (cfg.succs[bb]) |s| if (!lp.body[s]) {
if (exit != none and exit != s) continue :dead;
exit = s;
};
}
if (exit == none) continue;
var pre: u32 = none;
for (cfg.preds[lp.h]) |p| if (!lp.body.has(p)) {
for (cfg.preds[lp.h]) |p| if (!lp.body[p]) {
if (pre != none) continue :dead;
pre = p;
};
@ -440,8 +338,9 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
if (pterm.op != .br) continue;
if (pterm.op.br.then == exit or pterm.op.br.@"else" == exit) continue;
for (lp.body.blocks) |bb| @memset(loop_inst[cfg.block_start[bb]..cfg.block_start[bb + 1]], true);
marked = lp.body;
for (0..nb) |bb| for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| {
loop_inst[i] = lp.body[bb];
};
// The exit's phis: one value from the loop, from before it.
const phi_end = blk: {
var i = cfg.block_start[exit];
@ -451,7 +350,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
const from_loop = try a.alloc(?Value, phi_end - cfg.block_start[exit]);
for (cfg.block_start[exit]..phi_end, from_loop) |i, *fl| {
fl.* = null;
for (insts[i].op.phi.incoming) |in| if (lp.body.has(in.block)) {
for (insts[i].op.phi.incoming) |in| if (lp.body[in.block]) {
if (in.val == .inst and loop_inst[in.val.inst]) continue :dead;
if (fl.* != null and !std.meta.eql(fl.*.?, in.val)) continue :dead;
fl.* = in.val;
@ -468,7 +367,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
};
var check: Check = .{ .loop_inst = loop_inst };
for (0..nb) |bb| {
if (lp.body.has(@intCast(bb))) continue;
if (lp.body[bb]) continue;
for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| {
if (bb == exit and i < phi_end) continue;
var copy = insts[i];
@ -480,7 +379,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
const ma = m.allocator();
for (cfg.block_start[exit]..phi_end, from_loop) |i, fl| {
var edges: std.ArrayList(Edge) = .empty;
for (insts[i].op.phi.incoming) |in| if (!lp.body.has(in.block)) try edges.append(ma, in);
for (insts[i].op.phi.incoming) |in| if (!lp.body[in.block]) try edges.append(ma, in);
if (fl) |v| try edges.append(ma, .{ .val = v, .block = pre });
insts[i].op.phi.incoming = edges.items;
}
@ -488,7 +387,9 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
if (pterm.op.br.@"else") |*e| if (e.* == lp.h) {
e.* = exit;
};
for (lp.body.blocks) |bb| insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable";
for (0..nb) |bb| if (lp.body[bb]) {
insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable";
};
return true;
}
@ -496,28 +397,25 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
const h = lp.h;
if (tried.contains(h)) continue;
// Innermost: no other loop's header inside.
for (loops.items) |other| if (other.h != h and lp.body.has(other.h)) continue :candidates;
for (loops.items) |other| if (other.h != h and lp.body[other.h]) continue :candidates;
try tried.put(a, h, {});
// `[unroll]` (its back edge marked by the emitter).
const marked_loop = for (lp.latches) |l| {
if (insts[cfg.block_start[l + 1] - 1].md == .unroll) break true;
} else false;
// One way out: a conditional branch from one block, to one block.
var exiting: u32 = none;
var exit: u32 = none;
var size: usize = 0;
var body_blocks: std.ArrayList(u32) = .empty;
for (lp.body.blocks) |bb| {
try body_blocks.append(a, bb);
for (0..nb) |bb| {
if (!lp.body[bb]) continue;
try body_blocks.append(a, @intCast(bb));
size += cfg.block_start[bb + 1] - cfg.block_start[bb];
const term = insts[cfg.block_start[bb + 1] - 1].op;
if (term == .@"switch") {
for (cfg.succs[bb]) |s| if (!lp.body.has(s)) continue :candidates;
for (cfg.succs[bb]) |s| if (!lp.body[s]) continue :candidates;
}
for (cfg.succs[bb]) |s| if (!lp.body.has(s)) {
for (cfg.succs[bb]) |s| if (!lp.body[s]) {
if (exiting != none) continue :candidates;
exiting = bb;
exiting = @intCast(bb);
exit = s;
};
}
@ -525,11 +423,11 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
const xterm = insts[cfg.block_start[exiting + 1] - 1].op;
if (xterm != .br or xterm.br.@"else" == null) continue;
const stay = if (xterm.br.then == exit) xterm.br.@"else".? else xterm.br.then;
if (!lp.body.has(stay) or stay == exit) continue;
if (!lp.body[stay] or stay == exit) continue;
for (lp.latches) |l| if (!cfg.dominates(exiting, l)) continue :candidates;
// One way in.
var pre: u32 = none;
for (cfg.preds[h]) |p| if (!lp.body.has(p)) {
for (cfg.preds[h]) |p| if (!lp.body[p]) {
if (pre != none) continue :candidates;
pre = p;
};
@ -554,7 +452,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
while (true) {
const c = eval(m, f, &state, xcond, 0) orelse continue :candidates;
if ((c & 1) != stay_on) break;
if (states.items.len >= @as(usize, if (marked_loop) max_marked_trips else max_trips)) continue :candidates;
if (states.items.len >= max_trips) continue :candidates;
try states.append(a, try state.clone(a));
// Next values: what every latch passes back (the same).
var next: std.AutoHashMapUnmanaged(u32, i64) = .empty;
@ -577,7 +475,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
}
const trips = states.items.len;
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;
try states.append(a, state); // the last pass, up to the exit
@ -722,7 +620,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
const last: Mapper = .{ .maps = maps, .new_index = new_index, .k = copies - 1 };
const in_body = try a.alloc(bool, n0);
for (0..nb) |bb| for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| {
in_body[i] = lp.body.has(@intCast(bb));
in_body[i] = lp.body[bb];
};
const Outside = struct {
last: Mapper,
@ -734,7 +632,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
};
var outside: Outside = .{ .last = last, .in_body = in_body };
for (0..nb) |bb| {
if (lp.body.has(@intCast(bb))) {
if (lp.body[bb]) {
// The originals: unreachable now.
insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable";
continue;

View File

@ -7,7 +7,6 @@
//! builtin types are recognized by name.
const std = @import("std");
const BumpArena = @import("../BumpArena.zig");
const Allocator = std.mem.Allocator;
const ast = @import("ast.zig");
const lexer = @import("lexer.zig");
@ -41,8 +40,6 @@ pub const Parser = struct {
/// Name of the struct most recently parsed by parseStructDeclInto
/// (synthesized for anonymous structs), for `typedef struct ...`.
last_struct_name: []const u8 = "",
/// The last parseType read `const` after the type (`float const x`).
type_const: bool = false,
/// The qualifier words read by the last parseQualifiers call.
last_quals: []const ast.QualWord = &.{},
/// Qualifier words for the next parseDeclaratorsInto call.
@ -412,8 +409,6 @@ pub const Parser = struct {
fn skipTypeAttrs(p: *const Parser, start: usize) usize {
var i = start;
// `T const`: a type qualifier written after the type.
while (p.toks[i].isIdent("const")) i += 1;
if (!(p.toks[i].kind == .l_square and p.toks[i + 1].kind == .l_square)) return i;
var depth: u32 = 0;
while (true) : (i += 1) {
@ -528,7 +523,7 @@ pub const Parser = struct {
defer p.last_quals = words.items;
while (p.at(.identifier)) {
const word = p.tok().text;
if (isReservedDeclspec(word)) {
if (inList(&reserved_declspecs, word)) {
// dxc reports these and parses on as if they were absent.
_ = p.reportAt(p.pos, .@"error", "'{s}' is a reserved keyword in HLSL", .{word});
_ = p.advance();
@ -569,19 +564,10 @@ pub const Parser = struct {
t.pack_matrix = p.packMatrixAt(type_pos);
if (norm != .none) t.norm = norm;
if (words.items.len > 0) t.attr_words = words.items;
p.type_const = false;
while (p.eatIdent("const")) p.type_const = true;
if (p.at(.l_square) and p.peek(1).kind == .l_square) t.attrs = try p.parseAttributes();
return t;
}
/// parseType for a declaration: `const` after the type joins `quals`.
fn parseDeclType(p: *Parser, quals: *ast.Qualifiers) Error!*ast.TypeRef {
const t = try p.parseType();
if (p.type_const) quals.@"const" = true;
return t;
}
fn parseTypeInner(p: *Parser) Error!*ast.TypeRef {
// An elaborated type: `struct S` names S (declaring it if needed).
const elaborated = (p.atIdent("struct") or p.atIdent("class")) and p.peek(1).kind == .identifier and p.peek(2).kind != .l_brace and p.peek(2).kind != .colon;
@ -848,9 +834,9 @@ pub const Parser = struct {
return out.append(p.arena, d);
}
var quals = p.parseQualifiers();
const quals = p.parseQualifiers();
const words = p.last_quals;
const ty = try p.parseDeclType(&quals);
const ty = try p.parseType();
p.decl_quals = words;
const first = out.items.len;
try p.parseDeclaratorsInto(out, attrs, quals, template_params, ty, ctx);
@ -1312,9 +1298,9 @@ pub const Parser = struct {
if (p.atIdent("void") and p.peek(1).kind == .r_paren) _ = p.advance();
while (!p.at(.r_paren)) {
const pattrs = try p.parseAttributes();
var pquals = p.parseQualifiers();
const pquals = p.parseQualifiers();
const pwords = p.last_quals;
const pty = try p.parseDeclType(&pquals);
const pty = try p.parseType();
var pname: []const u8 = "";
var pname_loc = p.tok().loc;
if (p.at(.identifier) and !isReserved(p.tok().text)) {
@ -1520,8 +1506,8 @@ pub const Parser = struct {
/// `expr`, or `T name = init` (C++ condition declaration).
fn parseCondition(p: *Parser) Error!struct { decl: ?*ast.Decl, cond: *ast.Expr } {
if (!p.startsLocalDecl()) return .{ .decl = null, .cond = try p.parseExpr() };
var quals = p.parseQualifiers();
const ty = try p.parseDeclType(&quals);
const quals = p.parseQualifiers();
const ty = try p.parseType();
const name = try p.expectIdent("variable name");
_ = try p.expect(.equal, "'='");
const init_expr = try p.parseAssign();
@ -1579,7 +1565,7 @@ pub const Parser = struct {
if (std.mem.eql(u8, w, "struct") or std.mem.eql(u8, w, "class") or std.mem.eql(u8, w, "typedef") or
std.mem.eql(u8, w, "using") or std.mem.eql(u8, w, "enum") or std.mem.eql(u8, w, "_Static_assert"))
return true;
if (isReservedDeclspec(w)) return true;
if (inList(&reserved_declspecs, w)) return true;
if (isEffectObjectWord(t) and p.peek(1).kind == .identifier) return true;
if (qualifierField(w) != null) {
if (!isContextualQualifier(w)) return true;
@ -1953,22 +1939,14 @@ fn isTechniqueWord(t: Token) bool {
}
/// dxc's g_DeprecatedEffectObjectNames.
const effect_object_words = [_][]const u8{
fn isEffectObjectWord(t: Token) bool {
const names = [_][]const u8{
"texture", "Texture", "pixelshader", "PixelShader", "vertexshader",
"VertexShader", "pixelfragment", "vertexfragment", "ComputeShader", "DomainShader",
"GeometryShader", "HullShader", "BlendState", "DepthStencilState", "DepthStencilView",
"RasterizerState", "RenderTargetView",
};
fn isEffectObjectWord(t: Token) bool {
if (t.kind != .identifier) return false;
const info = word_map.get(t.text) orelse return false;
return info.effect_object;
}
fn isReservedDeclspec(w: []const u8) bool {
const info = word_map.get(w) orelse return false;
return info.declspec;
return t.kind == .identifier and inList(&names, t.text);
}
/// Type attributes that may precede a type: `unorm float`,
@ -2099,8 +2077,6 @@ const WordInfo = struct {
numeric_scalar: bool = false,
object: bool = false,
template: bool = false,
declspec: bool = false,
effect_object: bool = false,
};
fn inList(list: []const []const u8, w: []const u8) bool {
@ -2112,7 +2088,7 @@ fn inList(list: []const []const u8, w: []const u8) bool {
/// replaces linear scans of the lists above (a third of parse time).
const word_map = blk: {
@setEvalBranchQuota(1_000_000);
var words: []const []const u8 = &(reserved_words ++ contextual_words ++ scalar_types ++ object_types ++ enum_typedefs ++ template_types ++ template_funcs ++ reserved_declspecs ++ effect_object_words);
var words: []const []const u8 = &(reserved_words ++ contextual_words ++ scalar_types ++ object_types ++ enum_typedefs ++ template_types ++ template_funcs);
for (qualifier_words) |q| words = words ++ &[_][]const u8{q[0]};
var kvs: [words.len]struct { []const u8, WordInfo } = undefined;
var n: usize = 0;
@ -2125,8 +2101,6 @@ const word_map = blk: {
.numeric_scalar = inList(&scalar_types, w) and !std.mem.endsWith(u8, w, "_packed"),
.object = inList(&object_types, w) or inList(&enum_typedefs, w),
.template = inList(&template_types, w) or inList(&template_funcs, w),
.declspec = inList(&reserved_declspecs, w),
.effect_object = inList(&effect_object_words, w),
};
for (qualifier_words) |q| {
if (std.mem.eql(u8, q[0], w)) info.qualifier = q[1];
@ -2135,66 +2109,9 @@ const word_map = blk: {
n += 1;
}
const final = kvs[0..n].*;
break :blk WordMap(WordInfo, final.len).init(final);
break :blk std.StaticStringMap(WordInfo).initComptime(final);
};
/// A string map built at compile time: an open-addressing table on a cheap
/// hash, comparing a stored hash before any bytes. Most identifiers a
/// lookup sees are not in it, and miss after a probe or two (what
/// std.StaticStringMap does is compare every key of the same length).
fn WordMap(comptime V: type, comptime n: usize) type {
return struct {
const Self = @This();
/// Twice the keys or more, a power of two.
const size = std.math.ceilPowerOfTwoAssert(usize, n * 4);
const empty = std.math.maxInt(u16);
keys: [n][]const u8,
values: [n]V,
hashes: [n]u32,
slots: [size]u16,
fn hash(w: []const u8) u32 {
var h: u32 = 2166136261;
for (w) |c| h = (h ^ c) *% 16777619;
return h;
}
fn init(comptime kvs: anytype) Self {
var m: Self = undefined;
m.slots = @splat(empty);
for (kvs, 0..) |kv, k| {
m.keys[k] = kv[0];
m.values[k] = kv[1];
m.hashes[k] = hash(kv[0]);
var i = m.hashes[k] & (size - 1);
while (m.slots[i] != empty) i = (i + 1) & (size - 1);
m.slots[i] = k;
}
return m;
}
fn get(m: *const Self, w: []const u8) ?V {
const h = hash(w);
var i = h & (size - 1);
while (true) : (i = (i + 1) & (size - 1)) {
const k = m.slots[i];
if (k == empty) return null;
if (m.hashes[k] == h and std.mem.eql(u8, m.keys[k], w)) return m.values[k];
}
}
};
}
test WordMap {
const M = WordMap(u8, 3);
const m = comptime M.init(.{ .{ "float", 1 }, .{ "in", 2 }, .{ "inout", 3 } });
try std.testing.expectEqual(1, m.get("float").?);
try std.testing.expectEqual(3, m.get("inout").?);
try std.testing.expectEqual(null, m.get("floa"));
try std.testing.expectEqual(null, m.get(""));
}
fn isNumericScalar(w: []const u8) bool {
const info = word_map.get(w) orelse return false;
return info.numeric_scalar;
@ -2237,7 +2154,7 @@ const TestParse = struct {
mfs: source.MemoryFs = .{},
sm: source.SourceManager = undefined,
diags: Diagnostics = undefined,
arena: BumpArena = undefined,
arena: std.heap.ArenaAllocator = undefined,
out: std.Io.Writer.Allocating = undefined,
fn run(t: *TestParse, text: []const u8) ![]const u8 {

View File

@ -4,7 +4,6 @@
//! disabled macro.
const std = @import("std");
const BumpArena = @import("../BumpArena.zig");
const Allocator = std.mem.Allocator;
const source = @import("source.zig");
const lexer = @import("lexer.zig");
@ -1447,7 +1446,7 @@ const TestPP = struct {
mfs: source.MemoryFs = .{},
sm: source.SourceManager = undefined,
diags: Diagnostics = undefined,
arena: BumpArena = undefined,
arena: std.heap.ArenaAllocator = undefined,
pp: Preprocessor = undefined,
fn init(t: *TestPP, files: []const [2][]const u8, main: []const u8, opts: Options) !void {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -189,8 +189,6 @@ const Pass = struct {
if (info.done) return;
info.done = true;
const f = p.m.functions.items[fi];
// (Inlined everywhere: not emitted.)
if (f.dead) return;
// Callees first: their returns may be resources.
for (f.insts.items) |inst| if (inst.op == .call) try p.function(inst.op.call.func);
@ -211,10 +209,7 @@ const Pass = struct {
const n_old = f.insts.items.len;
const ret_holds = holdsResources(p.t, f.ret) or isOpaque(p.t, f.ret);
// Definitions before uses: inlining leaves a call's continuation
// ahead of the callee's blocks.
for (try reversePostorder(p.a, f)) |bi| {
const blk = &f.blocks.items[bi];
for (f.blocks.items, 0..) |*blk, bi| {
var out: std.ArrayList(Ref) = .empty;
for (blk.insts.items) |r| {
const old = f.insts.items[r.index()];
@ -426,6 +421,7 @@ const Pass = struct {
.@"switch" => |sw| blk.term = .{ .@"switch" = .{ .value = mp.map(sw.value), .default = sw.default, .cases = sw.cases } },
else => {},
}
_ = bi;
}
_ = n_old;
// What each out / inout resource holds when the function returns:
@ -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).
pub fn run(a: Allocator, m: *ir.Module, diags: *diag.Diagnostics) Error!void {
var any = false;

View File

@ -28,7 +28,6 @@
//! and fails its job.
const std = @import("std");
const BumpArena = @import("zdxc").BumpArena;
const Io = std.Io;
const Allocator = std.mem.Allocator;
const FileSystem = @import("zdxc").front.source.FileSystem;
@ -239,7 +238,7 @@ const Batch = struct {
/// jobs ahead of the compiles.
fn read(b: *Batch) void {
const gpa = std.heap.smp_allocator;
var arena: BumpArena = .init(gpa);
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
for (b.jobs, b.sources, 0..) |args, *s, i| {
while (true) {
@ -304,7 +303,7 @@ const Batch = struct {
fn work(b: *Batch) void {
const gpa = std.heap.smp_allocator;
var arena: BumpArena = .init(gpa);
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
while (true) {
const i = b.next.fetchAdd(1, .monotonic);

View File

@ -1,10 +1,8 @@
//! 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 options = @import("options.zig");
pub const compile = @import("compile.zig");
pub const stats = @import("stats.zig");
pub const BumpArena = @import("BumpArena.zig");
pub const Diagnostics = diag.Diagnostics;
pub const front = struct {

View File

@ -112,37 +112,6 @@ pub const Db = struct {
pub const Resolved = struct { ret: TypeId, index: u16 = 0, params: []const TypeId = &.{}, ok: bool = false };
pub fn resolve(db: *const Db, sema: anytype, loc: source.Loc, ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) !Resolved {
// The same call (name, object, explicit type, argument types and
// lvalues) resolves the same way: matched once per compile.
var key_buf: [256]u8 = undefined;
var key: std.ArrayList(u8) = .initBuffer(&key_buf);
const keyed = memoKey(&key, ns, name, object, args, explicit);
if (keyed) if (sema.intrinsic_memo.get(key.items)) |r| return r;
const reported = sema.diags.list.items.len;
const r = try db.resolveUncached(sema, loc, ns, name, object, args, explicit);
// (Not one that reported something: a repeat reports it again.)
if (keyed and r.ok and sema.diags.list.items.len == reported) try sema.intrinsic_memo.put(sema.arena, try sema.arena.dupe(u8, key.items), r);
return r;
}
/// The memo key of a call; false if it does not fit.
fn memoKey(key: *std.ArrayList(u8), ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) bool {
const fixed = ns.len + name.len + 2 + 2 * @sizeOf(TypeId) + args.len * (@sizeOf(TypeId) + 1);
if (fixed > key.capacity) return false;
key.appendSliceAssumeCapacity(ns);
key.appendAssumeCapacity(0);
key.appendSliceAssumeCapacity(name);
key.appendAssumeCapacity(0);
key.appendSliceAssumeCapacity(std.mem.asBytes(&@as(TypeId, object orelse std.math.maxInt(TypeId))));
key.appendSliceAssumeCapacity(std.mem.asBytes(&@as(TypeId, explicit orelse std.math.maxInt(TypeId))));
for (args) |a| {
key.appendSliceAssumeCapacity(std.mem.asBytes(&a.ty));
key.appendAssumeCapacity(@intFromBool(a.lvalue));
}
return true;
}
fn resolveUncached(db: *const Db, sema: anytype, loc: source.Loc, ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) !Resolved {
const cands = try db.candidates(sema.arena, ns, name);
if (cands.len == 0) {
if (object) |o| {
@ -197,16 +166,6 @@ const Bindings = struct {
return null;
}
/// Bind `name` to `v` unless it is bound to a smaller value.
fn lower(b: *Bindings, name: []const u8, v: u16) void {
if (std.fmt.parseInt(u16, name, 10)) |_| return else |_| {}
for (b.names[0..b.n], b.values[0..b.n]) |k, *old| if (std.mem.eql(u8, k, name)) {
old.* = @min(old.*, v);
return;
};
_ = b.bind(name, v);
}
/// Bind or check; false on conflict.
fn bind(b: *Bindings, name: []const u8, v: u16) bool {
if (b.get(name)) |old| return old == v;
@ -231,7 +190,6 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
.resource => |r| r.elem,
.stream => |s| s.elem,
.patch => |p| p.elem,
.node => |x| x.elem,
else => TypeTable.error_type,
} else TypeTable.error_type;
@ -264,66 +222,12 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
}
var bindings: Bindings = .{};
// A vector size (`c` of `numeric<c>`) shared by several arguments takes
// the widest of them, scalars splatting to it, as in dxc: `dot(1, v)`
// is a dot product of v's size, not v truncated to a scalar.
{
var syms: [8][]const u8 = undefined;
var widest: [8]u16 = undefined;
var ok: [8]bool = undefined;
var ns: usize = 0;
for (args[0..it.params.len], 1..) |a, i| {
const ls = if (specs[i].dims.len > 0) specs[i] else specs[layout_group[i]];
if (ls.any_layout or ls.dims.len != 1) continue;
const sym = ls.dims[0];
if (std.fmt.parseInt(u16, sym, 10)) |_| continue else |_| {}
const sh = t.shape(a.ty) orelse continue;
const len: u16 = switch (sh.kind) {
.scalar => 1,
.vector => sh.cols,
else => continue,
};
const k = for (syms[0..ns], 0..) |s, j| {
if (std.mem.eql(u8, s, sym)) break j;
} else blk: {
if (ns == syms.len) break :blk null;
syms[ns] = sym;
widest[ns] = len;
ok[ns] = true;
ns += 1;
break :blk ns - 1;
} orelse continue;
// (Vectors of two different sizes: left to the usual binding,
// which converts to the first.)
if (len != 1 and widest[k] != 1 and len != widest[k]) ok[k] = false;
widest[k] = @max(widest[k], len);
}
for (syms[0..ns], widest[0..ns], ok[0..ns]) |s, w, good| if (good and w > 1) {
_ = bindings.bind(s, w);
};
}
for (args[0..it.params.len], 1..) |a, i| {
// (Also arguments whose layout links to a `<>` one.)
if (!specs[i].any_layout and !specs[layout_group[i]].any_layout) continue;
const sh = t.shape(a.ty) orelse continue;
if (bindings.any_shape == null or sh.count() > bindings.any_shape.?.count()) bindings.any_shape = sh;
}
// A dimension shared by several arguments (`dot(numeric<c>,
// numeric<c>)`, mul's `numeric<r, c>` and `numeric<c>`) is the
// smallest one: dxc truncates the larger arguments (with a warning).
// Scalars splat and do not bind it.
for (args[0..it.params.len], 1..) |a, i| {
const ls = if (specs[i].dims.len > 0) specs[i] else specs[layout_group[i]];
const sh = t.shape(a.ty) orelse continue;
switch (ls.dims.len) {
1 => if (sh.kind == .vector) bindings.lower(ls.dims[0], sh.cols),
2 => if (sh.kind == .matrix) {
bindings.lower(ls.dims[0], sh.rows);
bindings.lower(ls.dims[1], sh.cols);
},
else => {},
}
}
var sum: u32 = 0;
var worst: u32 = 0;
const out_params = try sema.arena.alloc(bool, args.len);
@ -386,12 +290,6 @@ fn paramType(
// Non-numeric classes.
const base = if (cs.special == .none) cs.base else s.base;
// NodeOutput's Get{Thread,Group}NodeOutputRecords: records of the
// output's record type.
if (i == 0 and obj_elem != TypeTable.error_type) {
const records: ?types.NodeKind = if (std.mem.eql(u8, base, "ThreadNodeOutputRecords")) .thread_output_records else if (std.mem.eql(u8, base, "GroupNodeOutputRecords")) .group_output_records else null;
if (records) |k| return try t.intern(.{ .node = .{ .kind = k, .elem = obj_elem } });
}
if (!std.mem.eql(u8, base, "void") and !isNumericClass(base)) {
// Objects (samplers are checked) and classes zdxc does not model
// (HitObject, node records, LinAlg...): unconstrained.

View File

@ -89,9 +89,6 @@ pub const Resolution = union(enum) {
/// A bitfield member (`this_bitfield`: named without `this.`).
bitfield: types.Bitfield,
this_bitfield: types.Bitfield,
/// A node object's record: `Get()`, `Get(i)` or `[i]` (lowered as an
/// element of the object).
node_record,
};
pub const Param = struct {
@ -99,10 +96,6 @@ pub const Param = struct {
type: TypeId,
dir: enum { in, out, inout },
has_default: bool,
/// A template instance's default argument that does not convert to
/// the parameter's type: an error only where a call uses it (C++
/// instantiates default arguments on use).
bad_default: bool = false,
/// `groupshared` parameter (SM 6.8 groupshared arguments).
groupshared: bool = false,
};
@ -226,8 +219,6 @@ pub const Sema = struct {
loop_depth: u32 = 0,
switch_depth: u32 = 0,
intrinsic_db: *const intrinsics.Db,
/// Intrinsic calls resolved so far (see Db.resolve).
intrinsic_memo: std.StringHashMapUnmanaged(intrinsics.Db.Resolved) = .empty,
enum_scopes: std.AutoHashMapUnmanaged(*types.EnumInfo, *Scope) = .empty,
/// Where each template was declared (its names resolve from there).
template_scopes: std.AutoHashMapUnmanaged(*const ast.Decl, *Scope) = .empty,
@ -947,26 +938,13 @@ pub const Sema = struct {
}
fn lookup(s: *Sema, name: []const u8) ?Symbol {
// (The name hashed once, for every scope out to the global one.)
const key: Prehashed = .{ .h = std.hash_map.hashString(name) };
var sc: ?*Scope = s.scope;
while (sc) |c| : (sc = c.parent) {
if (c.syms.getAdapted(name, key)) |sym| return sym;
if (c.syms.get(name)) |sym| return sym;
}
return null;
}
/// A string hash map key context with the hash already worked out.
const Prehashed = struct {
h: u64,
pub fn hash(k: Prehashed, _: []const u8) u64 {
return k.h;
}
pub fn eql(_: Prehashed, a: []const u8, b: []const u8) bool {
return std.mem.eql(u8, a, b);
}
};
/// Resolve a possibly qualified name.
fn lookupName(s: *Sema, n: ast.Name) ?Symbol {
return s.lookupNameInst(n) catch null;
@ -1359,18 +1337,6 @@ pub const Sema = struct {
// Any other builtin object (RayQuery, node records, vk:: types...).
// vk::ext_result_id<T>: a T (an inline instruction's result).
if (eql(n, "ext_result_id") and args.len == 1) return try s.typeArg(args[0]) orelse TypeTable.error_type;
// Work graph node objects: their record type.
if (types.NodeKind.named(n)) |kind| {
var elem: TypeId = TypeTable.void_type;
if (kind.templated()) {
if (args.len == 0) {
s.err(t.loc, "'{s}' requires a record type template argument", .{n});
return TypeTable.error_type;
}
elem = try s.typeArg(args[0]) orelse return TypeTable.error_type;
}
return s.types.intern(.{ .node = .{ .kind = kind, .elem = elem } });
}
if (isOtherBuiltinObject(n)) {
var elem: TypeId = TypeTable.void_type;
if (eql(n, "RayQuery")) {
@ -1567,15 +1533,6 @@ pub const Sema = struct {
// ------------------------------------------------------------------
// Constant evaluation (array sizes, case labels, template arguments)
/// Whether struct `info` was declared with attribute `name` (any case).
pub fn structHasAttr(s: *const Sema, info: *const types.StructInfo, name: []const u8) bool {
_ = s;
const ss: *const StructSema = @ptrCast(@alignCast(info.sema orelse return false));
if (ss.decl.kind != .@"struct") return false;
for (ss.decl.kind.@"struct".attrs) |a| if (std.ascii.eqlIgnoreCase(a.name, name)) return true;
return false;
}
pub fn evalInt(s: *Sema, e: *const ast.Expr) ?i64 {
return switch (s.evalConst(e) orelse return null) {
.int => |v| v,
@ -2194,13 +2151,6 @@ pub const Sema = struct {
if (last_shader) |kept| {
if (!eql(kept, stage)) s.err(a.loc, "shader attribute type '{s}' conflicts with shader attribute type '{s}'", .{ stage, kept });
} else last_shader = stage;
} else if (std.ascii.eqlIgnoreCase(a.name, "nodelaunch") and a.args.len == 1 and a.args[0].kind == .string_lit) {
// (Exactly these: dxc compares case-sensitively.)
const lit = a.args[0].kind.string_lit;
const v = if (lit.len >= 2) lit[1 .. lit.len - 1] else lit;
if (!eql(v, "broadcasting") and !eql(v, "coalescing") and !eql(v, "thread")) {
s.err(a.args[0].loc, "attribute 'NodeLaunch' must have one of these values: broadcasting,coalescing,thread", .{});
}
} else if (std.ascii.eqlIgnoreCase(a.name, "wavesize")) {
if (last_wavesize) |kept| {
var same = kept.args.len == a.args.len;
@ -2525,16 +2475,7 @@ pub const Sema = struct {
.has_default = p.init != null,
.groupshared = p.quals.groupshared,
};
if (p.init) |init_e| {
if (s.instance_depth > 0) {
const m = s.diags.mark();
_ = try s.checkInitializer(pt, init_e);
if (s.diags.error_count != m.errors) {
s.diags.rollback(m);
out.bad_default = true;
}
} else _ = try s.checkInitializer(pt, init_e);
}
if (p.init) |init_e| _ = try s.checkInitializer(pt, init_e);
}
const func = try s.arena.create(Function);
func.* = .{ .name = name, .decl = f, .loc = d.loc, .ret = ret, .params = params, .defined = f.body != null, .owner = owner };
@ -3598,17 +3539,6 @@ pub const Sema = struct {
return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } };
},
.stream, .patch => return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } },
.node => |x| {
// Get: the record (records objects); the rest from the
// intrinsics table.
const known = (eql(name, "Get") and x.kind.hasRecords()) or
if (methodNamespace(s.types.get(b.ty))) |ns| s.intrinsic_db.hasMethod(ns, name) else false;
if (!known) {
s.err(name_loc, "no member named '{s}' in '{s}'", .{ name, s.typeName(b.ty) });
return err_typed;
}
return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } };
},
else => {
s.err(name_loc, "member reference base type '{s}' is not a structure", .{s.typeName(b.ty)});
return err_typed;
@ -3652,16 +3582,6 @@ pub const Sema = struct {
};
return .{ .ty = try s.types.vector(m.elem, m.cols), .lvalue = b.lvalue, .read_only = b.read_only };
},
.node => |x| {
// Records of a records array; an output of an outputs array.
if (x.kind.isArray()) {
s.record(e, .node_record);
return .{ .ty = x.elem, .lvalue = true, .read_only = !x.kind.writable() };
}
if (x.kind.outputElement()) |k| return rvalue(try s.types.intern(.{ .node = .{ .kind = k, .elem = x.elem } }));
s.err(e.loc, "type '{s}' does not provide a subscript operator", .{s.typeName(b.ty)});
return err_typed;
},
.resource => |r| {
if (r.kind.indexDims() == 0 or r.elem == TypeTable.void_type) {
if (r.kind == .other) return err_typed;
@ -3789,25 +3709,6 @@ pub const Sema = struct {
if (sym != .functions) return err_typed;
return rvalue(s.resolveUserCall(e, sym.functions, arg_types, callee));
},
.node => |x| if (eql(m.name, "Get")) {
// The record (`Get(i)`: of several).
const most: usize = if (x.kind.isArray()) 1 else 0;
if (arg_types.len > most) {
s.err(e.loc, "too many arguments to function call, expected at most {d}, have {d}", .{ most, arg_types.len });
return err_typed;
}
if (arg_types.len == 1 and s.conversionCost(arg_types[0].ty, try s.types.scalar(.uint)) == null) {
s.err(e.loc, "no matching member function for call to 'Get'", .{});
return err_typed;
}
s.record(e, .node_record);
return .{ .ty = x.elem, .lvalue = true, .read_only = !x.kind.writable() };
} else {
const ns = methodNamespace(s.types.get(m.object)) orelse return err_typed;
const r = try s.intrinsic_db.resolve(s, e.loc, ns, m.name, m.object, arg_types, null);
if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params, .object = m.object } });
return rvalue(r.ret);
},
else => {
var explicit: ?TypeId = null;
if (template_args.len > 0) explicit = try s.typeArg(template_args[0]);
@ -3856,17 +3757,7 @@ pub const Sema = struct {
var explicit: ?TypeId = null;
if (template_args.len > 0) explicit = try s.typeArg(template_args[0]);
const r = try s.intrinsic_db.resolve(s, e.loc, if (s.opts.spirv and isVkQualified(callee)) "VkIntrinsics" else "Intrinsics", name, null, arg_types, explicit);
if (r.ok) {
s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } });
// `dot(float4, float3)`: the longer argument is truncated.
for (arg_types, r.params[0..@min(arg_types.len, r.params.len)], 0..) |a, pt, i| {
const as = s.types.shape(a.ty) orelse continue;
const ps = s.types.shape(pt) orelse continue;
if (as.kind == .scalar or ps.kind == .scalar or (ps.rows >= as.rows and ps.cols >= as.cols)) continue;
const loc = if (e.kind == .call and i < e.kind.call.args.len) startLoc(e.kind.call.args[i]) else a.loc;
s.warn(loc, "conversion", "implicit truncation of vector type", .{});
}
}
if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } });
return rvalue(r.ret);
}
@ -3920,10 +3811,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"});
}
}
for (f.params[@min(args.len, f.params.len)..]) |p| if (p.bad_default) {
s.err(callee.loc, "cannot initialize a parameter of type '{s}' with its default argument", .{s.typeName(p.type)});
return TypeTable.error_type;
};
if (s.current_fn) |caller| caller.callees.append(s.arena, f) catch {};
s.record(e, .{ .function = f });
s.ensureBody(f) catch {};
@ -4165,9 +4052,6 @@ pub fn parseIntLiteral(text: []const u8) ?i64 {
if (digits.len > 2 and digits[0] == '0' and (digits[1] == 'x' or digits[1] == 'X')) {
base = 16;
body = digits[2..];
} else if (isBinaryLiteral(digits)) {
base = 2;
body = digits[2..];
} else if (digits.len > 1 and digits[0] == '0') {
base = 8;
body = digits[1..];
@ -4187,11 +4071,6 @@ pub fn parseFloatLiteral(text: []const u8) ?f64 {
/// dxc's `.#INF`): where the suffix starts and whether it is floating.
fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = false } {
var i: usize = 0;
if (isBinaryLiteral(text)) {
i = 2;
while (i < text.len and (text[i] == '0' or text[i] == '1')) i += 1;
return .{ .end = i, .float = false };
}
const hex = text.len > 1 and text[0] == '0' and (text[1] == 'x' or text[1] == 'X');
if (hex) i = 2;
const isDigit = struct {
@ -4220,24 +4099,6 @@ fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = f
return .{ .end = i, .float = float };
}
/// `0b101`: a binary integer literal (clang accepts them in HLSL).
/// Where an expression's text starts (clang's getBeginLoc): `i` in `i.T`.
fn startLoc(e: *const ast.Expr) Loc {
return switch (e.kind) {
.member => |m| startLoc(m.base),
.index => |x| startLoc(x.base),
.binary => |b| startLoc(b.lhs),
.assign => |b| startLoc(b.lhs),
.conditional => |c| startLoc(c.cond),
.call => |c| startLoc(c.callee),
else => e.loc,
};
}
fn isBinaryLiteral(text: []const u8) bool {
return text.len > 2 and text[0] == '0' and (text[1] == 'b' or text[1] == 'B') and (text[2] == '0' or text[2] == '1');
}
/// `f16` / `f32` / `f64` (any case) at the end of a float literal.
fn fixedFloatSuffix(text: []const u8) ?[]const u8 {
if (text.len < 4) return null;
@ -4452,15 +4313,6 @@ fn methodNamespace(t: types.Type) ?[]const u8 {
.constant_buffer, .texture_buffer, .raytracing_acceleration_structure => null,
.other => if (std.mem.eql(u8, r.name, "RayQuery")) "RayQueryMethods" else if (std.mem.eql(u8, r.name, "SubpassInput")) "VkSubpassInputMethods" else if (std.mem.eql(u8, r.name, "SubpassInputMS")) "VkSubpassInputMSMethods" else null,
},
.node => |x| switch (x.kind) {
.empty_input => "EmptyNodeInputMethods",
.rw_dispatch_input => "RWDispatchNodeInputRecordMethods",
.group_input, .rw_group_input => "GroupNodeInputRecordsMethods",
.output => "NodeOutputMethods",
.empty_output => "EmptyNodeOutputMethods",
.thread_output_records, .group_output_records => "GroupOrThreadNodeOutputRecordsMethods",
else => null,
},
else => null,
};
}

View File

@ -527,110 +527,6 @@ pub const Type = union(enum) {
/// `__builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(c, m, n, use,
/// scope)]]` (SM 6.10): an opaque matrix handle.
linalg: LinAlgMatrix,
/// A work graph node input, output or output record object
/// (`DispatchNodeInputRecord<T>`, `NodeOutput<T>`, ...): `elem` is the
/// record type (void for the empty ones).
node: struct { kind: NodeKind, elem: TypeId },
};
/// Work graph node object types, as DXC's NodeIOKind.
pub const NodeKind = enum {
dispatch_input,
rw_dispatch_input,
group_input,
rw_group_input,
thread_input,
rw_thread_input,
empty_input,
output,
output_array,
empty_output,
empty_output_array,
thread_output_records,
group_output_records,
pub const names = [_]struct { []const u8, NodeKind }{
.{ "DispatchNodeInputRecord", .dispatch_input }, .{ "RWDispatchNodeInputRecord", .rw_dispatch_input },
.{ "GroupNodeInputRecords", .group_input }, .{ "RWGroupNodeInputRecords", .rw_group_input },
.{ "ThreadNodeInputRecord", .thread_input }, .{ "RWThreadNodeInputRecord", .rw_thread_input },
.{ "EmptyNodeInput", .empty_input }, .{ "NodeOutput", .output },
.{ "NodeOutputArray", .output_array }, .{ "EmptyNodeOutput", .empty_output },
.{ "EmptyNodeOutputArray", .empty_output_array }, .{ "ThreadNodeOutputRecords", .thread_output_records },
.{ "GroupNodeOutputRecords", .group_output_records },
};
pub fn named(n: []const u8) ?NodeKind {
for (names) |e| if (std.mem.eql(u8, e[0], n)) return e[1];
return null;
}
pub fn name(k: NodeKind) []const u8 {
for (names) |e| if (e[1] == k) return e[0];
unreachable;
}
/// NodeIOFlags: input 0x1, output 0x2, read-write 0x4, empty 0x8,
/// array 0x10; record granularity thread 0x20, group 0x40, dispatch
/// 0x60.
pub fn ioFlags(k: NodeKind) u32 {
return switch (k) {
.dispatch_input => 0x61,
.rw_dispatch_input => 0x65,
.group_input => 0x41,
.rw_group_input => 0x45,
.thread_input => 0x21,
.rw_thread_input => 0x25,
.empty_input => 0x9,
.output => 0x6,
.output_array => 0x16,
.empty_output => 0xA,
.empty_output_array => 0x1A,
.thread_output_records => 0x26,
.group_output_records => 0x46,
};
}
pub fn isInput(k: NodeKind) bool {
return k.ioFlags() & 1 != 0;
}
/// Objects holding records (Get and, for the group ones, indexing).
pub fn hasRecords(k: NodeKind) bool {
return switch (k) {
.dispatch_input, .rw_dispatch_input, .group_input, .rw_group_input, .thread_input, .rw_thread_input, .thread_output_records, .group_output_records => true,
else => false,
};
}
/// Several records: `Get(i)` and `[i]` (dxc's IsArray).
pub fn isArray(k: NodeKind) bool {
return switch (k) {
.group_input, .rw_group_input, .thread_output_records, .group_output_records => true,
else => false,
};
}
/// An array of outputs: `[i]` is one.
pub fn outputElement(k: NodeKind) ?NodeKind {
return switch (k) {
.output_array => .output,
.empty_output_array => .empty_output,
else => null,
};
}
/// Records that may be written.
pub fn writable(k: NodeKind) bool {
return k.ioFlags() & 4 != 0 and k.hasRecords();
}
/// Whether the type takes a record type argument.
pub fn templated(k: NodeKind) bool {
return switch (k) {
.empty_input, .empty_output, .empty_output_array => false,
else => true,
};
}
};
pub const LinAlgMatrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u32 };
@ -639,9 +535,7 @@ pub const LinAlgMatrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u3
pub const TypeTable = struct {
gpa: Allocator,
types: std.ArrayList(Type) = .empty,
map: std.HashMapUnmanaged(Key, TypeId, KeyContext, std.hash_map.default_max_load_percentage) = .empty,
/// scalar's results.
scalars: [@typeInfo(Scalar).@"enum".field_names.len]TypeId = @splat(std.math.maxInt(TypeId)),
map: std.AutoHashMapUnmanaged(Key, TypeId) = .empty,
pub const error_type: TypeId = 0;
pub const void_type: TypeId = 1;
@ -649,23 +543,6 @@ pub const TypeTable = struct {
/// Hashable identity of structural types.
const Key = struct { tag: u8, a: u64, b: u64 };
/// Hashes a Key's words (it has padding, which the automatic context
/// hashes around field by field).
const KeyContext = struct {
fn mix(x: u64) u64 {
var z = x;
z = (z ^ (z >> 30)) *% 0xbf58476d1ce4e5b9;
z = (z ^ (z >> 27)) *% 0x94d049bb133111eb;
return z ^ (z >> 31);
}
pub fn hash(_: KeyContext, k: Key) u64 {
return mix(k.a ^ mix(k.b ^ @as(u64, k.tag) << 56));
}
pub fn eql(_: KeyContext, x: Key, y: Key) bool {
return x.tag == y.tag and x.a == y.a and x.b == y.b;
}
};
pub fn init(gpa: Allocator) !TypeTable {
var t: TypeTable = .{ .gpa = gpa };
try t.types.append(gpa, .@"error");
@ -701,7 +578,6 @@ pub const TypeTable = struct {
.texture_view => |v| .{ .tag = 14, .a = v.texture, .b = @backingInt(v.kind) },
.linalg => |x| .{ .tag = 16, .a = (@as(u64, x.comp) << 32) | x.m, .b = (@as(u64, x.n) << 32) | (@as(u64, x.use) << 16) | x.scope },
.spirv => |x| .{ .tag = 15, .a = (@as(u64, x.opcode) << 32) | x.size, .b = std.hash.Wyhash.hash(x.alignment, std.mem.sliceAsBytes(x.operands)) },
.node => |x| .{ .tag = 17, .a = @backingInt(x.kind), .b = x.elem },
};
}
@ -715,9 +591,7 @@ pub const TypeTable = struct {
}
pub fn scalar(t: *TypeTable, s: Scalar) !TypeId {
const k = @backingInt(s);
if (t.scalars[k] == std.math.maxInt(TypeId)) t.scalars[k] = try t.intern(.{ .scalar = s });
return t.scalars[k];
return t.intern(.{ .scalar = s });
}
/// `len == 1` vectors are kept distinct from scalars (float1 != float).
@ -883,7 +757,6 @@ pub const TypeTable = struct {
.triangle => "TriangleStream",
}, try t.format(gpa, s.elem), ""),
.patch => |p| templateName(gpa, if (p.output) "OutputPatch" else "InputPatch", try t.format(gpa, p.elem), try std.fmt.allocPrint(gpa, ", {d}", .{p.count})),
.node => |x| if (x.kind.templated()) templateName(gpa, x.kind.name(), try t.format(gpa, x.elem), "") else x.kind.name(),
.descriptor_heap => |h| if (h.sampler) "SamplerDescriptorHeap" else "ResourceDescriptorHeap",
.dynamic_resource => "<dynamic resource>",
.texture_view => |v| std.fmt.allocPrint(gpa, "{s}::{s}", .{ try t.format(gpa, v.texture), switch (v.kind) {

View File

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

View File

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

View File

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