Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3fb0214c4d | ||
|
|
f72fb1f8cc | ||
|
|
41b5c00628 | ||
|
|
611fc150f3 | ||
|
|
5e3d47ab5f | ||
|
|
6454f15dd1 | ||
|
|
dfab1aefe5 | ||
|
|
509a0445dd | ||
|
|
60da11a198 | ||
|
|
0909e33acd | ||
|
|
7921e6f9c5 | ||
|
|
6bd03a44ff | ||
|
|
4cb99e5476 | ||
|
|
8e43c2b378 | ||
|
|
98c5fdeec0 | ||
|
|
410e968963 | ||
|
|
bd18274cdc | ||
|
|
fa2cafab38 | ||
|
|
3d407b9093 | ||
|
|
2a2f1ad709 | ||
|
|
5c6b4ee7b9 | ||
|
|
d1de9152a0 | ||
|
|
8eb8bf24a4 | ||
|
|
7fb6a9f878 | ||
|
|
daac1b4668 | ||
|
|
c885ed06a2 | ||
|
|
6f4f4c9cb7 | ||
|
|
ebe455c8ea | ||
|
|
39956661b4 | ||
|
|
17a6dbf636 | ||
|
|
300bcbaf24 | ||
|
|
7417dcf6ae | ||
|
|
5ee3854568 | ||
|
|
72319359da | ||
|
|
cd43ef4610 | ||
|
|
9f0288b60f | ||
|
|
321a82ab6e | ||
|
|
570ab22464 | ||
|
|
82004ab6e4 | ||
|
|
6031c3e35c | ||
|
|
c58823f2a9 | ||
|
|
f52d16dff5 | ||
|
|
7d80c7bb2a | ||
|
|
fa29de923b | ||
|
|
4787a8d35c | ||
|
|
4b70f4db7d | ||
|
|
bb8e9b1b92 | ||
|
|
c041afb6de | ||
|
|
64de51ca06 | ||
|
|
6a2e04fca0 | ||
|
|
d6cf04323c | ||
|
|
777116fd67 | ||
|
|
39c99ca6ff | ||
|
|
a097975fae | ||
|
|
2ad2bc45c2 | ||
|
|
310ef0f841 | ||
|
|
3e6c195401 | ||
|
|
b82a57df11 | ||
|
|
9c343e3f84 | ||
|
|
3f8c4b99bf | ||
|
|
d47761f38c | ||
|
|
399160b629 | ||
|
|
5ec1bf02f5 | ||
|
|
4499383fb7 | ||
|
|
ccc44bd825 | ||
|
|
a595d4400d | ||
|
|
07533fba59 | ||
|
|
fd895bcf5e | ||
|
|
95187576c9 | ||
|
|
f82b47982a | ||
|
|
1866499455 | ||
|
|
8c6605ef09 | ||
|
|
8a64a61a84 | ||
|
|
f754f6441c | ||
|
|
390c94b85b | ||
|
|
a1fcbe9bef | ||
|
|
a200101561 | ||
|
|
025e29c5c9 | ||
|
|
b605ffe25a | ||
|
|
96ac611dd0 | ||
|
|
f706bb19bb | ||
|
|
6920f1551f | ||
|
|
26a5e035fa | ||
|
|
67c4681f0a | ||
|
|
d1ae0da903 | ||
|
|
4666d3f938 | ||
|
|
ff583fe0f0 | ||
|
|
bac564d64a | ||
|
|
9629368999 | ||
|
|
203800c091 | ||
|
|
ebf1c642be | ||
|
|
0fe03609a9 | ||
|
|
a007a9cb73 | ||
|
|
612bd6133a | ||
|
|
7e0000bd41 | ||
|
|
25b81f30ce | ||
|
|
e225a4fe6a | ||
|
|
dd829704b1 | ||
|
|
1f6cbf0775 | ||
|
|
856950ad5f | ||
|
|
5bf3eaa569 | ||
|
|
ac3116d543 | ||
|
|
b110b16a9a | ||
|
|
cceecbbe5d | ||
|
|
2523610f6d | ||
|
|
86db9c6295 | ||
|
|
c450e3a3f2 | ||
|
|
8133bd41ef | ||
|
|
1b27d10552 | ||
|
|
2a4f6ff0da | ||
|
|
1758248473 | ||
|
|
aa6998fcf4 | ||
|
|
adc26dac04 | ||
|
|
4c62f8b838 | ||
|
|
c3ef9fb291 | ||
|
|
a1ce537bb0 | ||
|
|
debc381ccb | ||
|
|
d9d8764d32 | ||
|
|
c2ef7933a6 | ||
|
|
9a5d17123e | ||
|
|
e597f6052e | ||
|
|
f314c9b6b6 | ||
|
|
7eac27ba16 | ||
|
|
527c3d0b18 | ||
|
|
0afcf938e0 | ||
|
|
f2ff55ad99 | ||
|
|
02c7847641 | ||
|
|
54aeaba518 | ||
|
|
d3f6874326 | ||
|
|
4ac82147c3 | ||
|
|
835fc9230c | ||
|
|
9acf8693d8 | ||
|
|
3bdd7c6b7f | ||
|
|
1b7608b82e | ||
|
|
b378ac14ad | ||
|
|
0983c2cebc | ||
|
|
94bab2bb5b | ||
|
|
dec3944830 | ||
|
|
f17d6915f2 | ||
|
|
5769bdf699 | ||
|
|
7ced8e858b | ||
|
|
6651443eab | ||
|
|
5130aaf56c | ||
|
|
62d90ff97d | ||
|
|
1eef0a811a | ||
|
|
7ad836764e | ||
|
|
3a5c775ad8 | ||
|
|
26a1e47854 | ||
|
|
122990b237 | ||
|
|
3116ceb59e | ||
|
|
b5b8167f18 | ||
|
|
51e4505dd2 | ||
|
|
920c86a10d | ||
|
|
2684af8d22 | ||
|
|
d0435e6b37 | ||
|
|
94dc864260 | ||
|
|
5db3d3c394 | ||
|
|
eb53af7dae | ||
|
|
3432c0ca26 | ||
|
|
b4d7ad82f8 | ||
|
|
7e56396c5c | ||
|
|
b6cc625a55 | ||
|
|
9f601753bf | ||
|
|
5462fe2ebf | ||
|
|
fc11f5cefb | ||
|
|
9a22b19d74 | ||
|
|
8818597892 | ||
|
|
86827bb4cd | ||
|
|
79267de637 | ||
|
|
ec96fe0b3f | ||
|
|
8e8e53bacd | ||
|
|
ca459aecd9 | ||
|
|
25a11628d4 | ||
|
|
34bd23fa4e | ||
|
|
be5b40432e | ||
|
|
81a0bca977 | ||
|
|
e9e57d940f | ||
|
|
d60a9c91fa | ||
|
|
f59690f087 | ||
|
|
80b8cca8bb | ||
|
|
a7f112ff48 | ||
|
|
7a2ed8ec3b | ||
|
|
5a2ba0a576 | ||
|
|
9432a11070 | ||
|
|
3a59682d86 | ||
|
|
2cafe84dc8 | ||
|
|
f442d706fe | ||
|
|
f7516d81d0 | ||
|
|
bc946f307e | ||
|
|
036cb7b5d2 | ||
|
|
379776191c | ||
|
|
ce42bdc0c1 | ||
|
|
e69f7143e9 | ||
|
|
80a44b3c4c | ||
|
|
31f4184827 | ||
|
|
3fec72ab5f | ||
|
|
9748087d91 | ||
|
|
e6fdd96421 | ||
|
|
68d845f49a | ||
|
|
10f603625a | ||
|
|
5f95fae22f | ||
|
|
10570c2e39 | ||
|
|
a4058c6011 | ||
|
|
0fdd5cdab1 | ||
|
|
244db56e5c | ||
|
|
400f4c3edd | ||
|
|
ef16754c17 | ||
|
|
0f1ed01d71 | ||
|
|
b63ebae04c | ||
|
|
d7146386a5 | ||
|
|
fed9bd0f95 | ||
|
|
0bb3f36178 | ||
|
|
797332dec6 | ||
|
|
91bca360c8 | ||
|
|
ac64565e50 | ||
|
|
e6756bf62c | ||
|
|
6205d2f20a | ||
|
|
30134bd9c1 | ||
|
|
1934aae05e | ||
|
|
55b0176800 | ||
|
|
13c2a22ae6 | ||
|
|
0eaed218e5 | ||
|
|
2806fb1cb5 | ||
|
|
d898d1d122 | ||
|
|
884ef80bdb | ||
|
|
177bcfd845 | ||
|
|
4f49aa9aff | ||
|
|
6669a95333 | ||
|
|
674412ede3 | ||
|
|
7f9c508814 | ||
|
|
ee671ab680 | ||
|
|
7e0695890c | ||
|
|
1269a28afd | ||
|
|
a1325927ad | ||
|
|
e0a05faa5e | ||
|
|
0c4465a461 | ||
|
|
05ced3662c | ||
|
|
343de87f21 | ||
|
|
93853cd5ee | ||
|
|
d1b30019b2 | ||
|
|
adcf0873b2 | ||
|
|
241d817fa2 | ||
|
|
c243baa6ae | ||
|
|
68dc0f8cac | ||
|
|
94e4fdcfc4 | ||
|
|
8489739d3f | ||
|
|
512ddb2e88 | ||
|
|
96ce8d50d6 | ||
|
|
45b74b4e31 | ||
|
|
e0f10da84b | ||
|
|
aa3e9452bf | ||
|
|
91af270734 | ||
|
|
4c5b7e8eec | ||
|
|
37f7455c4e | ||
|
|
7f17dcabeb | ||
|
|
e6f45f0d57 | ||
|
|
84f33e9b6a | ||
|
|
66bd467132 | ||
|
|
0422744e10 | ||
|
|
65084bf882 | ||
|
|
b488c2a322 | ||
|
|
680f746969 | ||
|
|
46b5935540 | ||
|
|
b8d9637711 | ||
|
|
fa65a3fbd9 | ||
|
|
3c905a61c1 | ||
|
|
478c74a9cf | ||
|
|
284fd5ae59 | ||
|
|
7899b2d32b | ||
|
|
bd243f9915 | ||
|
|
398bd43d9c | ||
|
|
c510c4c8ff | ||
|
|
d11ae9fe3b | ||
|
|
c4c853819a | ||
|
|
7fbc8152b0 | ||
|
|
3005017a2c | ||
|
|
e6f4ccecce | ||
|
|
c3b3028f18 | ||
|
|
386130b636 | ||
|
|
794a12f458 | ||
|
|
0b34cc8a11 | ||
|
|
c6768a4d60 | ||
|
|
ffef721f5e | ||
|
|
ba6290c771 | ||
|
|
0bf00c77db | ||
|
|
5a2ee505c0 | ||
|
|
08f85f5d15 | ||
|
|
d033f60448 | ||
|
|
3f69e9c5fd | ||
|
|
1ac1653faa | ||
|
|
b9b66c1b8a | ||
|
|
378e2870d3 | ||
|
|
4a488a44f3 | ||
|
|
970b7687db | ||
|
|
f662d6c53a | ||
|
|
d647525b07 | ||
|
|
5065f7a577 | ||
|
|
ceb9de7737 | ||
|
|
439dbcf10d | ||
|
|
84a89f4c8e | ||
|
|
52aad2d6cf | ||
|
|
2313b49cb0 | ||
|
|
bda3d67882 | ||
|
|
515449986e | ||
|
|
e0367fa9c5 | ||
|
|
03543b73fd | ||
|
|
255a96027a | ||
|
|
b88ab90c92 | ||
|
|
426c732928 | ||
|
|
13bb919632 | ||
|
|
d3feb8a34b | ||
|
|
6742ac54cc | ||
|
|
dd0aff6424 | ||
|
|
617dd0ede2 | ||
|
|
6d7ddadb72 | ||
|
|
83d541dc68 | ||
|
|
8cabdb9e64 | ||
|
|
7897145d25 | ||
|
|
bafbad6c8b | ||
|
|
22c756016b | ||
|
|
6a066abdb2 | ||
|
|
ebd19223fa | ||
|
|
ddd853e149 | ||
|
|
18fb5aeb6c | ||
|
|
ae16ed5112 | ||
|
|
225784c977 | ||
|
|
898f58a5fb | ||
|
|
a129921478 | ||
|
|
36e6caf964 | ||
|
|
e991274a2e | ||
|
|
1a97a1a571 | ||
|
|
d17c7aa1e0 | ||
|
|
96c23c7de6 | ||
|
|
900ed8f716 | ||
|
|
42dc1b0f41 | ||
|
|
444649ed6f | ||
|
|
1fd89e81cd | ||
|
|
8a3b727cfc | ||
|
|
888f39a992 | ||
|
|
fde5c44154 | ||
|
|
30b2374fed | ||
|
|
4389559ae6 | ||
|
|
848d11dd48 | ||
|
|
dd102f8a58 | ||
|
|
d2d33d3556 | ||
|
|
17677858b3 | ||
|
|
aea1e2adff | ||
|
|
1d071b6765 | ||
|
|
4001c4e8ac | ||
|
|
ab5f39b9f1 | ||
|
|
4fdd16d21e | ||
|
|
ad3877d9c3 | ||
|
|
118ec0ff46 | ||
|
|
6e3d216c68 | ||
|
|
feb984ce97 | ||
|
|
1ffc9365e4 | ||
|
|
af1121a9ce | ||
|
|
d01ed08bfc | ||
|
|
76b6bb454f | ||
|
|
97f5f43343 | ||
|
|
af087b47b8 | ||
|
|
16bd1edf6e | ||
|
|
ab7fe5a521 | ||
|
|
d1fabf4043 | ||
|
|
fdcd90072b | ||
|
|
572b50d000 | ||
|
|
f9f92b46db | ||
|
|
ee68a8b268 | ||
|
|
768495fcbd | ||
|
|
7acf793845 | ||
|
|
cc31776b37 | ||
|
|
30dc39b17a | ||
|
|
37de4b35bf | ||
|
|
0d8fb13db6 | ||
|
|
2b49d83b60 | ||
|
|
f7a0bafd91 | ||
|
|
c97860d964 | ||
|
|
93a15838fb | ||
|
|
680b1d5e26 | ||
|
|
5953b38977 | ||
|
|
11f94607f8 | ||
|
|
7441f9f5de | ||
|
|
5d60ef90d0 | ||
|
|
02e3478ea7 | ||
|
|
0c31c0b6b3 | ||
|
|
95ad997f0b | ||
|
|
f00a8d5b49 | ||
|
|
436d73cf3a | ||
|
|
8022b2326b | ||
|
|
a6cbf5b6d8 | ||
|
|
fe535abdf5 | ||
|
|
12c78dda4b | ||
|
|
d29b58d75b | ||
|
|
c9b088cb30 | ||
|
|
98f22ce6f8 | ||
|
|
6fc175170f | ||
|
|
b5958c162b | ||
|
|
de2e9f1a0d | ||
|
|
25cf857cfa | ||
|
|
ad6b02c83e | ||
|
|
77a7ef0459 | ||
|
|
699eb20c69 | ||
|
|
31d291f337 | ||
|
|
c0efdfd534 | ||
|
|
e9a0418423 | ||
|
|
787580628b | ||
|
|
7ac6643d04 | ||
|
|
db0bae5077 | ||
|
|
8f0bd37614 | ||
|
|
a86e6da41f | ||
|
|
e813c84737 | ||
|
|
c6bf5cbf5d | ||
|
|
a95fef8c10 | ||
|
|
f44e5afa81 | ||
|
|
73b77bd817 | ||
|
|
f0c9a610b8 | ||
|
|
b2ce9761ac | ||
|
|
b4e3fccd55 | ||
|
|
7910e60542 | ||
|
|
68477abbf0 | ||
|
|
68a0737e70 | ||
|
|
c1e3f08505 | ||
|
|
65cd4c7e1e | ||
|
|
94355db42d | ||
|
|
285b51e2e2 | ||
|
|
e76ebae7ae | ||
|
|
0ecdc85601 | ||
|
|
40212fc992 | ||
|
|
93a54f08db | ||
|
|
b1089b207c | ||
|
|
a7bb3c27b0 | ||
|
|
0e6e37935f | ||
|
|
6f69f0176b | ||
|
|
74e5d8f30b | ||
|
|
8e812f5da1 | ||
|
|
9436b8a7f5 | ||
|
|
eb42c5fb9d | ||
|
|
38f133cd31 | ||
|
|
931fed4c86 | ||
|
|
943c1a5bfc | ||
|
|
eb05cf68e4 | ||
|
|
fe3624fa97 | ||
|
|
c7b107d26f | ||
|
|
ad2952866f | ||
|
|
e41b61abee | ||
|
|
1f1abe72e7 | ||
|
|
f60e704d4c | ||
|
|
c43f2ba4e1 | ||
|
|
96f65225e6 | ||
|
|
e4fe9c0b6c | ||
|
|
43e743b081 | ||
|
|
9ad5f481ef | ||
|
|
46a099154a | ||
|
|
d9360880c3 | ||
|
|
efe3fabf71 | ||
|
|
490c107fda | ||
|
|
16b60d090f | ||
|
|
1a750826b7 | ||
|
|
cb0a762fd4 | ||
|
|
1d2a6f5d85 | ||
|
|
42da58fef1 | ||
|
|
761411435d | ||
|
|
f4a26ecc08 | ||
|
|
78d7eae3f8 | ||
|
|
6582e55feb | ||
|
|
7eceb25e21 | ||
|
|
f645a925bf | ||
|
|
0e9abf798d | ||
|
|
665fbbca60 | ||
|
|
65b890108e | ||
|
|
4d7fa2fd45 | ||
|
|
6031f41cb7 | ||
|
|
e36596732a | ||
|
|
2f22c43e22 | ||
|
|
4401df78e7 | ||
|
|
a0136b02b7 | ||
|
|
39ae6033ac | ||
|
|
9a453acd80 | ||
|
|
a4fb763b2e | ||
|
|
b721a53649 | ||
|
|
1078ba6ea4 | ||
|
|
b1c9dc5516 | ||
|
|
a7fcb8ab01 | ||
|
|
712f70a324 | ||
|
|
35e03697d4 | ||
|
|
34aba841ae | ||
|
|
f985be664e | ||
|
|
b0216fd4e1 | ||
|
|
bd85c5288f | ||
|
|
7fc35a9bff | ||
|
|
b390572374 | ||
|
|
37a64372a6 | ||
|
|
1cf12f8aa4 | ||
|
|
01ad5ebbc6 | ||
|
|
04fadbbce7 | ||
|
|
ab18ff0972 | ||
|
|
525ebb743b | ||
|
|
4e33fa2221 | ||
|
|
10e854af6b | ||
|
|
bb89cbe24b | ||
|
|
71c0eec79d | ||
|
|
d2db9d35fe | ||
|
|
0ac56bdebe | ||
|
|
78621014f3 | ||
|
|
4838ce9b2f | ||
|
|
126266c4a6 | ||
|
|
8d44256676 | ||
|
|
4dc2da6b09 | ||
|
|
61b1e5402a |
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# Byte-preservation fixtures deliberately contain trailing spaces.
|
||||
tests/fixtures/formatter/source.zi.in -whitespace
|
||||
@@ -0,0 +1,144 @@
|
||||
# Generated by waozixyz/gitea-ops scripts/test-ziran.py --emit from
|
||||
# .github/workflows/check.yml (Linux check job) for Build's Gitea runner.
|
||||
name: Build check
|
||||
on:
|
||||
# Prose alone cannot break a check. CHANGELOG.md is read by the version check.
|
||||
push:
|
||||
branches: [master]
|
||||
paths: ['**', '!**/*.md', CHANGELOG.md]
|
||||
pull_request:
|
||||
paths: ['**', '!**/*.md', CHANGELOG.md]
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
concurrency:
|
||||
group: check-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
jobs:
|
||||
check:
|
||||
name: check
|
||||
runs-on: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && 'build-native-ziran' || 'build-primary' }}
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
JOBS: 2
|
||||
BUILD_NATIVE: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && 'true' || 'false' }}
|
||||
steps:
|
||||
- name: Check out the exact Build commit
|
||||
id: native
|
||||
if: env.BUILD_NATIVE == 'true'
|
||||
run: gitea-native-build checkout
|
||||
- uses: actions/checkout@v4
|
||||
if: env.BUILD_NATIVE == 'false'
|
||||
# site_pages.sh marks std modules shipped in the latest v* tag.
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-go@v5
|
||||
if: env.BUILD_NATIVE == 'false'
|
||||
with:
|
||||
go-version: '1.25'
|
||||
cache: false
|
||||
# tests/zstd_go_cases.zi builds against this module with GOPROXY=off,
|
||||
# and the module itself requires Go 1.25.
|
||||
- name: Fetch the Go Zstandard module for the offline Go checks
|
||||
if: env.BUILD_NATIVE == 'false'
|
||||
run: cd "$RUNNER_TEMP" && go mod download github.com/klauspost/[email protected]
|
||||
- name: Install ripgrep, MinGW, Wine, Vorbis, ARMv7 tools and the private display for the test scripts
|
||||
if: env.BUILD_NATIVE == 'false'
|
||||
timeout-minutes: 5
|
||||
run: sh scripts/ci_packages.sh ccache ripgrep zip unzip gcc-mingw-w64-x86-64 wine wine64 xvfb xauth libsdl2-dev ffmpeg libvorbis-dev python3-markdown gcc-arm-linux-gnueabihf libc6-dev-armhf-cross qemu-user clang-18 lld-18
|
||||
# The emcc checks use the Emscripten the playground and the site use;
|
||||
# Ubuntu's emscripten package is 3.1.6, and its emcc is a symlink to a
|
||||
# wrapper that cannot run under its resolved name.
|
||||
- name: Set up Emscripten
|
||||
if: env.BUILD_NATIVE == 'false'
|
||||
uses: emscripten-core/setup-emsdk@v15
|
||||
with:
|
||||
version: '6.0.6'
|
||||
- name: Keep compile results between runs
|
||||
if: env.BUILD_NATIVE == 'false'
|
||||
uses: ./.github/actions/compile-cache
|
||||
with:
|
||||
key: check
|
||||
- name: Verify the cached native toolchain and Go modules
|
||||
if: env.BUILD_NATIVE == 'true' && steps.native.outputs.current == 'true'
|
||||
run: gitea-native-build run bash -ec 'emcc --version && go mod download github.com/klauspost/[email protected]'
|
||||
- name: Build the toolchain
|
||||
if: env.BUILD_NATIVE == 'false' || steps.native.outputs.current == 'true'
|
||||
run: |
|
||||
if [ "$BUILD_NATIVE" = true ]; then
|
||||
gitea-native-build run make
|
||||
else
|
||||
make
|
||||
fi
|
||||
- name: Run the language, backend, and portable runtime checks
|
||||
if: env.BUILD_NATIVE == 'false' || steps.native.outputs.current == 'true'
|
||||
run: |
|
||||
if [ "$BUILD_NATIVE" = true ]; then
|
||||
gitea-native-build run env -u DISPLAY -u WAYLAND_DISPLAY WINDOWS_REQUIRED=1 ARM_REQUIRED=1 WASM_REQUIRED=1 ZIRAN_WASM_CC=clang-18 make check CHECK_JOBS=2 </dev/null
|
||||
else
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY WINDOWS_REQUIRED=1 ARM_REQUIRED=1 WASM_REQUIRED=1 ZIRAN_WASM_CC=clang-18 make check CHECK_JOBS=2 </dev/null
|
||||
fi
|
||||
- name: Pack the tested Ziran toolchain
|
||||
id: toolchain
|
||||
if: github.server_url == 'https://git.waozi.xyz' && github.event_name == 'push' && github.ref == 'refs/heads/master' && (env.BUILD_NATIVE != 'true' || steps.native.outputs.current == 'true')
|
||||
env:
|
||||
SOURCE: ${{ steps.native.outputs.source || github.workspace }}
|
||||
run: |
|
||||
output="build/toolchains/$GITHUB_SHA"
|
||||
if [ "$BUILD_NATIVE" = true ]; then
|
||||
gitea-native-build run python3 scripts/toolchain_package.py pack "$GITHUB_SHA" "$output"
|
||||
else
|
||||
python3 scripts/toolchain_package.py pack "$GITHUB_SHA" "$output"
|
||||
fi
|
||||
printf 'directory=%s/%s\n' "$SOURCE" "$output" >> "$GITHUB_OUTPUT"
|
||||
- name: Keep the verified toolchain archive
|
||||
if: steps.toolchain.outputs.directory != ''
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: toolchain-${{ github.sha }}
|
||||
path: ${{ steps.toolchain.outputs.directory }}
|
||||
if-no-files-found: error
|
||||
- name: Publish the toolchain to Gitea Packages
|
||||
if: steps.toolchain.outputs.directory != ''
|
||||
env:
|
||||
SOURCE: ${{ steps.native.outputs.source || github.workspace }}
|
||||
OUTPUT: ${{ steps.toolchain.outputs.directory }}
|
||||
ZIRAN_TOOLCHAIN_PACKAGE_USER: ${{ secrets.ZIRAN_TOOLCHAIN_PACKAGE_USER }}
|
||||
ZIRAN_TOOLCHAIN_PACKAGE_TOKEN: ${{ secrets.ZIRAN_TOOLCHAIN_PACKAGE_TOKEN }}
|
||||
run: |
|
||||
if [ -z "$ZIRAN_TOOLCHAIN_PACKAGE_USER$ZIRAN_TOOLCHAIN_PACKAGE_TOKEN" ]; then
|
||||
echo "Gitea package writer is unavailable. The toolchain is in this run's artifacts."
|
||||
exit 0
|
||||
fi
|
||||
for descriptor in "$OUTPUT"/*.json; do
|
||||
python3 "$SOURCE/scripts/toolchain_package.py" publish "$GITHUB_SHA" "$descriptor"
|
||||
done
|
||||
- name: Show how much the compile cache saved
|
||||
if: always()
|
||||
run: |
|
||||
if [ "$BUILD_NATIVE" = true ]; then
|
||||
gitea-native-build run ccache --show-stats || true
|
||||
else
|
||||
ccache --show-stats || true
|
||||
fi
|
||||
- name: Keep complete check logs
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: check-logs
|
||||
path: ${{ steps.native.outputs.source || github.workspace }}/build/check-logs/
|
||||
|
||||
release:
|
||||
name: Publish a new Ziran version
|
||||
needs: check
|
||||
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
|
||||
runs-on: build-native-ziran
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Check out the tested Build commit
|
||||
run: /usr/local/libexec/gitea-native-build checkout
|
||||
- name: Publish the tested VERSION to Gitea
|
||||
env:
|
||||
ZIRAN_RELEASE_TOKEN: ${{ github.token }}
|
||||
run: /usr/local/libexec/gitea-native-build run python3 scripts/release_gitea.py
|
||||
@@ -0,0 +1,26 @@
|
||||
name: Quick Ziran build
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
quick:
|
||||
# Build's primary host slot. ccache is installed on the host.
|
||||
runs-on: build-primary
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: https://github.com/actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: ./.github/actions/compile-cache
|
||||
with:
|
||||
key: check
|
||||
- name: Compile and start Ziran
|
||||
run: |
|
||||
make JOBS=2 build/bin/ziran
|
||||
build/bin/ziran --version
|
||||
- name: Report compile cache savings
|
||||
if: always()
|
||||
run: ccache --show-stats
|
||||
@@ -1,11 +1,11 @@
|
||||
name: Set up Ziran
|
||||
description: >
|
||||
Check out the Ziran a project's ziran.lock pins with its compiler built, put
|
||||
its build/bin on PATH and optionally fetch the locked packages. The build
|
||||
tree is the Toolchains workflow's prebuilt archive for that commit, else
|
||||
this repository's cache, else a build here. Package checkouts are cached by
|
||||
the whole lock and start from the previous checkouts when it changes,
|
||||
keeping only the ones the lock uses.
|
||||
Set up the Ziran revision pinned by a project's ziran.lock, put its
|
||||
build/bin on PATH and optionally fetch the locked packages. The build
|
||||
tree comes from this repository's exact verified cache, the Toolchains
|
||||
workflow's prebuilt archive for that commit, or a build here. Package
|
||||
checkouts are cached by the whole lock and start from the previous checkouts
|
||||
when it changes, keeping only the ones the lock uses.
|
||||
|
||||
inputs:
|
||||
project:
|
||||
@@ -25,6 +25,12 @@ inputs:
|
||||
Ubuntu packages to install, separated by spaces or lines, from the
|
||||
canonical Ubuntu archive with time limits (scripts/ci_packages.sh).
|
||||
default: ''
|
||||
jobs:
|
||||
description: Make jobs (1–64), capped by the runner's JOBS allocation when set. Defaults to JOBS or 1.
|
||||
default: ''
|
||||
min-free-mib:
|
||||
description: Minimum available MiB at each destination (checkout, runner scratch, and requested package cache).
|
||||
default: '1024'
|
||||
recommends:
|
||||
description: Also install the packages' recommended packages.
|
||||
default: 'false'
|
||||
@@ -51,49 +57,90 @@ outputs:
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Resolve the Ziran commit
|
||||
- name: Resolve inputs and check available space
|
||||
id: resolve
|
||||
shell: bash
|
||||
env:
|
||||
PROJECT: ${{ inputs.project }}
|
||||
CHECKOUT: ${{ inputs.path }}
|
||||
COMMIT: ${{ inputs.commit }}
|
||||
FETCH: ${{ inputs.fetch }}
|
||||
PACKAGES: ${{ inputs.packages }}
|
||||
REQUESTED_JOBS: ${{ inputs.jobs }}
|
||||
MIN_FREE_MIB: ${{ inputs.min-free-mib }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
lock="$PROJECT/ziran.lock"
|
||||
digest=none
|
||||
if [ -f "$lock" ]; then
|
||||
digest=$(python3 -c 'import hashlib, sys; print(hashlib.sha256(open(sys.argv[1], "rb").read()).hexdigest())' "$lock")
|
||||
for tool in python3 git mktemp rm mkdir printenv; do
|
||||
if ! command -v "$tool" >/dev/null; then
|
||||
echo "::error::Ziran setup requires $tool on PATH"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
python3 - <<'PY'
|
||||
import hashlib, json, os, re, shutil, sys, tempfile
|
||||
from pathlib import Path
|
||||
|
||||
def number(label, value, maximum):
|
||||
if not re.fullmatch(r'[1-9][0-9]*', value) or len(value) > len(str(maximum)) or int(value) > maximum:
|
||||
raise ValueError(f'{label} must be an integer from 1 to {maximum}')
|
||||
return int(value)
|
||||
|
||||
def probe(path, needed):
|
||||
directory = path
|
||||
while not directory.exists():
|
||||
directory = directory.parent
|
||||
if not directory.is_dir():
|
||||
raise ValueError(f'expected a directory for {path}, found {directory}')
|
||||
try:
|
||||
with tempfile.TemporaryFile(dir=directory) as scratch:
|
||||
scratch.write(b'ziran setup preflight')
|
||||
scratch.flush()
|
||||
except OSError as error:
|
||||
raise ValueError(f'cannot write scratch for {path} in {directory}: {error}') from error
|
||||
available = shutil.disk_usage(directory).free // (1024 * 1024)
|
||||
if available < needed:
|
||||
raise ValueError(f'{directory} has {available} MiB available for {path}, needs {needed} MiB')
|
||||
|
||||
env = os.environ
|
||||
try:
|
||||
allocation = number('JOBS allocation', env['JOBS'], 64) if env.get('JOBS') else None
|
||||
requested = number('jobs input', env['REQUESTED_JOBS'], 64) if env['REQUESTED_JOBS'] else allocation or 1
|
||||
jobs = min(requested, allocation) if allocation else requested
|
||||
minimum = number('min-free-mib', env['MIN_FREE_MIB'], 1048576)
|
||||
workspace = Path(env['GITHUB_WORKSPACE']).resolve()
|
||||
checkout = Path(env['CHECKOUT'])
|
||||
root = (workspace / checkout).resolve()
|
||||
if not env['CHECKOUT'] or checkout.is_absolute() or workspace not in (root, *root.parents):
|
||||
raise ValueError(f'checkout path must be relative to the workspace: {checkout}')
|
||||
lock = Path(env['PROJECT'], 'ziran.lock')
|
||||
lock_data = lock.read_bytes() if lock.is_file() else None
|
||||
digest = hashlib.sha256(lock_data).hexdigest() if lock_data is not None else 'none'
|
||||
commit = env['COMMIT']
|
||||
fetch = env['FETCH'].lower() == 'true'
|
||||
if not commit or fetch:
|
||||
if lock_data is None:
|
||||
raise ValueError(f'missing lock file: {lock}')
|
||||
toolchain = json.loads(lock_data)['toolchain']
|
||||
if not commit:
|
||||
commit = toolchain['commit']
|
||||
if not isinstance(commit, str) or not re.fullmatch('[0-9a-f]{40}', commit):
|
||||
raise ValueError(f'expected a full Ziran commit hash, got {commit!r}')
|
||||
sources = Path(env.get('XDG_CACHE_HOME') or Path.home() / '.cache', 'ziran', 'sources')
|
||||
probe(root, minimum)
|
||||
probe(Path(env['RUNNER_TEMP']).resolve(), minimum)
|
||||
if fetch:
|
||||
probe(sources.resolve(), minimum)
|
||||
except (OSError, ValueError, KeyError, TypeError) as error:
|
||||
sys.exit(f'::error::Ziran setup preflight: {error}')
|
||||
with open(env['GITHUB_OUTPUT'], 'a') as output:
|
||||
for name, value in {'commit': commit, 'lock': digest, 'root': root,
|
||||
'sources': sources, 'jobs': jobs}.items():
|
||||
print(f'{name}={value}', file=output)
|
||||
print(f'Ziran setup preflight: {commit}, {jobs} make jobs, minimum {minimum} MiB per destination')
|
||||
PY
|
||||
if [ -n "$PACKAGES" ]; then
|
||||
sh "$GITHUB_ACTION_PATH/../../../scripts/ci_packages.sh" --check
|
||||
fi
|
||||
if [ -z "$COMMIT" ]; then
|
||||
COMMIT=$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))["toolchain"]["commit"])' "$lock")
|
||||
fi
|
||||
if ! printf '%s' "$COMMIT" | grep -Eq '^[0-9a-f]{40}$'; then
|
||||
echo "::error::The Ziran commit is not a full commit hash: $COMMIT"
|
||||
exit 1
|
||||
fi
|
||||
case "$RUNNER_OS-$RUNNER_ARCH" in
|
||||
Linux-X64)
|
||||
platform=linux-x64
|
||||
;;
|
||||
Linux-ARM64)
|
||||
platform=linux-arm64
|
||||
;;
|
||||
*)
|
||||
platform=
|
||||
;;
|
||||
esac
|
||||
# A compiler built on a newer image needs its newer C library, so
|
||||
# cached build trees are kept per image.
|
||||
libc=$(getconf GNU_LIBC_VERSION 2>/dev/null | tr ' ' '-' || true)
|
||||
{
|
||||
echo "commit=$COMMIT"
|
||||
echo "lock=$digest"
|
||||
echo "platform=$platform"
|
||||
echo "system=${ImageOS:-local}-${libc:-nolibc}"
|
||||
echo "root=$GITHUB_WORKSPACE/$CHECKOUT"
|
||||
echo "sources=${XDG_CACHE_HOME:-$HOME/.cache}/ziran/sources"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
# The script of this action's version, so every project gets its fix
|
||||
# whichever Ziran it locks.
|
||||
@@ -116,6 +163,77 @@ runs:
|
||||
read -r -d '' -a names <<< "$PACKAGES" || true
|
||||
timeout 1200 sh "$GITHUB_ACTION_PATH/../../../scripts/ci_packages.sh" "${options[@]}" "${names[@]}"
|
||||
|
||||
- name: Check native tools and resolve the build cache key
|
||||
id: native
|
||||
shell: bash
|
||||
env:
|
||||
COMMIT: ${{ steps.resolve.outputs.commit }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
require_tool() {
|
||||
if ! command -v "$1" >/dev/null; then
|
||||
echo "::error::Ziran setup requires $1 on PATH"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
read -r -a compiler <<< "${CC:-cc}"
|
||||
read -r -a host_compiler <<< "${HOST_CC:-cc}"
|
||||
for tool in make tar find touch tee grep "${compiler[0]}" "${host_compiler[0]}" "${AR:-ar}"; do
|
||||
require_tool "$tool"
|
||||
done
|
||||
platform=
|
||||
libs=()
|
||||
source='int main(void) { return 0; }'
|
||||
if [ "$RUNNER_OS" = Linux ]; then
|
||||
require_tool "${OBJCOPY:-objcopy}"
|
||||
require_tool "${HOST_OBJCOPY:-objcopy}"
|
||||
case "$RUNNER_ARCH" in
|
||||
X64) platform=linux-x64 ;;
|
||||
ARM64) platform=linux-arm64 ;;
|
||||
esac
|
||||
if [ -z "${PACKAGE_LIBS:-}" ]; then
|
||||
source='extern int RAND_bytes(unsigned char *, int); int main(void) { unsigned char x; return RAND_bytes(&x, 1) != 1; }'
|
||||
libs=(-lcrypto)
|
||||
fi
|
||||
fi
|
||||
probe=$(mktemp -d "$RUNNER_TEMP/ziran-native.XXXXXX")
|
||||
trap 'rm -rf "$probe"' EXIT
|
||||
if ! printf '%s\n' "$source" | "${compiler[@]}" -x c - -o "$probe/probe" "${libs[@]}"; then
|
||||
echo "::error::Ziran setup could not compile and link with ${compiler[*]}; check the diagnostics and native development dependencies above"
|
||||
exit 1
|
||||
fi
|
||||
libc=$(getconf GNU_LIBC_VERSION 2>/dev/null || true)
|
||||
libc=${libc// /-}
|
||||
# Jobs do not change the generated objects. Build overrides and compiler
|
||||
# identities do, and must not share the default prebuilt or cached tree.
|
||||
config=(CC HOST_CC CFLAGS CPPFLAGS LDFLAGS BOOTSTRAP BOOTSTRAP_CFLAGS
|
||||
AR OBJCOPY HOST_OBJCOPY PACKAGE_LIBS RUNTIME_LIBS SANITIZE_FLAGS
|
||||
CMAKE GEN_ZI2C MAKEFLAGS ZIRAN_DEFINES)
|
||||
overrides=false
|
||||
for name in "${config[@]}"; do
|
||||
if printenv "$name" >/dev/null; then
|
||||
overrides=true
|
||||
fi
|
||||
done
|
||||
fingerprint=$({
|
||||
for name in "${config[@]}"; do
|
||||
if printenv "$name" >/dev/null; then
|
||||
printf '%s=%s\0' "$name" "${!name}"
|
||||
fi
|
||||
done
|
||||
"${compiler[@]}" --version
|
||||
"${compiler[@]}" -dumpmachine
|
||||
"${host_compiler[@]}" --version
|
||||
"${host_compiler[@]}" -dumpmachine
|
||||
} | python3 -c 'import hashlib, sys; print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())')
|
||||
system="${ImageOS:-local}-${libc:-nolibc}"
|
||||
{
|
||||
echo "system=$system"
|
||||
echo "key=ziran-build-v2-$RUNNER_OS-$RUNNER_ARCH-$system-$COMMIT-$fingerprint"
|
||||
echo "platform=$platform"
|
||||
echo "overrides=$overrides"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Check out Ziran
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
with:
|
||||
@@ -124,40 +242,78 @@ runs:
|
||||
path: ${{ inputs.path }}
|
||||
persist-credentials: false
|
||||
|
||||
- name: Download the prebuilt build tree
|
||||
id: prebuilt
|
||||
if: steps.resolve.outputs.platform != ''
|
||||
- name: Restore the exact build cache
|
||||
id: cache
|
||||
continue-on-error: true
|
||||
uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
|
||||
with:
|
||||
path: ${{ inputs.path }}/build
|
||||
key: ${{ steps.native.outputs.key }}
|
||||
|
||||
- name: Verify the restored build tree
|
||||
id: verify
|
||||
shell: bash
|
||||
env:
|
||||
ROOT: ${{ steps.resolve.outputs.root }}
|
||||
ASSET: ziran-${{ steps.resolve.outputs.commit }}-${{ steps.resolve.outputs.platform }}.tar.gz
|
||||
COMMIT: ${{ steps.resolve.outputs.commit }}
|
||||
KEY: ${{ steps.native.outputs.key }}
|
||||
CACHE_HIT: ${{ steps.cache.outputs.cache-hit }}
|
||||
run: |
|
||||
set -uo pipefail
|
||||
set -euo pipefail
|
||||
if [ "$(git -C "$ROOT" rev-parse HEAD)" != "$COMMIT" ]; then
|
||||
echo "::error::Ziran checkout does not match requested commit $COMMIT"
|
||||
exit 1
|
||||
fi
|
||||
if ! git -C "$ROOT" diff --quiet HEAD --; then
|
||||
echo '::error::Ziran checkout has changes to tracked build inputs'
|
||||
exit 1
|
||||
fi
|
||||
started=$SECONDS
|
||||
if [ "$CACHE_HIT" = true ]; then
|
||||
if python3 "$GITHUB_ACTION_PATH/../../../scripts/toolchain_package.py" cache-verify "$KEY" "$ROOT/build"; then
|
||||
echo 'valid=true' >> "$GITHUB_OUTPUT"
|
||||
echo "Ziran cache: verified exact hit in $((SECONDS - started))s, skipping prebuilt download"
|
||||
exit 0
|
||||
fi
|
||||
echo '::warning::Rejected exact Ziran cache entry; using the normal fallback'
|
||||
else
|
||||
echo 'Ziran cache: exact miss'
|
||||
fi
|
||||
# A failed or prefix restore can leave a partial tree behind.
|
||||
rm -rf "$ROOT/build"
|
||||
|
||||
- name: Download the prebuilt build tree
|
||||
id: prebuilt
|
||||
if: steps.verify.outputs.valid != 'true' && steps.native.outputs.platform != '' && steps.native.outputs.overrides != 'true'
|
||||
shell: bash
|
||||
env:
|
||||
ROOT: ${{ steps.resolve.outputs.root }}
|
||||
ASSET: ziran-${{ steps.resolve.outputs.commit }}-${{ steps.native.outputs.platform }}.tar.gz
|
||||
run: |
|
||||
set -euo pipefail
|
||||
base=https://github.com/ziranlang/ziran/releases/download/toolchains
|
||||
work="$RUNNER_TEMP/ziran-prebuilt"
|
||||
rm -rf "$work"
|
||||
mkdir -p "$work"
|
||||
# A just-published asset can answer 504 for a while, longer than
|
||||
# curl's default 1+2+4 s of retries, so keep retrying for 2 minutes.
|
||||
for tool in curl sha256sum; do
|
||||
if ! command -v "$tool" >/dev/null; then
|
||||
echo "::warning::Ziran prebuilt download requires $tool; building locally"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
work=$(mktemp -d "$RUNNER_TEMP/ziran-prebuilt.XXXXXX")
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
started=$SECONDS
|
||||
echo "Ziran prebuilt: trying $ASSET"
|
||||
# Newly published assets can return 504 for longer than curl's usual retries.
|
||||
retry=(--retry 12 --retry-delay 10 --retry-max-time 120 --connect-timeout 10)
|
||||
if curl -fsSL "${retry[@]}" --max-time 180 -o "$work/$ASSET" "$base/$ASSET" &&
|
||||
curl -fsSL "${retry[@]}" --max-time 30 -o "$work/$ASSET.sha256" "$base/$ASSET.sha256" &&
|
||||
(cd "$work" && sha256sum --check --quiet "$ASSET.sha256") &&
|
||||
tar -xzf "$work/$ASSET" -C "$ROOT"; then
|
||||
echo "found=true" >> "$GITHUB_OUTPUT"
|
||||
echo 'found=true' >> "$GITHUB_OUTPUT"
|
||||
echo "Ziran prebuilt: verified download in $((SECONDS - started))s"
|
||||
else
|
||||
rm -rf "$ROOT/build"
|
||||
echo "No prebuilt build tree for $ASSET"
|
||||
echo "Ziran prebuilt: unavailable after $((SECONDS - started))s"
|
||||
fi
|
||||
rm -rf "$work"
|
||||
|
||||
- name: Restore the cached build tree
|
||||
id: cache
|
||||
if: steps.prebuilt.outputs.found != 'true'
|
||||
uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
|
||||
with:
|
||||
path: ${{ inputs.path }}/build
|
||||
key: ziran-build-${{ runner.os }}-${{ runner.arch }}-${{ steps.resolve.outputs.system }}-${{ steps.resolve.outputs.commit }}
|
||||
|
||||
- name: Build Ziran
|
||||
id: build
|
||||
@@ -166,9 +322,11 @@ runs:
|
||||
ROOT: ${{ steps.resolve.outputs.root }}
|
||||
COMMIT: ${{ steps.resolve.outputs.commit }}
|
||||
PREBUILT: ${{ steps.prebuilt.outputs.found }}
|
||||
CACHED: ${{ steps.cache.outputs.cache-hit }}
|
||||
CACHED: ${{ steps.verify.outputs.valid }}
|
||||
JOBS: ${{ steps.resolve.outputs.jobs }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
started=$SECONDS
|
||||
toolchain=built
|
||||
if [ "$PREBUILT" = true ]; then
|
||||
toolchain=prebuilt
|
||||
@@ -185,48 +343,94 @@ runs:
|
||||
rm -f "$ROOT/build/$name"
|
||||
fi
|
||||
done
|
||||
stamp="$RUNNER_TEMP/ziran-build-stamp"
|
||||
touch "$stamp"
|
||||
stamp=$(mktemp "$RUNNER_TEMP/ziran-build-stamp.XXXXXX")
|
||||
find "$ROOT/build" -exec touch -r "$stamp" {} +
|
||||
rm -f "$stamp" "$ROOT/build/obj/cmd/zir/zir_load.o"
|
||||
fi
|
||||
jobs=$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 2)
|
||||
log="$RUNNER_TEMP/ziran-make.log"
|
||||
make -C "$ROOT" -j"$jobs" all 2>&1 | tee "$log"
|
||||
log=$(mktemp "$RUNNER_TEMP/ziran-make.XXXXXX")
|
||||
trap 'rm -f "$log"' EXIT
|
||||
make -C "$ROOT" -j"$JOBS" BUILD_DIR=build all 2>&1 | tee "$log"
|
||||
"$ROOT/build/bin/ziran" version
|
||||
compiled=$(grep -c -- ' -c -o ' "$log" || true)
|
||||
rm -f "$log"
|
||||
echo "Ziran $COMMIT: $toolchain build tree, $compiled C files compiled"
|
||||
echo "Ziran $COMMIT: $toolchain build tree, $compiled C files compiled in $((SECONDS - started))s with $JOBS jobs"
|
||||
{
|
||||
echo "toolchain=$toolchain"
|
||||
echo "compiled=$compiled"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
echo "$ROOT/build/bin" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Record the built tree's cache inventory
|
||||
id: inventory
|
||||
if: steps.build.outputs.toolchain == 'built' && steps.cache.outputs.cache-hit != 'true'
|
||||
shell: bash
|
||||
env:
|
||||
ROOT: ${{ steps.resolve.outputs.root }}
|
||||
KEY: ${{ steps.native.outputs.key }}
|
||||
run: |
|
||||
if python3 "$GITHUB_ACTION_PATH/../../../scripts/toolchain_package.py" cache-write "$KEY" "$ROOT/build"; then
|
||||
echo 'ready=true' >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo '::warning::Ziran build succeeded but its build tree could not be cached'
|
||||
fi
|
||||
|
||||
- name: Save the build tree
|
||||
if: steps.prebuilt.outputs.found != 'true' && steps.cache.outputs.cache-hit != 'true'
|
||||
if: steps.inventory.outputs.ready == 'true'
|
||||
uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
|
||||
with:
|
||||
path: ${{ inputs.path }}/build
|
||||
key: ziran-build-${{ runner.os }}-${{ runner.arch }}-${{ steps.resolve.outputs.system }}-${{ steps.resolve.outputs.commit }}
|
||||
key: ${{ steps.native.outputs.key }}
|
||||
|
||||
# Package checkouts can hold programs built inside them, so they are kept
|
||||
# per image as well.
|
||||
- name: Restore the package checkouts
|
||||
id: sources
|
||||
if: inputs.fetch == 'true'
|
||||
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
|
||||
uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
|
||||
with:
|
||||
path: ${{ steps.resolve.outputs.sources }}
|
||||
key: ziran-sources-${{ runner.os }}-${{ runner.arch }}-${{ steps.resolve.outputs.system }}-${{ steps.resolve.outputs.lock }}
|
||||
key: ziran-sources-${{ runner.os }}-${{ runner.arch }}-${{ steps.native.outputs.system }}-${{ steps.resolve.outputs.lock }}
|
||||
restore-keys: |
|
||||
ziran-sources-${{ runner.os }}-${{ runner.arch }}-${{ steps.resolve.outputs.system }}-
|
||||
ziran-sources-${{ runner.os }}-${{ runner.arch }}-${{ steps.native.outputs.system }}-
|
||||
|
||||
- name: Fetch the locked packages
|
||||
id: fetch
|
||||
if: inputs.fetch == 'true'
|
||||
shell: bash
|
||||
working-directory: ${{ inputs.project }}
|
||||
env:
|
||||
ZIRAN: ${{ steps.resolve.outputs.root }}/build/bin/ziran
|
||||
run: '"$ZIRAN" fetch --locked'
|
||||
ROOT: ${{ steps.resolve.outputs.root }}
|
||||
JOBS: ${{ steps.resolve.outputs.jobs }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
started=$SECONDS
|
||||
# Fetch still checks the locked graph. When this launcher already is
|
||||
# the lock's toolchain, skip forwarding to a second build of it.
|
||||
python3 - <<'PY'
|
||||
import json, os, subprocess, sys
|
||||
from pathlib import Path
|
||||
|
||||
env = os.environ.copy()
|
||||
root = env['ROOT']
|
||||
lock = json.loads(Path('ziran.lock').read_text())
|
||||
toolchain = lock['toolchain']
|
||||
origin = subprocess.check_output(['git', '-C', root, 'config', '--get', 'remote.origin.url'], text=True).strip()
|
||||
origins = ('https://git.waozi.xyz/ziranlang/ziran', 'https://github.com/ziranlang/ziran')
|
||||
commit = subprocess.check_output(['git', '-C', root, 'rev-parse', 'HEAD'], text=True).strip()
|
||||
same_origin = any(origin in (url, url + '.git') and toolchain.get('url') in (url, url + '.git')
|
||||
for url in origins)
|
||||
prepared = same_origin and commit == toolchain.get('commit') and not Path('ziran.local.toml').exists()
|
||||
if prepared:
|
||||
env['ZIRAN_PINNED_LAUNCHER'] = '1'
|
||||
print('Ziran locked package fetch: using the prepared compiler', flush=True)
|
||||
status = subprocess.run([env['ZIRAN'], 'fetch', '--locked'], env=env).returncode
|
||||
if status:
|
||||
sys.exit(status)
|
||||
if prepared:
|
||||
with open(env['GITHUB_OUTPUT'], 'a') as output:
|
||||
print('prepared=true', file=output)
|
||||
PY
|
||||
echo "Ziran locked package fetch: $((SECONDS - started))s"
|
||||
|
||||
# A new lock starts from the previous lock's checkouts, so without this
|
||||
# the saved cache keeps every commit ever locked and grows until runners
|
||||
@@ -240,11 +444,15 @@ runs:
|
||||
ZIRAN: ${{ steps.resolve.outputs.root }}/build/bin/ziran
|
||||
SOURCES: ${{ steps.resolve.outputs.sources }}
|
||||
KEEP: ${{ runner.temp }}/ziran-locked-checkouts
|
||||
JOBS: ${{ steps.resolve.outputs.jobs }}
|
||||
PREPARED: ${{ steps.fetch.outputs.prepared }}
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
import json, os, re, shutil, subprocess
|
||||
from pathlib import Path
|
||||
sources, keep = Path(os.environ['SOURCES']).resolve(), Path(os.environ['KEEP'])
|
||||
if os.environ['PREPARED'] == 'true':
|
||||
os.environ['ZIRAN_PINNED_LAUNCHER'] = '1'
|
||||
lock = json.loads(Path('ziran.lock').read_text())
|
||||
names = [package['name'] for package in lock['packages']] + (['ziran'] if 'toolchain' in lock else [])
|
||||
used = set(keep.read_text().split()) if keep.exists() else set()
|
||||
@@ -260,3 +468,10 @@ runs:
|
||||
removed += 1
|
||||
print(f'Kept {len(used)} locked package checkouts; removed {removed} unused')
|
||||
PY
|
||||
|
||||
- name: Save the locked package checkouts
|
||||
if: inputs.fetch == 'true' && steps.sources.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
|
||||
with:
|
||||
path: ${{ steps.resolve.outputs.sources }}
|
||||
key: ${{ steps.sources.outputs.cache-primary-key }}
|
||||
+73
-22
@@ -14,13 +14,9 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
jobs:
|
||||
check:
|
||||
name: check (${{ matrix.shard }}/2)
|
||||
name: check
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
# site_pages.sh marks std modules shipped in the latest v* tag.
|
||||
@@ -28,10 +24,21 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.24'
|
||||
- name: Install ripgrep, MinGW, Wine, Vorbis, ARMv7 and Wasm tools, and the private display for the test scripts
|
||||
go-version: '1.25'
|
||||
# tests/zstd_go_cases.zi builds against this module with GOPROXY=off,
|
||||
# and the module itself requires Go 1.25.
|
||||
- name: Fetch the Go Zstandard module for the offline Go checks
|
||||
run: cd "$RUNNER_TEMP" && go mod download github.com/klauspost/[email protected]
|
||||
- name: Install ripgrep, MinGW, Wine, Vorbis, ARMv7 tools and the private display for the test scripts
|
||||
timeout-minutes: 5
|
||||
run: sh scripts/ci_packages.sh ccache ripgrep gcc-mingw-w64-x86-64 wine wine64 xvfb xauth ffmpeg libvorbis-dev python3-markdown gcc-arm-linux-gnueabihf libc6-dev-armhf-cross qemu-user clang-18 lld-18
|
||||
run: sh scripts/ci_packages.sh ccache ripgrep zip unzip gcc-mingw-w64-x86-64 wine wine64 xvfb xauth libsdl2-dev ffmpeg libvorbis-dev python3-markdown gcc-arm-linux-gnueabihf libc6-dev-armhf-cross qemu-user clang-18 lld-18
|
||||
# The emcc checks use the Emscripten the playground and the site use;
|
||||
# Ubuntu's emscripten package is 3.1.6, and its emcc is a symlink to a
|
||||
# wrapper that cannot run under its resolved name.
|
||||
- name: Set up Emscripten
|
||||
uses: emscripten-core/setup-emsdk@v15
|
||||
with:
|
||||
version: '6.0.6'
|
||||
- name: Keep compile results between runs
|
||||
uses: ./.github/actions/compile-cache
|
||||
with:
|
||||
@@ -39,7 +46,42 @@ jobs:
|
||||
- name: Build the toolchain
|
||||
run: make
|
||||
- name: Run the language, backend, and portable runtime checks
|
||||
run: env -u DISPLAY -u WAYLAND_DISPLAY WINDOWS_REQUIRED=1 ARM_REQUIRED=1 WASM_REQUIRED=1 ZIRAN_WASM_CC=clang-18 make check CHECK_JOBS=4 CHECK_SHARD=${{ matrix.shard }}/2
|
||||
run: env -u DISPLAY -u WAYLAND_DISPLAY WINDOWS_REQUIRED=1 ARM_REQUIRED=1 WASM_REQUIRED=1 ZIRAN_WASM_CC=clang-18 make check CHECK_JOBS=4
|
||||
- name: Pack the tested Ziran toolchain
|
||||
id: toolchain
|
||||
if: github.server_url == 'https://git.waozi.xyz' && github.event_name == 'push' && github.ref == 'refs/heads/master' && (env.BUILD_NATIVE != 'true' || steps.native.outputs.current == 'true')
|
||||
env:
|
||||
SOURCE: ${{ steps.native.outputs.source || github.workspace }}
|
||||
run: |
|
||||
output="build/toolchains/$GITHUB_SHA"
|
||||
if [ "$BUILD_NATIVE" = true ]; then
|
||||
gitea-native-build run python3 scripts/toolchain_package.py pack "$GITHUB_SHA" "$output"
|
||||
else
|
||||
python3 scripts/toolchain_package.py pack "$GITHUB_SHA" "$output"
|
||||
fi
|
||||
printf 'directory=%s/%s\n' "$SOURCE" "$output" >> "$GITHUB_OUTPUT"
|
||||
- name: Keep the verified toolchain archive
|
||||
if: steps.toolchain.outputs.directory != ''
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: toolchain-${{ github.sha }}
|
||||
path: ${{ steps.toolchain.outputs.directory }}
|
||||
if-no-files-found: error
|
||||
- name: Publish the toolchain to Gitea Packages
|
||||
if: steps.toolchain.outputs.directory != ''
|
||||
env:
|
||||
SOURCE: ${{ steps.native.outputs.source || github.workspace }}
|
||||
OUTPUT: ${{ steps.toolchain.outputs.directory }}
|
||||
ZIRAN_TOOLCHAIN_PACKAGE_USER: ${{ secrets.ZIRAN_TOOLCHAIN_PACKAGE_USER }}
|
||||
ZIRAN_TOOLCHAIN_PACKAGE_TOKEN: ${{ secrets.ZIRAN_TOOLCHAIN_PACKAGE_TOKEN }}
|
||||
run: |
|
||||
if [ -z "$ZIRAN_TOOLCHAIN_PACKAGE_USER$ZIRAN_TOOLCHAIN_PACKAGE_TOKEN" ]; then
|
||||
echo "Gitea package writer is unavailable. The toolchain is in this run's artifacts."
|
||||
exit 0
|
||||
fi
|
||||
for descriptor in "$OUTPUT"/*.json; do
|
||||
python3 "$SOURCE/scripts/toolchain_package.py" publish "$GITHUB_SHA" "$descriptor"
|
||||
done
|
||||
- name: Show how much the compile cache saved
|
||||
if: always()
|
||||
run: ccache --show-stats || true
|
||||
@@ -47,7 +89,7 @@ jobs:
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: check-logs-${{ matrix.shard }}
|
||||
name: check-logs
|
||||
path: build/check-logs/
|
||||
macos:
|
||||
runs-on: macos-latest
|
||||
@@ -69,14 +111,10 @@ jobs:
|
||||
cd "$RUNNER_TEMP/hello"
|
||||
test "$("$ziran" run)" = "Hello, world!"
|
||||
sanitize:
|
||||
name: sanitize (${{ matrix.shard }}/2)
|
||||
name: sanitize
|
||||
runs-on: ubuntu-24.04
|
||||
# A shard takes 15-20 minutes; runner speed varies by about twice.
|
||||
# Runner speed varies; execute the whole lean suite under both sanitizers.
|
||||
timeout-minutes: 35
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
# site_pages.sh marks std modules shipped in the latest v* tag.
|
||||
@@ -84,16 +122,27 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.24'
|
||||
go-version: '1.25'
|
||||
# tests/zstd_go_cases.zi builds against this module with GOPROXY=off,
|
||||
# and the module itself requires Go 1.25.
|
||||
- name: Fetch the Go Zstandard module for the offline Go checks
|
||||
run: cd "$RUNNER_TEMP" && go mod download github.com/klauspost/[email protected]
|
||||
- name: Install ripgrep and Vorbis for the test scripts
|
||||
timeout-minutes: 5
|
||||
run: sh scripts/ci_packages.sh ccache ripgrep ffmpeg libvorbis-dev python3-markdown
|
||||
run: sh scripts/ci_packages.sh ccache ripgrep zip unzip xvfb xauth libsdl2-dev ffmpeg libvorbis-dev python3-markdown
|
||||
# The emcc checks use the Emscripten the playground and the site use;
|
||||
# Ubuntu's emscripten package is 3.1.6, and its emcc is a symlink to a
|
||||
# wrapper that cannot run under its resolved name.
|
||||
- name: Set up Emscripten
|
||||
uses: emscripten-core/setup-emsdk@v15
|
||||
with:
|
||||
version: '6.0.6'
|
||||
- name: Keep compile results between runs
|
||||
uses: ./.github/actions/compile-cache
|
||||
with:
|
||||
key: sanitize
|
||||
- name: Run the checks under AddressSanitizer and UBSan
|
||||
run: env -u DISPLAY -u WAYLAND_DISPLAY make sanitize CHECK_JOBS=4 CHECK_SHARD=${{ matrix.shard }}/2
|
||||
run: env -u DISPLAY -u WAYLAND_DISPLAY make sanitize CHECK_JOBS=4
|
||||
- name: Show how much the compile cache saved
|
||||
if: always()
|
||||
run: ccache --show-stats || true
|
||||
@@ -101,7 +150,7 @@ jobs:
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: sanitizer-check-logs-${{ matrix.shard }}
|
||||
name: sanitizer-check-logs
|
||||
path: build/sanitize/check-logs/
|
||||
fuzz:
|
||||
runs-on: ubuntu-24.04
|
||||
@@ -135,7 +184,7 @@ jobs:
|
||||
path: package
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.24'
|
||||
go-version: '1.25'
|
||||
- name: Build the current toolchain
|
||||
run: make
|
||||
- name: Build the package's locked native library
|
||||
@@ -143,7 +192,9 @@ jobs:
|
||||
- name: Test every backend from source and saved IR with the current compiler
|
||||
working-directory: package
|
||||
run: |
|
||||
python3 "$GITHUB_WORKSPACE/scripts/test_native_package.py" \
|
||||
"$GITHUB_WORKSPACE/build/bin/ziran" run --target=c \
|
||||
--root "$GITHUB_WORKSPACE/scripts" --module-path "$GITHUB_WORKSPACE/tests" \
|
||||
"$GITHUB_WORKSPACE/scripts/test_native_package.zi" -- \
|
||||
--ziran "$GITHUB_WORKSPACE/build/bin/ziran" \
|
||||
--tools "$GITHUB_WORKSPACE/build/bin" \
|
||||
--source "tests/${{ matrix.package }}_test.zi" \
|
||||
|
||||
@@ -4,12 +4,12 @@ name: Publish website
|
||||
# whenever a push to master changes it. The repository secrets
|
||||
# CLOUDFLARE_API_TOKEN (Cloudflare Pages: Edit) and CLOUDFLARE_ACCOUNT_ID
|
||||
# authorize it; without them the job finishes without deploying.
|
||||
# By hand: npx wrangler pages deploy site --project-name=ziran --branch=master
|
||||
# Deploy only through this GitHub Actions workflow; never invoke Wrangler locally.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
paths: ['site/**', 'web/playground.c', 'web/bundle.c', 'scripts/build_playground.zi', 'scripts/site_target*', 'tests/site_targets.sh', 'cmd/zir/**', 'cmd/package*.zi', 'cmd/compiler_*.zi', 'bootstrap/**', 'std/**', 'Makefile', '.github/workflows/site.yml']
|
||||
paths: ['examples/**', 'site/**', 'web/playground.c', 'web/bundle.c', 'scripts/build_playground.zi', 'scripts/site_target*', 'scripts/site_library_targets.py', 'scripts/site_kernel_targets.py', 'scripts/site_standard_benchmarks.zi', 'scripts/site_benchmark_*.zi', 'bench/standard_cases.zi', 'bench/json_text.py', 'scripts/site_numbers.zi', 'bench/results/standard/**', 'scripts/benchmark_samples.py', 'bench/results/wasm-tier-*.json', 'tests/site_targets.sh', 'cmd/zir/**', 'cmd/package*.zi', 'cmd/compiler_*.zi', 'bootstrap/**', 'std/**', 'Makefile', '.github/workflows/site.yml']
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
@@ -35,6 +35,9 @@ jobs:
|
||||
fi
|
||||
- uses: actions/checkout@v4
|
||||
if: steps.credentials.outputs.present == 'true'
|
||||
with:
|
||||
# Receipt checks read inputs at the commits that measured and published them.
|
||||
fetch-depth: 0
|
||||
- name: Set up Emscripten
|
||||
if: steps.credentials.outputs.present == 'true'
|
||||
uses: emscripten-core/setup-emsdk@v15
|
||||
@@ -43,6 +46,9 @@ jobs:
|
||||
- name: Build the browser playground
|
||||
if: steps.credentials.outputs.present == 'true'
|
||||
run: |
|
||||
rm -rf site/examples
|
||||
mkdir site/examples
|
||||
cp examples/*.zi site/examples/
|
||||
make -j2 all
|
||||
build/bin/ziran run --target=c scripts/build_playground.zi
|
||||
node tests/playground_runtime.cjs
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
/build/
|
||||
/backup/
|
||||
/tests/build/
|
||||
/.fuse_hidden*
|
||||
/work/
|
||||
# zi2c locks the directory it writes, including a seed directory
|
||||
.build.lock
|
||||
__pycache__/
|
||||
/.wrangler/
|
||||
/site/assets/playground-runtime.js
|
||||
/site/assets/playground-runtime.wasm
|
||||
.wrangler/
|
||||
# Editor settings local to one machine (the shared tasks.json stays tracked)
|
||||
/.vscode/settings.json
|
||||
# Command Code agent state
|
||||
/.commandcode/
|
||||
Vendored
+93
@@ -0,0 +1,93 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "Ziran: Inspect assembly (scalar fixture)",
|
||||
"type": "process",
|
||||
"command": "env",
|
||||
"args": [
|
||||
"-u",
|
||||
"DISPLAY",
|
||||
"-u",
|
||||
"WAYLAND_DISPLAY",
|
||||
"-u",
|
||||
"XAUTHORITY",
|
||||
"-u",
|
||||
"DBUS_SESSION_BUS_ADDRESS",
|
||||
"HARMONY_DESKTOP_RECOVERY=0",
|
||||
"build-queue",
|
||||
"--",
|
||||
"python3",
|
||||
"scripts/inspect_assembly.py"
|
||||
],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
"group": {
|
||||
"kind": "build",
|
||||
"isDefault": true
|
||||
},
|
||||
"problemMatcher": [],
|
||||
"presentation": {
|
||||
"clear": true,
|
||||
"panel": "dedicated",
|
||||
"reveal": "always"
|
||||
}
|
||||
},
|
||||
{
|
||||
"label": "Ziran: Inspect assembly (choose source and entry)",
|
||||
"type": "process",
|
||||
"command": "env",
|
||||
"args": [
|
||||
"-u",
|
||||
"DISPLAY",
|
||||
"-u",
|
||||
"WAYLAND_DISPLAY",
|
||||
"-u",
|
||||
"XAUTHORITY",
|
||||
"-u",
|
||||
"DBUS_SESSION_BUS_ADDRESS",
|
||||
"HARMONY_DESKTOP_RECOVERY=0",
|
||||
"build-queue",
|
||||
"--",
|
||||
"python3",
|
||||
"scripts/inspect_assembly.py",
|
||||
"--source",
|
||||
"${input:assemblySource}",
|
||||
"--entry",
|
||||
"${input:assemblyEntry}",
|
||||
"--root",
|
||||
"${input:assemblyRoot}"
|
||||
],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
"problemMatcher": [],
|
||||
"presentation": {
|
||||
"clear": true,
|
||||
"panel": "dedicated",
|
||||
"reveal": "always"
|
||||
}
|
||||
}
|
||||
],
|
||||
"inputs": [
|
||||
{
|
||||
"id": "assemblySource",
|
||||
"type": "promptString",
|
||||
"description": "Ziran source file, relative to the repository",
|
||||
"default": "tests/spec/assembly_scalar.zi"
|
||||
},
|
||||
{
|
||||
"id": "assemblyEntry",
|
||||
"type": "promptString",
|
||||
"description": "Direct-backend entry (MODULE:FUNCTION)",
|
||||
"default": "assembly_scalar:Answer"
|
||||
},
|
||||
{
|
||||
"id": "assemblyRoot",
|
||||
"type": "promptString",
|
||||
"description": "Module root, relative to the repository",
|
||||
"default": "tests/spec"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -4,26 +4,81 @@ Ziran owns the language, compiler tools, `.zir`, portable `.zx` output,
|
||||
standard modules, and runtime. Keep this repository usable for programs that
|
||||
do not import a UI library.
|
||||
|
||||
- Do not put Inbe application code, screens, assets, workflows, or platform
|
||||
policy in Ziran. Those belong in `../inbe`.
|
||||
- Do not put Kryon widgets or UI-specific compiler cases in Ziran. Kryon is an
|
||||
ordinary library in `../kryon`, imported by applications that need it.
|
||||
- Add a capability here only when it is useful to non-graphical programs as a
|
||||
language or standard-library feature. Keep the source, checked `.zir`,
|
||||
native targets, and portable VM behavior aligned.
|
||||
- Use the current Ziran syntax directly. Do not add legacy Kryon/KIR/KRB
|
||||
compatibility paths.
|
||||
- Do not preserve old source spellings, command flags, binary formats, or
|
||||
runtime entry points for backward compatibility. Remove executable legacy
|
||||
paths when replacing them; keep rejection tests that enforce the current
|
||||
language rules.
|
||||
- Run relevant checks with `DISPLAY` and `WAYLAND_DISPLAY` removed. Any test
|
||||
that needs a display must use a private Xvfb/Xephyr display.
|
||||
- Test with `make check` (every check, run in parallel on `BUILD_QUEUE_JOBS`)
|
||||
and `make check-bootstrap`; `make check CHECK_FILTER=text` reruns only the
|
||||
checks whose name contains `text`. Full logs are in `build/check-logs/`.
|
||||
## Layout
|
||||
|
||||
- `cmd/` compiler and tools (`ziran`, `zi2c`, `zi2go`, `zi2zx`, `zx2native`,
|
||||
`zx2wasm`, `zi-edit`, `zi-fmt`, `zi-api`, `zi-inspect`, `zi2zir`).
|
||||
- `bootstrap/` generated C seeds; refresh with `make update-bootstrap`.
|
||||
- `std/` standard modules; `tests/` retained checks; `proofs/` Lean model.
|
||||
- `bench/` benchmark drivers; retained receipts in `bench/results/`.
|
||||
- `docs/` user and contributor documents; `plans/` open work;
|
||||
`ASSEMBLY/` machine-IR and ZX format specs; `site/` generated website.
|
||||
- `scripts/` site and release helpers; `templates/` project templates.
|
||||
|
||||
## Commands
|
||||
|
||||
- Build: `make`; install: `make install-user` (into `~/.local/bin`).
|
||||
- Checks: `make check` and `make check-bootstrap`. `make check
|
||||
CHECK_FILTER=text` runs every check whose name contains `text`. Full logs
|
||||
land in `build/check-logs/`.
|
||||
- Run checks with `DISPLAY` and `WAYLAND_DISPLAY` removed; any test that needs
|
||||
a display uses a private Xvfb/Xephyr.
|
||||
- Proof model: `make proof-model LEAN=/path/to/lean` (see docs/LAWS.md).
|
||||
|
||||
## Question -> document
|
||||
|
||||
| Question | Document |
|
||||
| --- | --- |
|
||||
| How do I compile, run, or package a program? | docs/USAGE.md |
|
||||
| Which targets and features are supported today? | docs/IMPLEMENTATION_STATUS.md, docs/FEATURES.md |
|
||||
| How do packages, projects, and locks work? | docs/PACKAGES.md |
|
||||
| What does the compiler pipeline do? | docs/ARCHITECTURE.md |
|
||||
| How do I write Ziran (syntax by example, habits from other languages, std signatures)? | docs/REFERENCE.md (site/llms.txt is generated from it) |
|
||||
| What is the language syntax (directives, enums, imports)? | docs/LANGUAGE_DIRECTION.md |
|
||||
| How do owned values and recoverable failures behave? | docs/OWNED_VALUES.md |
|
||||
| What do diagnostic codes and JSON diagnostics look like? | docs/DIAGNOSTICS.md |
|
||||
| How do tools edit and query source programmatically? | docs/AUTHORING.md, docs/API_DISCOVERY.md, docs/SEMANTIC_EDIT.md |
|
||||
| How do laws and proof certificates work? | docs/LAWS.md |
|
||||
| What is `.zir`? | docs/ZIR.md |
|
||||
| What is `.zx` and how is it linked? | docs/ZX.md, ASSEMBLY/zx-executable-format.md, ASSEMBLY/zx-library-format.md |
|
||||
| How does direct native code generation work? | ASSEMBLY/README.md, ASSEMBLY/machine-ir.md, ASSEMBLY/lowered-format.md |
|
||||
| How is Unicode handled? | docs/UNICODE.md |
|
||||
| How do benchmarks run? | bench/README.md, bench/standard/README.md |
|
||||
| What work is still open? | plans/open-work.md |
|
||||
|
||||
## Rules
|
||||
|
||||
- Scope: no Inbe application code (`../inbe`); no Kryon widgets or
|
||||
UI-specific compiler cases (`../kryon` is an ordinary library). Add a
|
||||
capability here only when non-graphical programs benefit. The exception
|
||||
is ZX Runner and the platform layer it hosts (window, drawing, input,
|
||||
media) on Linux and Android, which belong here even though they are
|
||||
visual (owner, 2026-11-23); widgets stay in UI libraries.
|
||||
- No backward compatibility: use current Ziran syntax only. Remove legacy
|
||||
spellings, flags, binary formats, and entry points; keep the rejection
|
||||
tests that enforce current rules.
|
||||
- Keep source, checked `.zir`, native targets, and instruction-engine
|
||||
behavior aligned. Generated output carries only the code a program reaches;
|
||||
shrink output by removing what is not needed.
|
||||
- Module roots are ordinary repeatable search folders. Keep package manifests,
|
||||
CLI forwarding, editor paths and loader storage dynamically sized; do not add
|
||||
a folder-count cap or library-specific compiler handling. Preserve resolution
|
||||
ordering and use normal input-size, allocation and operating-system bounds.
|
||||
CLI forwarding, editor paths, and loader storage dynamically sized; no
|
||||
folder-count caps or library-specific compiler handling.
|
||||
- Write retained test logic and helpers in Ziran. Remove redundant tests and
|
||||
unused helpers instead of growing a parallel suite. Run every retained
|
||||
check; never substitute sharding or skipped tests.
|
||||
- Keep private transfer and recovery state under the ignored `backup/`.
|
||||
Keep benchmark reports under tracked `bench/results/`; temporary compiler
|
||||
and test outputs under `build/`.
|
||||
- Benchmarks run directly on Alpha's physical host, never virtualized. If
|
||||
Alpha is unavailable, wait instead of measuring elsewhere. Record the host
|
||||
in every report; collect both sides of a comparison on the same host.
|
||||
Exclude anomalies with the symmetric 1.5xIQR rule (inclusive interpolated
|
||||
quartiles) for every target and platform; keep raw samples and excluded
|
||||
indices.
|
||||
- Shared checkout: commit on master through the shared index. `git add` only
|
||||
your own paths, then `git commit -- <those paths>`, so other lanes' staged
|
||||
paths stay out. Never `git add -A`, a private `GIT_INDEX_FILE`, plumbing
|
||||
that writes commits or moves HEAD, a rebase, reset or stash; never touch
|
||||
files another lane is editing.
|
||||
- Deploy the website only through `.github/workflows/site.yml` on CI. Never
|
||||
invoke Wrangler directly from a local terminal.
|
||||
@@ -0,0 +1,98 @@
|
||||
# Step 01 — Freeze the execution contract and completion matrix
|
||||
|
||||
Status: in progress. The experimental [scalar prototype](README.md) does not close this step's completion gates. Delivery order, plan review and per-row cutover rules are in [milestones](milestones.md); the Alpha physical-host baseline of the old engines was captured at milestone M0, before they were removed.
|
||||
|
||||
The [assembly-target gap policy](gap-policy.md) is normative. A missing
|
||||
implementation is a named failing matrix cell with a stable diagnostic; no
|
||||
fallback, downgrade, skipped probe, emulated run, or legacy engine can satisfy
|
||||
that cell.
|
||||
|
||||
## Objective
|
||||
|
||||
Upgrade `.zx` into a portable executable instruction format and add a direct native compilation path. Preserve `.zir` as the checked language interchange format. Make every transformation inspectable, including the final linked instructions. QBE is outside this plan.
|
||||
|
||||
The intended architecture is:
|
||||
|
||||
```text
|
||||
.zi -> .zir -> lowered portable IR -> .zx container
|
||||
| |
|
||||
+--------+---------+
|
||||
|
|
||||
optimization and target lowering
|
||||
|
|
||||
machine IR -> registers and stack frames
|
||||
|
|
||||
instruction encoding -> object code
|
||||
|
|
||||
native linker -> executable
|
||||
|
||||
.zx -> instruction verifier -> portable interpreter
|
||||
.zx -> instruction verifier -> same native backend -> executable memory
|
||||
```
|
||||
|
||||
Assembly listings are views of the instruction stream used for encoding, not a required write-and-reparse stage. Final disassembly reads the actual linked or loaded bytes.
|
||||
|
||||
## Ordered implementation files
|
||||
|
||||
1. [Contract and completion matrix](01-contract-and-completion-matrix.md).
|
||||
2. [Lowered IR and verifier](02-lowered-ir-and-verifier.md).
|
||||
3. [Complete language lowering](03-language-lowering.md).
|
||||
4. [Portable instruction engine](04-portable-instruction-engine.md).
|
||||
5. [ZX format and linking](05-zx-format-and-linking.md).
|
||||
6. [Optimization and first native backend](06-optimization-and-native-backend.md).
|
||||
7. [Architecture and platform coverage](07-architecture-and-platform-coverage.md).
|
||||
8. [Assembler, object files, and native linker](08-assembler-objects-and-linker.md).
|
||||
9. [Native runtime, cache, and host integration](09-native-runtime-and-integration.md).
|
||||
10. [Inspection, performance, and final cutover](10-inspection-performance-and-cutover.md).
|
||||
|
||||
## Current repository boundaries
|
||||
|
||||
- [The shared IR schema](../cmd/compiler_ir.zi) represents typed statements, expression graphs, declarations, source spans, laws, and proofs.
|
||||
- [The ZX container](../cmd/compiler_bundle.zi) packages verified instructions, assets and the host interface; [the embedding API](../cmd/zir/zir_host.c) runs them on [the portable instruction engine](../cmd/compiler_exec.zi).
|
||||
- [The architecture contract](../docs/ARCHITECTURE.md) changes only after replacement paths are verified.
|
||||
- Current working-tree changes belong to their existing tasks. Record a baseline and coordinate overlapping files before implementation; never absorb unrelated changes into this feature.
|
||||
|
||||
## Required decisions and deliverables
|
||||
|
||||
- [x] Create a [feature-by-target matrix](feature-matrix.md) from current compiler capability reporting, tests, and documented limitations. Name each feature, reference fixture, source/saved-IR behavior, portable behavior, native behavior, and required execution platform.
|
||||
- [ ] Separate portable language behavior, native language extensions, CPU requirements, OS services, and foreign-runtime requirements. A Go-only foreign type does not become a portable native type by renaming its representation.
|
||||
- [ ] Set the native language coverage target to all currently supported C-native language semantics, plus all currently supported portable ZX semantics. Keep C and Go output available. List legitimate target-specific exclusions explicitly.
|
||||
- [x] Cover the maintained Linux, Android, Windows, macOS, and browser/WebAssembly combinations. Derive exact CPU/OS/ABI rows from the live toolchain and repository; include existing 32-bit ARM support. New architectures such as RISC-V are explicit extensions, not an unbounded definition of completion. The [target registry](07-architecture-and-platform-coverage.md#target-registry-and-preflight) lists every row.
|
||||
- [x] Specify numeric behavior, memory and pointer rules, ownership, cleanup, initialization, traps, call order, concurrency, fuel checkpoints, and capability contracts before assigning opcodes: the [execution contract](execution-contract.md).
|
||||
- [x] Define the new format as an incompatible executable-format revision: [revision 28](zx-executable-format.md), chosen against the writer it replaced. A file of another revision is rejected.
|
||||
- [x] Define backend APIs and ownership: verified portable program, target description, machine program, encoded image, and loaded instance. Separate immutable code from mutable instance state. See the [contract layers](execution-contract.md#contract-layers).
|
||||
- [x] State that validated native code is not an operating-system sandbox. Keep malformed-input rejection, capability restrictions, and native process isolation claims distinct.
|
||||
- [x] Define debug and release policies. Semantic checks remain correct in both; stripping inspection metadata is an explicit build choice.
|
||||
- [x] Record that cross-compilation, successful encoding, a child-agent receipt, or a saved benchmark report does not establish target execution correctness.
|
||||
- [ ] Assign every non-Implemented matrix cell a stable Gap diagnostic or a
|
||||
deliberate Excluded contract. Verify rejection before output replacement,
|
||||
initialization, host calls or entry execution.
|
||||
- [x] Make engine and target selection explicit. Portable, native, Wasm, C and
|
||||
Go are separate contracts; none may rescue another after preflight fails.
|
||||
|
||||
The implementation keeps those routes distinct: portable runs
|
||||
verified LIR, native means direct verified-LIR-to-machine-code/platform output,
|
||||
and the separately selected C and Go backends generate source that can be
|
||||
compiled into platform binaries. Native slice comparison and host ABI gaps stop
|
||||
before output replacement; they do not select any of the other routes.
|
||||
|
||||
## Proposed implementation ownership
|
||||
|
||||
Implement reusable compiler/runtime modules in Ziran under `cmd/`, following the existing compiler modules. Add only necessary C embedding and OS glue at the existing boundaries. Proposed module names in later steps are implementation targets, not files claimed to exist today. Use the current C backend to bootstrap new Ziran code initially, then verify the new backend can build those modules itself.
|
||||
|
||||
## Definition of 100% complete
|
||||
|
||||
Every required matrix cell has fresh execution evidence; no required cell is
|
||||
silently skipped or satisfied by a fallback. Every remaining gap has its stable,
|
||||
side-effect-free error and stays visibly incomplete. Both source and saved
|
||||
`.zir` reach the same lowered semantics. `.zx` runs without reparsing semantic
|
||||
statement text or requiring embedded executable `.zir`. Native AOT and native
|
||||
ZX execution use the same code generator without generated C, an external
|
||||
assembler, or an external linker on the promised direct path. External
|
||||
OS libraries remain allowed dependencies.
|
||||
|
||||
All ten exit gates must pass. A smaller scalar prototype is a milestone, never the finished upgrade. There is no promise of universally optimal machine code: performance acceptance uses declared workloads and measured regressions, not the phrase “absolute performance.” Missing hardware, signing facilities, or tools remain named incomplete gates.
|
||||
|
||||
## Verification and handoff
|
||||
|
||||
Save the baseline matrix, reproducible fixture list, explicit non-goals, and ownership map in this folder or the established documentation/report locations. Do not create release tags or bump the product version for planning. Step 02 may proceed once the semantic and portability contracts are concrete enough to encode and validate.
|
||||
@@ -0,0 +1,96 @@
|
||||
# Step 02 — Implement lowered portable IR and its verifier
|
||||
|
||||
Status: in progress; [typed scalar/aggregate schema and verifier](README.md), including checked global-derived pointers and procedure values. Complete memory, capability and language coverage remain pending. Depends on [step 01](01-contract-and-completion-matrix.md). Next: [complete language lowering](03-language-lowering.md).
|
||||
|
||||
The schema carries the [gap policy](gap-policy.md) through target preflight:
|
||||
unsupported required operations and target extensions have stable identifiers
|
||||
and cannot be rewritten as calls into another engine or backend.
|
||||
|
||||
## Objective
|
||||
|
||||
Create a structured, serializable representation of executable operations below `.zir`. It must support efficient interpretation and native lowering while retaining useful optimization and debugging facts. Do not make portable instructions expose physical registers, host addresses, or a particular calling convention.
|
||||
|
||||
## Existing integration points
|
||||
|
||||
- [Checked compiler records](../cmd/compiler_ir.zi).
|
||||
- [ZIR reader and writer](../cmd/compiler_zir_serial.zi).
|
||||
- [Scalar semantic helpers](../cmd/zir/zir_scalar.h).
|
||||
- [Compiler embedding contract](../docs/COMPILER_API.md).
|
||||
|
||||
Proposed new modules: `cmd/compiler_lowered_ir.zi`, `cmd/compiler_lowered_verify.zi`, and `cmd/compiler_lowered_text.zi`. Keep binary ZX framing in step 05 rather than coupling instruction records to file offsets.
|
||||
|
||||
## Typed console service boundary
|
||||
|
||||
The direct console path represents output as effectful `HostCall` instructions,
|
||||
not as generated C/Go or an untyped call to a process address. Its reserved
|
||||
module is `ziran.platform`. The byte-output signature is exactly
|
||||
`ziran.platform.write_all(u64 fd, *u8 bytes, u64 count) -> void`, with Host
|
||||
calling convention, no variadic parameters, and no body. Here `*u8` is a
|
||||
verified Ziran pointer token, not a raw host address. The native veneer resolves
|
||||
that token to permitted byte storage and checks the requested extent before
|
||||
issuing an operating-system write.
|
||||
|
||||
`compiler_lowered_verify.zi` admits this one pointer parameter only for that
|
||||
exact module, name, arity, and type signature. It does not relax the ordinary
|
||||
host-capability restriction on pointers or pointer-containing aggregates. The
|
||||
native encoder independently validates the service signature; matching a name
|
||||
alone cannot authorize a different ABI.
|
||||
|
||||
Literal-format `print` evaluates all arguments before its first output call.
|
||||
It then emits literal byte writes and Ziran-owned signed-integer,
|
||||
unsigned-integer, and boolean formatting services. The scalar formatter names
|
||||
are `ziran.print.signed(s64)`, `ziran.print.unsigned(u64)`, and
|
||||
`ziran.print.bool(bool)`, all returning void in the same reserved module.
|
||||
`HostCall` retains its effect ordering through optimization. Float-format
|
||||
service records may be inspected or serialized, but native ELF emission must
|
||||
reject them with the named float-format gap until an exact formatter exists.
|
||||
This console binding does not claim general foreign-call, host-trampoline, or
|
||||
cross-target support; see [the runtime contract](09-native-runtime-and-integration.md).
|
||||
|
||||
## Implementation work
|
||||
|
||||
- [ ] Define program, module, type, function, basic-block, value, instruction, constant, global, import, and debug-location records with stable IDs.
|
||||
- [ ] Use SSA values and block parameters for register-like values. Represent mutable/address-taken storage through explicit memory operations. Specify block-parameter semantics so interpreter and native phi elimination agree.
|
||||
- [ ] Define integer widths and signed operations explicitly. Specify narrowing, sign/zero extension, overflow, shift counts, division edge cases, comparison, and conversion behavior from current Ziran semantics.
|
||||
- [ ] Define float32/float64 operations, bitcasts, NaN-sensitive comparisons, signed zero, conversions, and rounding assumptions. Do not introduce implicit fast-math permissions.
|
||||
- [ ] Extend the existing checked global/frame pointers, procedure values and
|
||||
immutable string byte/count representation to heap-derived pointers, slices,
|
||||
unions, vectors and the remaining string operations without assuming a fixed
|
||||
host pointer width. Keep code, data and capability references distinct.
|
||||
The M1 subset now includes checked frame-local aggregate/procedure storage,
|
||||
bounded derived slice addresses, byte equality, readonly data and typed
|
||||
byte-view/pointer-free aggregate capabilities. Unions, resizable vectors,
|
||||
general ownership and raw host pointers remain open or deliberately rejected.
|
||||
- [ ] Separate portable logical type identity from target physical layout. Keep field/element access and layout queries symbolic until target layout is known; explicitly mark native-layout-dependent declarations and required host ABI descriptors.
|
||||
- [ ] Define loads, stores, copies, zeroing, address calculations, calls, branches, returns, traps, and unreachable terminators. Specify alignment, access width, alias assumptions, and permitted overlap for each memory operation.
|
||||
- [ ] Preserve effect order with an explicit effect dependency or another equally checkable ordering contract. Calls, stores, cleanup, volatile/atomic operations, and fuel checkpoints must not move unsafely.
|
||||
- [ ] Specify atomics and memory ordering only where supported by the language contract. Declare unsupported operations instead of interpreting ordinary loads as atomic.
|
||||
- [ ] Define source-origin IDs and transformation-origin chains, including generated cleanup, inlined calls, generic instances, host adapters, and native variants.
|
||||
- [ ] Attach conservative optimization facts such as known ranges, alignment, readonly arguments, and ownership. Distinguish verifier-derived facts from producer assertions; unsafe producer claims cannot authorize code motion or unchecked access.
|
||||
- [ ] Implement deterministic traversal and textual dumps. Stable IDs must not depend on pointer values, allocator order, timestamps, or nondeterministic hash iteration.
|
||||
- [ ] Implement a structural verifier for IDs, types, terminators, predecessor lists, argument arity, use-before-definition, dominance, block parameters, entry points, and reachable symbol signatures.
|
||||
- [ ] Implement memory/effect and layout validation. Reject invalid offsets, contradictory alignments, malformed constant data, impossible call conventions, and illegal native-only operations in portable code.
|
||||
- [ ] Bound decoder allocation and graph work by checked input sizes and explicit resource budgets. Use iterative algorithms where attacker-controlled depth could exhaust the compiler stack.
|
||||
- [ ] Provide recoverable structured diagnostics with function, block, instruction, and source context. Library errors must not abort the host process or leak partially built programs.
|
||||
- [ ] Represent required target features and Gap identifiers explicitly. The
|
||||
verifier rejects an operation outside the selected target contract; it never
|
||||
erases it, serializes it as a no-op, or substitutes a portable/native helper.
|
||||
|
||||
## Tests
|
||||
|
||||
Add `tests/lowered_ir_cases.zi` and `tests/lowered_verifier_cases.zi`, with shell launchers following the repository's existing check discovery.
|
||||
|
||||
- Positive fixtures: straight-line arithmetic, diamonds, loops, nested loops, block parameters, memory-backed locals, indirect calls, and multiple return fields.
|
||||
- Negative fixtures: cycles in value definitions, invalid dominance, duplicate IDs, wrong block arity, missing terminators, bad types, impossible layouts, effect-order violations, and malformed debug references.
|
||||
- Determinism: rebuild equivalent programs under different allocation histories and compare serialized instruction content and text dumps.
|
||||
- Lifetime: retain a verified lowered program after closing its original `.zir` owner; verify ownership is explicit and no borrowed storage becomes invalid.
|
||||
|
||||
Run builds and local tests through `build-queue --` with `DISPLAY` and `WAYLAND_DISPLAY` removed. This step requires no benchmark claims.
|
||||
|
||||
## Exit gate
|
||||
|
||||
All defined instruction forms have documented semantics and verifier coverage. A malformed program cannot become executable merely because it has a “checked” flag. Every unresolved required operation remains a visible Gap with a stable diagnostic. No new saved format relies on C struct padding or process pointers. The schema, verifier, and printer are usable independently of a specific CPU backend.
|
||||
|
||||
## Handoff
|
||||
|
||||
Deliver the schema, opcode/effect/layout tables, diagnostics, deterministic fixtures, and verifier API to steps 03–05. Record any operation whose semantics remain unresolved; do not fill the gap with generated source text.
|
||||
@@ -0,0 +1,63 @@
|
||||
# Step 03 — Lower the complete supported language into executable operations
|
||||
|
||||
Status: in progress; [scalar, record, fixed-array, procedure-value and restricted global/pointer lowering](README.md). Complete language coverage remains pending. Depends on [step 02](02-lowered-ir-and-verifier.md). Next: [portable instruction execution](04-portable-instruction-engine.md).
|
||||
|
||||
Missing lowering follows the [gap policy](gap-policy.md): it is a stable,
|
||||
source-located compiler error and an open matrix cell, never a request to
|
||||
evaluate the AST, generate C, or select another engine.
|
||||
|
||||
## Objective
|
||||
|
||||
Translate checked `.zir` into the new portable executable model without recovering program meaning from statement text. Cover the full matrix from step 01; use a small arithmetic subset only to establish the lowering framework.
|
||||
|
||||
## Existing integration points
|
||||
|
||||
- [Checked program schema](../cmd/compiler_ir.zi) and [semantic body utilities](../cmd/compiler_zir_lower.zi).
|
||||
- [Current statement, expression, and call emission](../cmd/compiler_zir_lower.zi) as behavior references, not source-generation dependencies.
|
||||
- [Current semantic cleanup implementation](../cmd/compiler_ir_cleanup.zi).
|
||||
- [Current native symbol/layout planning](../cmd/compiler_machine_elf.zi).
|
||||
- [Current assembly metadata](../cmd/zir/zir_asm.c) and [SIMD classification](../cmd/compiler_simd_metadata.zi).
|
||||
|
||||
Proposed modules: `cmd/compiler_lower.zi`, `cmd/compiler_lower_expr.zi`, `cmd/compiler_lower_control.zi`, `cmd/compiler_lower_storage.zi`, and `cmd/compiler_lower_calls.zi`. Split further only when responsibilities require it.
|
||||
|
||||
## Implementation work
|
||||
|
||||
- [ ] Lower concrete checked functions after generic specialization and compile-time selection. Preserve declaration ownership, imported names, public/private linkage, and stable function identity.
|
||||
- [ ] Lower expressions in the language's evaluation order. Named arguments evaluate in source order, then map to parameter positions; do not accidentally inherit machine ABI order.
|
||||
- [ ] Lower short-circuit logic, conditional expressions, branches, every supported loop form, and named break/continue into explicit blocks and edges.
|
||||
- [ ] Lower returns through a shared, checkable cleanup mechanism. Preserve `defer`, owned-vector/text destruction, moves, temporary lifetime, early exits, and unwind behavior wherever the target contract supports it.
|
||||
- [ ] Extend the implemented mutable scalar locals, checked global/frame
|
||||
pointers, nested record/fixed-array paths, immutable string literals/copies,
|
||||
result records and aggregate copies to local aggregate/procedure-value
|
||||
address-taking, heap-derived pointers, slices, dynamic aggregates, remaining
|
||||
string operations and enum storage. Preserve zero initialization and copy
|
||||
behavior.
|
||||
M1 now lowers local aggregate/procedure address-taking, borrowed fixed-array
|
||||
and byte-view slices, checked string indexing/comparison and ordered runtime
|
||||
initializers. Resizable owned aggregates, generated cleanup/moves, unions and
|
||||
remaining enum-storage coverage keep this broader item open.
|
||||
- [ ] Make alias-sensitive assignments and in-place aggregate results correct when a later argument mutates the destination or a global aliases an argument. Optimizations must not change old-value reads.
|
||||
- [ ] Emit explicit bounds/trap operations before optimization. Carry enough range and effect information for later verified check elimination; do not copy C-only proof shortcuts without their preconditions.
|
||||
- [ ] Lower direct/indirect calls, procedure values, callbacks, foreign C calls, varargs, startup functions, and function-address equality. Record ABI intent without assigning physical argument registers yet.
|
||||
- [ ] Represent language/runtime helpers through typed symbols with defined semantics. Implement helpers in Ziran where possible; inventory every remaining dependence on generated C macros, headers, or compiler intrinsics.
|
||||
- [ ] Lower portable SIMD to explicit lane types and operations. Preserve saturation, wrapping, masks, lane order, shuffles, and signedness; keep native vector width selection for target lowering.
|
||||
- [ ] Lower parallel regions into ordinary outlined procedures plus typed runtime operations. Preserve captures, reductions/results, deterministic failure behavior, and synchronization boundaries.
|
||||
- [ ] Treat GPU offload and OS services as explicit declared backend/runtime capabilities. Implement existing behavior where supported and reject genuine missing facilities before execution without introducing application-specific compiler rules or CPU fallbacks.
|
||||
- [ ] Preserve `#asm` portable implementations and typed native variant bindings as separate target implementations. A portable build lowers the portable implementation; a direct native build requires a matching architecture/feature variant and rejects its absence. Native templates have explicit operands, effects, clobbers, architecture, and CPU requirements; they cannot become portable opcode semantics.
|
||||
- [ ] Reject reachable foreign Go objects, Go maps/interfaces, reflection-only tags, or runtime operations in targets that cannot implement them. Retain the Go backend and its existing valid programs.
|
||||
- [ ] Carry global initialization order, reachability roots, callback roots, exported ABI layouts, diagnostic spans, and law/proof provenance into the lowered program.
|
||||
- [x] Feed the result through the step-02 verifier unconditionally and make lowering failures recoverable through the compiler API.
|
||||
|
||||
## Tests
|
||||
|
||||
Create lowering fixtures in Ziran and reuse current behavior tests, including [numeric semantics](../tests/numeric_semantics.sh), [operand order](../tests/spec/native_operand_order_test.zi), [parallel captures](../tests/parallel_captures.sh), [generic assembly](../tests/generic_assembly_cases.zi), and [saved-IR mutations](../tests/saved_ir_mutations.zi).
|
||||
|
||||
For each matrix feature, compile from `.zi` and saved `.zir`; compare verified lowered structure, outputs, traps, observable host calls, and cleanup effects against the existing supported execution paths. Add independent expected-result oracles for numeric boundaries and aliasing cases rather than relying only on agreement between backends sharing helper code.
|
||||
|
||||
## Exit gate
|
||||
|
||||
Every supported source construct has an explicit lowering, a deliberate Excluded contract, or a named Gap with a stable diagnostic. No placeholder operation invokes an AST evaluator, generated C fragment, source-text interpreter, portable body, or alternate backend. All required cells must be implemented before step 10 can declare completion.
|
||||
|
||||
## Handoff
|
||||
|
||||
Deliver the complete lowered fixture corpus, runtime helper inventory, explicit capability signatures, and source-to-operation mapping. Interpreter and native work can proceed in parallel once the applicable opcode contracts are stable.
|
||||
@@ -0,0 +1,79 @@
|
||||
# Step 04 — Execute the portable instruction set directly
|
||||
|
||||
Status: in progress; the [isolated verified-LIR engine](portable-execution.md) executes the current verifier-supported subset through `zi2zx run`. Full memory, host-capability, lifecycle/state and target integration remain required. Depends on [steps 02](02-lowered-ir-and-verifier.md) and [03](03-language-lowering.md). Next: [ZX container integration](05-zx-format-and-linking.md).
|
||||
|
||||
## Objective
|
||||
|
||||
Build a portable execution engine for the new lowered instructions. It is a
|
||||
semantic reference and an explicitly selected portable target. A host without
|
||||
native code generation may select it deliberately, but a failed native request
|
||||
must not select it automatically. It must not walk `.zir` expressions or
|
||||
reconstruct source statements during execution.
|
||||
|
||||
## Existing integration points
|
||||
|
||||
- [Host-value translation](../cmd/zir/zir_host_exec.c) and [the embedding API](../cmd/zir/zir_host.c).
|
||||
- [Portable execution contract](../docs/ZX.md).
|
||||
|
||||
Implemented module: `cmd/compiler_exec.zi`. Its immutable storage plan now keeps
|
||||
scalars in word slots and aliases a dead aggregate source to its `Insert` result
|
||||
only when a complete use count proves the source has no other consumer.
|
||||
Proposed additional modules: `cmd/compiler_exec_memory.zi` and
|
||||
`cmd/compiler_exec_host.zi`. Keep required embedding exports at the existing C
|
||||
API boundary. Current source/saved-IR and serialized-instruction tests cover
|
||||
scalar/aggregate operations, direct/indirect calls, instance globals, explicit
|
||||
frames, budgets and structured traps; they do not establish completion of every
|
||||
item below.
|
||||
|
||||
## Implementation work
|
||||
|
||||
- [x] Decode the current verified instruction subset once into a flattened,
|
||||
immutable execution plan with indexed word/byte slots, cached frame bases and
|
||||
pointer-based instruction/edge dispatch.
|
||||
- [ ] Extend arithmetic, memory, call and trap execution from the current
|
||||
verifier-supported subset to every required portable opcode.
|
||||
- [x] Implement word-backed scalar slots and fixed aggregate storage for the
|
||||
current logical layouts while preserving checked pointer provenance.
|
||||
- [ ] Add dynamic/heap aggregate storage, slices and the remaining memory forms
|
||||
(typed heap blocks through `resize` exist; address-table reuse does not);
|
||||
do not replace the language memory model with WebAssembly linear-memory rules.
|
||||
Checked borrowed slices and instance-owned host-returned byte storage are
|
||||
implemented; resizable owned collections and their cleanup remain open.
|
||||
- [x] Execute block-parameter transfers as parallel copies, using direct moves
|
||||
only when proven safe and scratch storage for overlap, swaps and cycles.
|
||||
- [x] Execute direct/indirect calls and recursion with owned frames and bounded
|
||||
work, fuel and frame limits for the current subset.
|
||||
- [ ] Complete owned-storage lifecycle, runtime global initialization, empty/null
|
||||
slices, vector cleanup and callback boundaries. Returned fixed aggregates and
|
||||
immutable string literal bytes/copies/count/data already execute on this path.
|
||||
Runtime initializers, empty/null slices and host-returned byte ownership are
|
||||
implemented per instance; vector cleanup and callback retirement remain open.
|
||||
- [ ] Adapt capability calls using validated typed signatures. Check host result shapes before writing them into execution storage; preserve nested host-to-bundle calls and reentrancy contracts.
|
||||
Scalar, structural byte-view and pointer-free record/fixed-array calls now use
|
||||
validated adapters. Nested host-to-bundle calls, reentrancy and native host
|
||||
trampolines remain open.
|
||||
- [ ] Specify and implement fuel at stable semantic checkpoints. Optimizations must preserve when exhaustion becomes observable, especially relative to host side effects and traps. Any batched charging requires a proof that timing is equivalent.
|
||||
- [ ] Implement portable SIMD lane behavior and legal parallel runtime operations without assuming native vector instructions or a host thread count.
|
||||
- [ ] Keep execution state, host bindings, error state, and mutable globals per instance. Exercise simultaneous instances, nested calls, replacement, and retirement.
|
||||
- [ ] Preserve snapshot/state migration semantics and library composition. Stable persistent identities must survive harmless instruction ordering changes without equating unrelated layouts.
|
||||
- [ ] Make debug stepping instruction-based with source mappings and inspectable value slots. Avoid debug-only execution semantics that hide release-mode defects.
|
||||
- [ ] Retain any existing `.zir` evaluator needed for compile-time execution, laws, or tooling until those consumers are deliberately migrated. Removing ZX dependence does not authorize deleting unrelated evaluator services.
|
||||
- [ ] Reject every unsupported portable opcode/capability with its stable Gap
|
||||
diagnostic before side effects. Do not invoke the old VM, native engine,
|
||||
generated C, or a target-specific helper to make the run appear successful.
|
||||
|
||||
## Tests
|
||||
|
||||
Add `tests/lowered_exec_cases.zi` and mutation/fault fixtures. Reuse [portable pointers](../tests/portable_pointers.sh), [portable records](../tests/portable_host_records.sh), [string cases](../tests/simd_string_cases.zi), and the retained portable cases under `tests/`.
|
||||
|
||||
Require the same results from source lowering, saved-IR lowering, encoded/decoded executable instructions, and the reference engine. Compare traps and host-call traces as well as final return values. Test allocation failures, malformed host responses, recursive callbacks, repeated failures, and cancellation/resource exhaustion without leaking instance state.
|
||||
|
||||
Run on the current machine and the required supported hosts; use private displays only where a host test actually needs them. Cross-compiled objects are not portable engine execution evidence.
|
||||
|
||||
## Exit gate
|
||||
|
||||
All required portable matrix cells run from lowered instructions with no executable `.zir` tree present. The engine rejects unverified programs and Gap operations without switching engines, preserves instance isolation and documented resource behavior, and can supply independent differential results for native backend development.
|
||||
|
||||
## Handoff
|
||||
|
||||
Deliver the engine API, portable opcode coverage table, executable fixtures, trap/side-effect traces, and state migration tests. Performance tuning of dispatch follows measurement and does not block the semantic reference from being useful.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Step 05 — Make ZX a versioned portable executable container
|
||||
|
||||
Status: in progress; the [revision-28 executable container](zx-executable-format.md) is the one `.zx` format. It stores verified LIR, runs stripped through the portable engine, and names its host capabilities, module globals and declarations in the host interface section; `ziran bundle`, `ziran run` and the embedding API use it. Library containers, partial composition and native variants remain open. Delivery order: [milestones](milestones.md) M1 and M3. Depends on [steps 02](02-lowered-ir-and-verifier.md)–[04](04-portable-instruction-engine.md). Next: [native code generation](06-optimization-and-native-backend.md).
|
||||
|
||||
## Objective
|
||||
|
||||
Replace embedded executable `.zir` with the lowered portable instruction program. Keep `.zx` responsible for executable code, linkage, capabilities, libraries, assets, variants, and inspection metadata. A stripped bundle must run without embedded source or semantic IR.
|
||||
|
||||
## Existing integration points
|
||||
|
||||
- [Container records and codec](../cmd/compiler_bundle.zi).
|
||||
- [Bundle linker](../cmd/compiler_link.zi), [bundle implementation](../cmd/compiler_bundle.zi), and [asset handling](../tests/bundle_assets.sh).
|
||||
- [Bundle command](../cmd/zi2zx/main.c), [package bundle execution](../cmd/package_bundle_run.zi), and [format documentation](../docs/ZX.md).
|
||||
- [Law checking](../cmd/compiler_law.zi) and [proof checking](../cmd/compiler_proof.zi).
|
||||
|
||||
Proposed modules: `cmd/compiler_exec_serial.zi`, `cmd/compiler_exec_link.zi`, and `cmd/compiler_exec_variants.zi`. Evolve the existing container owner instead of adding a competing bundle wrapper.
|
||||
|
||||
## Implementation work
|
||||
|
||||
- [ ] Define a new incompatible ZX revision with explicit section kinds, lengths, alignment, feature requirements, entry IDs, and deterministic ordering. Choose the revision from the live format history at implementation time.
|
||||
- [ ] Encode functions, blocks, values, instructions, types, relocatable symbolic constants, imports, exports, global initializers, and data without host pointer values or compiler struct layouts.
|
||||
Revision 28 already serializes ordered initializer IDs and readonly byte data;
|
||||
imports/exports, relocatable symbols and the public linked representation keep
|
||||
this container-wide item open.
|
||||
- [ ] Separate required execution sections from optional source maps, origins, optimization remarks, and original source attachments. Optional executable `.zir` must never be a hidden execution dependency.
|
||||
- [ ] Preserve asset streaming and binary bytes, deterministic output, write-to-pipe behavior, and existing error semantics. Validate offset/length arithmetic, overlaps, truncation, unsupported required features, and trailing data rules.
|
||||
- [ ] Lower then link executable symbols and portable type identities. Handle direct/indirect call roots, callbacks, exported layouts, global initialization, function/data address identity, and dead stripping conservatively.
|
||||
- [ ] Preserve external libraries, thin/add-on bundles, partial-module composition, and their resolution order. Detect duplicate/conflicting definitions and ABI/layout mismatches before instantiation.
|
||||
- [ ] Recompute capability requirements from verified reachable instructions. Cross-check declared tables, library bindings, and host signatures rather than trusting producer-supplied manifests.
|
||||
- [ ] Keep law evidence honest. Either revalidate attached proof material against an adequate non-executable witness or report producer evidence as unverified metadata. A checksum, previous checker flag, or matching law table is not a proof of lowering correctness.
|
||||
- [ ] Verify the executable itself independently of any optional proof/source section. Certificates for removed bounds checks or other privileged assumptions must be checkable by the consumer; otherwise retain the checks.
|
||||
- [ ] Define native variant records with target CPU, OS/ABI where relevant, required feature masks, common signature, and deterministic selection precedence. If no declared implementation matches the selected target/CPU contract, reject before execution; do not run portable code as a native fallback.
|
||||
- [ ] Keep generic executable code mandatory for portable bundles. Store native variants as verifiable target-operation/template metadata, not automatically trusted arbitrary machine-code blobs.
|
||||
- [ ] Validate variant operands, effects, register clobbers, and boundaries before code generation. Keep feature detection baseline-safe and check OS-enabled register state where required.
|
||||
- [ ] Define explicit target-only artifacts separately when a producer intentionally requires an architecture. The CLI must report that reduced portability and reject unsupported hosts before executing code.
|
||||
- [ ] Encode the stable Gap identifiers needed for target preflight and inspection.
|
||||
Unknown required target features reject; they do not select another executable
|
||||
section, format revision, or engine.
|
||||
- [ ] Reject old incompatible bundles with an actionable rebuild diagnostic. Keep legacy-format rejection tests; do not maintain two executable formats indefinitely.
|
||||
- [ ] Include every executable and variant section in cache/content identity while keeping optional debug-only changes from unnecessarily invalidating machine code where a correct split is possible.
|
||||
|
||||
## Tests
|
||||
|
||||
Extend the retained bundle checks: [provider cases](../tests/bundle_provider_cases.zi), [executable bundles](../tests/executable_bundle.sh), [global reachability](../tests/bundle_global_reachability.sh), and [step limits](../tests/bundle_step_limit.sh).
|
||||
|
||||
Add malformed new-section fixtures, required/optional feature mutations, variant incompatibility tests, stripped-bundle execution, deterministic source/saved-IR bytes, and proof-table tampering. Verify functionally identical portable behavior with supported variants selected, masked out, and unavailable.
|
||||
|
||||
## Exit gate
|
||||
|
||||
New bundles execute using step 04 without semantic `.zir` bodies. Libraries, assets, state, capabilities, law reporting, and diagnostics retain their defined behavior. Old bundles fail clearly. The writer and reader agree on a documented public instruction/container contract rather than private compiler serialization.
|
||||
|
||||
## Handoff
|
||||
|
||||
Deliver the binary/text format specification, opcode version policy, golden/mutation fixtures, variant contract, and the new bundler/loader path. Keep the installed default unchanged until step 10's integration gates pass.
|
||||
@@ -0,0 +1,63 @@
|
||||
# Step 06 — Optimize executable IR and implement the first native backend
|
||||
|
||||
Status: in progress; [verified scalar optimization](optimization-pipeline.md) and the machine-only native encoder ([README.md](README.md)). The [target-neutral machine IR](machine-ir.md) boundary, its verifier, deterministic liveness, linear-scan [register allocation](machine-ir.md#register-allocation) with splitting and spilling, a separate allocated-program verifier, and a [direct x86-64 machine-code encoder](machine-ir.md#machine-code-encoder) for verified allocated programs exist for Linux x86-64 SysV. `zx2native` uses that machine path exclusively; native ZX loading remains open. The implemented native call ABI passes and returns general-register values only: float, vector, aggregate and stack-passed call forms are [unsupported forms](machine-ir.md#supported-call-forms) rejected before encoding, not partially implemented. The full optimizer, the full SysV call ABI and external System V aggregate interoperability remain pending.
|
||||
|
||||
Direct native code here means Ziran's machine encoder writes machine code and the ELF executable from verified IR, without generated C, an assembler, a C compiler or a system linker. The C and Go targets also produce runnable binaries, but they are separate generated-code exporters with their own toolchains; they are never a fallback for an unsupported native form ([gap policy](gap-policy.md), [distinction](machine-ir.md#direct-native-code-versus-generated-code-exporters)). Depends on stable contracts from [steps 02](02-lowered-ir-and-verifier.md)–[05](05-zx-format-and-linking.md). Next: [target coverage](07-architecture-and-platform-coverage.md).
|
||||
|
||||
## Objective
|
||||
|
||||
The `zi2zx` CLI runs verified LIR optimization before writing portable ZX.
|
||||
Both native entry routes read and verify those bytes before selecting direct
|
||||
LIR or machine-IR target lowering. `--opt` selects optimized source inspection,
|
||||
not a second optimization pass on ZX input. `--emit wasm` lowers the same
|
||||
verified ZX to a wasm32 module, which `ziran build --target=wasm` and the
|
||||
bundle Wasm tier use. Source/debug origin attachments remain a gap.
|
||||
|
||||
Implement a native backend shared by standalone compilation and native ZX execution. Start with Linux x86-64 System V as the first execution milestone, then complete the required target matrix in step 07. A first working return-value executable is not completion of this step.
|
||||
|
||||
## Existing integration points
|
||||
|
||||
- [Scalar contracts](../cmd/zir/zir_scalar.h), [range-analysis behavior](../cmd/compiler_c_range.zi), and [SIMD behavior](../cmd/compiler_vector_x86.zi).
|
||||
- [Native planning](../cmd/compiler_machine_elf.zi).
|
||||
- [Existing Go assembly translator](../cmd/compiler_go_asm_x64.zi) for operand/ABI lessons only; Go ABI0 and its runtime assumptions are not Ziran's native ABI.
|
||||
- [Native and SIMD tests](../tests/simd_native.sh).
|
||||
|
||||
Implemented machine-IR modules: `cmd/compiler_machine_ir.zi`, `cmd/compiler_machine_lower.zi`, `cmd/compiler_machine_verify.zi`, `cmd/compiler_abi.zi` (the only module that names target registers), `cmd/compiler_regalloc.zi`, `cmd/compiler_machine_verify_allocated.zi`, and `cmd/compiler_x86_64.zi` with the shared byte encoders in `cmd/compiler_x86_bytes.zi`. Proposed: `cmd/compiler_opt.zi`.
|
||||
|
||||
## Implementation work
|
||||
|
||||
- [ ] Add a pass manager with explicit preconditions, preserved analyses, verification hooks, timing/counter collection, and deterministic before/after dumps.
|
||||
- [ ] Implement constant folding, copy propagation, unreachable-block removal, dead instruction elimination, and CFG simplification with exact numeric/effect semantics.
|
||||
- [ ] Add range propagation, redundant-check elimination, common subexpression elimination, and conservative load/store optimization. Invalidate facts on aliasing writes and effectful calls.
|
||||
- [ ] Implement inlining with recursion/growth limits, source-origin chains, and the existing `#inline`/`#cold` meaning. Include cross-module decisions in dependency/cache identities.
|
||||
- [ ] Add loop optimizations only when arithmetic, aliasing, exit, fuel, and trap conditions permit them. Do not treat signed overflow, float reassociation, or host side effects as compiler conveniences.
|
||||
- [ ] Lower to target instructions while retaining virtual registers. Model fixed registers, tied operands, condition flags, call clobbers, vector register classes, addressing modes, and literal pools explicitly.
|
||||
- [x] Implement liveness and a register allocator with splitting/spilling, call-aware live ranges, parallel-copy resolution, and deterministic output. Emit reasons and locations for every spill/reload. ([allocation](machine-ir.md#register-allocation), `tests/regalloc.sh`)
|
||||
- [x] Verify the allocated program: no overlapping live assignments, missing definitions, broken ties, clobbered live values, invalid register classes, or unresolved parallel copies. It also rejects unimplemented call forms and relocation addends the target cannot hold, so they never reach an encoder; allocation publishes only a verified program and leaves the owner's input intact on any failure.
|
||||
- [ ] Implement SysV argument/result classification, stack alignment, caller/callee-saved registers, aggregate passing, varargs, callbacks, indirect calls, and externally named symbols.
|
||||
- [ ] Generate prologues/epilogues, frame layout, unwind information, stack/resource checks, and target-correct returns. Keep source/inline locations through all inserted instructions.
|
||||
- [ ] Implement baseline scalar integer/float instruction selection first, then every required SIMD lane operation and supported CPU variant. Preserve a runnable baseline when optional features are unavailable.
|
||||
- [ ] Integrate typed native assembly operands and clobbers with allocation. Implement the supported GNU template/constraint surface or issue explicit unsupported-form diagnostics; never drop a selected assembly block silently.
|
||||
- [ ] Give separately selected portable and native implementations identical external semantics. Validate result/operand layouts; do not assume that an annotated template is proved equivalent merely because another body is checked. A missing native variant is a Gap error, not permission to execute the portable implementation.
|
||||
- [ ] Implement runtime calls and parallel-region helpers through the same typed ABI machinery, with stable entry points for the native engine.
|
||||
|
||||
## Tests
|
||||
|
||||
Add independent native-backend fixtures for register pressure, spills across calls, fixed-register division/shifts, flags, cyclic copies, float edge cases, stack alignment, aggregate ABI classes, varargs, and C callbacks.
|
||||
|
||||
Current machine-IR local tests: `tests/machine_ir_cases.zi` covers lowering, ABI constraints and malformed-MIR rejection. `tests/x86_encoder_cases.zi` covers exact encoded bytes, relocations, fuel and traps, and rejection of unsupported float and stack call forms and out-of-range global-address addends. `tests/regalloc.sh` covers allocation, the allocated verifier, incoming-argument order, and late failures that leave the owner's program intact. They use `--target=c` only to run the test programs.
|
||||
|
||||
Compare optimized/unoptimized new-native output with the portable instruction engine and existing C execution. Use external handwritten C/assembly ABI fixtures as independent callers/callees where practical. Inspect actual encoded instructions after step 08; text snapshots alone cannot validate encoding or execution.
|
||||
|
||||
Run all builds through `build-queue --`. Performance measurements occur only
|
||||
directly on Alpha's physical host, with raw samples and the repository's
|
||||
symmetric 1.5×IQR rule. Reject virtualization and leave measurements pending
|
||||
when Alpha is unavailable rather than substituting another host.
|
||||
|
||||
## Exit gate
|
||||
|
||||
All required Linux x86-64 feature cells execute with the new backend. Debug/release, source/saved IR, standalone/native ZX entry adapters, callbacks, SIMD, and spill-heavy code agree with their independent expectations. Optimization diagnostics identify which pass changed code and why. Any remaining provisional assembler/linker dependency is explicitly temporary until step 08.
|
||||
|
||||
## Handoff
|
||||
|
||||
Deliver shared machine/ABI interfaces, the complete first-target implementation, allocation verifier, target fixture corpus, and optimization remarks. Freeze common backend contracts before parallel target implementation to avoid competing register/ABI models.
|
||||
@@ -0,0 +1,146 @@
|
||||
# Step 07 — Complete architecture, ABI, and platform coverage
|
||||
|
||||
Status: planned. Depends on [step 06](06-optimization-and-native-backend.md). Coordinates with [encoding/linking](08-assembler-objects-and-linker.md) and [runtime integration](09-native-runtime-and-integration.md).
|
||||
|
||||
## Objective
|
||||
|
||||
Run one portable executable program across the maintained platform matrix while allowing explicit CPU variants. Match existing promised coverage rather than declaring a Linux-only backend to be the completed ZX upgrade.
|
||||
|
||||
## Existing integration points
|
||||
|
||||
- [Wasm lowering of verified ZX](../cmd/compiler_zx_wasm.zi) and [wasm bundle integration](../cmd/zir/zir_zx_wasm.c).
|
||||
- [Browser execution integration](../cmd/zir/zir_zx_wasm_web.c).
|
||||
- [Target diagnostics](../tests/target_diagnostics.sh), [ARM/CPU feature tests](../tests/assembly_features.sh), and [wasm tests](../tests/zx_wasm.sh).
|
||||
- [Platform and runtime coverage documentation](../docs/IMPLEMENTATION_STATUS.md).
|
||||
|
||||
Proposed modules: `cmd/compiler_target.zi`, `cmd/compiler_aarch64.zi`, `cmd/compiler_arm.zi`, `cmd/compiler_wasm.zi`, and platform-specific ABI modules under `cmd/`. Keep target tables explicit and dynamically sized where appropriate.
|
||||
|
||||
## Implementation work
|
||||
|
||||
- [ ] Establish exact target triples, pointer widths, endianness, data models, object formats, stack rules, symbol rules, and feature baselines from the step-01 matrix.
|
||||
- [ ] Implement AArch64 instruction selection, calling conventions, stack frames, relocatable addresses, NEON operations, literal placement, branch ranges, and platform-reserved registers.
|
||||
- [ ] Implement the maintained 32-bit ARM target: ARM/Thumb policy, instruction availability, 64-bit scalar operations, soft/hard-float ABI distinctions, alignment, NEON variants, interworking, and veneers.
|
||||
- [ ] Complete x86-64 Windows and macOS ABI differences, including Windows shadow space/unwind requirements and platform-specific symbol/TLS/layout rules. Include additional x86 platform rows only where the matrix requires them.
|
||||
- [ ] Complete Apple ARM64 rules, Android ABI/API requirements, TLS, dynamic loading, instruction-cache synchronization, and platform limits on executable memory.
|
||||
- [ ] Add required 32-bit x86 support if current maintained targets promise it; do not hide a missing target behind the x86-64 implementation. New RISC-V support is separately scoped unless explicitly included in step 01.
|
||||
- [ ] Lower the same portable IR directly to WebAssembly instructions, function tables, structured control flow, data, imports, and exports. Preserve numeric traps/conversions and the declared memory model at the wasm boundary.
|
||||
- [ ] Support browser AOT generation and the portable instruction engine when runtime native compilation is unavailable. Do not keep generated C/Emscripten as the hidden code generator for the new ZX instruction path.
|
||||
- [ ] Implement baseline and optional SIMD modes, including legal wider-vector decomposition. Match lane results with the portable engine; explicit native variants select only on compatible CPUs/OS state.
|
||||
- [ ] Centralize feature discovery and target requirement matching. Cross-compilation must use the requested target description, never the build machine's CPU flags.
|
||||
- [ ] Keep OS APIs in typed host capabilities or native foreign adapters. A Windows/Linux/macOS service binding is distinct from AVX/NEON instruction availability.
|
||||
- [ ] Define exact failures for absent host facilities, unavailable executable memory, missing CPU requirements, unsupported native extensions, and unavailable platform toolchains.
|
||||
- [ ] Supply unwind/debug mappings and profiler registration hooks for every native target, not just Linux x86-64.
|
||||
|
||||
## Target registry and preflight
|
||||
|
||||
[`cmd/compiler_target.zi`](../cmd/compiler_target.zi) holds the registry: one
|
||||
row for every CPU/OS pair `TargetDescribe` accepts, each with exactly one
|
||||
gap-policy state, its implemented CPU features and OS services, and the
|
||||
milestone that closes it. `TargetPreflight` checks a target description and
|
||||
its `TargetRequirements` (CPU features, OS services) against that row; only an
|
||||
Implemented row passes. `ziran capabilities --json` prints the registry as
|
||||
`assembly_targets`, and `ziran capabilities --assembly-target=ROW[+FEATURE...]
|
||||
[--os-service=NAME]... [INPUT...]` runs the preflight before any input is read.
|
||||
|
||||
| Row | ABI | State | Diagnostic | Milestone |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `x86_64-linux` | SysV | Gap | `assembly.gap.target-unimplemented` | M2–M3 |
|
||||
| `x86_64-android` | SysV | Gap | `assembly.gap.target-unimplemented` | M4 |
|
||||
| `x86_64-windows` | Win64 (kernel32 boundary only) | Gap | `assembly.gap.target-unimplemented` | M5 |
|
||||
| `x86_64-macos` | Apple64 | Gap | `assembly.gap.target-unimplemented` | M5 |
|
||||
| `armv7-linux`, `armv7-android` | AAPCS32 | Gap | `assembly.gap.target-unimplemented` | M4 |
|
||||
| `aarch64-linux`, `aarch64-android` | AAPCS64 | Gap | `assembly.gap.target-unimplemented` | M4 |
|
||||
| `aarch64-windows` | Win64 | Gap | `assembly.gap.target-unimplemented` | M5 |
|
||||
| `aarch64-macos` | Apple64 | Gap | `assembly.gap.target-unimplemented` | M5 |
|
||||
| `wasm32-browser`, `wasm32-wasi` | Wasm | Gap | `assembly.gap.target-unimplemented` | M4 |
|
||||
|
||||
No general registry row is Implemented yet. Linux x86-64 machine IR,
|
||||
allocation, encoding and opt-in ELF output exist, but the native ZX loader and
|
||||
runtime cutover are open, so that row stays a Gap until its M2–M3 gate passes; a partial stage
|
||||
such as `TargetMachineLoweringSupported` never implements a row. The
|
||||
`zx2native --target ARCH --platform OS`
|
||||
selector implements the rows whose registry entry names an `executable`
|
||||
container: `x86_64-linux` writes an ELF and `x86_64-windows` a PE32+ `.exe`
|
||||
([`compiler_machine_pe.zi`](../cmd/compiler_machine_pe.zi)). A Linux
|
||||
registration may also name an `ar(1)` archive of ELF64 x86-64 objects; the
|
||||
executable links the members its capabilities reach and stays static
|
||||
([`compiler_x86_archive.zi`](../cmd/compiler_x86_archive.zi)), and anything
|
||||
outside that subset is `assembly.gap.machine-archive` naming the capability,
|
||||
member and symbol. Both carry the
|
||||
same text, constants and data
|
||||
([`compiler_x86_image.zi`](../cmd/compiler_x86_image.zi)) and runtime
|
||||
([`compiler_x86_runtime.zi`](../cmd/compiler_x86_runtime.zi)), whose only
|
||||
per-OS parts are its primitives: Linux system calls, or kernel32 calls through
|
||||
the image's IAT with Win64 shadow space, 16-byte alignment and volatile
|
||||
registers ([`compiler_x86_win64.zi`](../cmd/compiler_x86_win64.zi)). Code
|
||||
inside the program keeps the Ziran-internal convention on both. The PE imports
|
||||
only what its runtime calls, is DYNAMIC_BASE/HIGH_ENTROPY_VA with base
|
||||
relocations for the pointer runtime's addresses and NX_COMPAT, and commits an
|
||||
8 MiB stack, so frames need no probes; every function with a prologue carries
|
||||
x64 unwind data (.pdata and .xdata), and a console gets each line once it ends
|
||||
where a redirected descriptor gets whole buffers. Both images also supply the
|
||||
ZX Runner's file and clock services themselves
|
||||
([`compiler_x86_host.zi`](../cmd/compiler_x86_host.zi)): a program that imports
|
||||
`FileStatusHost`, `FileReadHost`, `FileWriteHost`, `FileRemoveHost`,
|
||||
`FileRenameHost`, `DirectoryMakeHost`, `DirectoryListHost`,
|
||||
`MonotonicNanosecondsHost` or `WallMillisecondsHost` with the signatures
|
||||
`std/guest_files.zi` and `std/guest_clock.zi` declare gets a veneer after the
|
||||
library ones instead of a host-capability gap. The linker keeps these apart
|
||||
from library imports, so the ELF stays static and the PE imports only what its
|
||||
veneers call. Linux veneers make the system calls directly with the path in a
|
||||
4 KiB stack slot; Windows veneers widen UTF-8 paths to UTF-16 with
|
||||
`MultiByteToWideChar`, convert listed names back with `WideCharToMultiByte`,
|
||||
and import `GetFileAttributesExW`, `CreateFileW`, `ReadFile`, `WriteFile`,
|
||||
`DeleteFileW`, `MoveFileExW`, `CreateDirectoryW`, `FindFirstFileW`,
|
||||
`FindNextFileW`, `FindClose`, `QueryPerformanceCounter`,
|
||||
`QueryPerformanceFrequency` and `GetSystemTimeAsFileTime` as needed. A read
|
||||
or a listing grows a heap block through the runtime's resize entry, at least
|
||||
doubling it, and shrinks it to the final length; the block stays allocated.
|
||||
The built-in veneers carry no unwind records, since the unwind writer covers
|
||||
the program's own functions only. Every other described row
|
||||
fails before input/output with
|
||||
`assembly.gap.machine-platform-service-unavailable` because it has no
|
||||
executable writer or process-entry/`write_all`/exit runtime. Once a registry row
|
||||
is Implemented, a CPU feature it does not implement (including another
|
||||
family's, such as `neon` on x86-64) fails with `assembly.gap.cpu-feature`,
|
||||
and a missing OS service (`process-entry`, `executable-memory`, `threads`,
|
||||
`files`, `clock`, `dynamic-library`) fails with `assembly.gap.os-service`;
|
||||
the row check comes first. Typed host capabilities and read-only data keep
|
||||
their own `assembly.gap.*` codes. General registry preflight is reached through
|
||||
`ziran capabilities`.
|
||||
[Target diagnostics](../tests/target_diagnostics.sh) check every row, code,
|
||||
and source/saved-IR rejection; [machine IR cases](../tests/machine_ir_cases.zi)
|
||||
check registry coverage and every state.
|
||||
|
||||
## Execution matrix and tests
|
||||
|
||||
For every required CPU/OS/ABI row, record:
|
||||
|
||||
| Evidence | Required outcome |
|
||||
| --- | --- |
|
||||
| Source and saved `.zir` | Equivalent lowered instructions and behavior |
|
||||
| Same portable `.zx` bytes | Successful supported execution across applicable hosts |
|
||||
| Native AOT | Real executable launch, correct ABI interactions, expected results |
|
||||
| Native ZX or documented interpreter-only host | Correct loader/capability/state behavior |
|
||||
| CPU features enabled and masked | Correct declared-variant dispatch; stable preflight error when no implementation matches |
|
||||
| Debug/unwind/profile data | Correct function and source attribution |
|
||||
| Negative target cases | Clear diagnostics before invalid execution |
|
||||
|
||||
Run semantic tests under emulation when useful and on real hardware where ABI, OS integration, or CPU feature behavior requires it. Test phones on the owner-authorized USB Moto; preserve Wireless Debugging. GUI tests use private displays and only their own processes.
|
||||
|
||||
Emulation, cross-compilation, a lower-feature implementation, or another engine
|
||||
does not close the selected target/feature cell. Missing target hardware leaves
|
||||
the cell Unknown; missing implementation leaves it Gap.
|
||||
|
||||
Benchmarks run directly on Alpha's physical host only; the runner rejects
|
||||
virtualization. Emulated correctness results are not native performance
|
||||
measurements. If a required host is unavailable, retain its matrix cells as
|
||||
incomplete rather than reporting 100% coverage.
|
||||
|
||||
## Exit gate
|
||||
|
||||
Every required row has execution evidence and every opcode has either correct target lowering or a documented portable implementation. The same portable bundle does not require platform-specific rebuilding to execute its baseline behavior. Platform-specific variants and capabilities remain explicit.
|
||||
|
||||
## Handoff
|
||||
|
||||
Deliver target tables, ABI/encoding requirements, cross-platform fixtures, hardware limitations, and execution receipts to steps 08–10. Do not infer a platform passed merely because another platform uses the same CPU family.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Step 08 — Encode instructions, write objects, and link executables directly
|
||||
|
||||
Status: in progress; [direct Linux x86-64 ELF with scalar/aggregate code and static data](README.md). Relocatable objects and a general native linker remain pending. Depends on machine/target contracts from [steps 06](06-optimization-and-native-backend.md) and [07](07-architecture-and-platform-coverage.md).
|
||||
|
||||
## Objective
|
||||
|
||||
Complete the path from allocated machine instructions to native binaries without generated C, an external assembler, or an external linker on required targets. Keep optional external-tool comparison modes for validation, not as an undeclared dependency of the promised direct build.
|
||||
|
||||
## Existing integration points
|
||||
|
||||
- [Current C executable driver](../cmd/zi2c/main.c) and [build orchestration](../cmd/compiler_c_backend.zi) provide entry, diagnostics, cache, and failure-preservation behavior to retain.
|
||||
- [Native entry tests](../tests/native_entry.sh) and [link-flag tests](../tests/native_link_flags_cases.zi) provide existing executable/FFI expectations.
|
||||
- [Build rules](../Makefile) and [native runtime build selection](../assembly.mk).
|
||||
|
||||
Proposed modules: `cmd/compiler_encode_x86.zi`, `cmd/compiler_encode_arm.zi`, `cmd/compiler_encode_aarch64.zi`, `cmd/compiler_object.zi`, `cmd/compiler_elf.zi`, `cmd/compiler_coff.zi`, `cmd/compiler_macho.zi`, `cmd/compiler_link_native.zi`, and `cmd/compiler_disassemble.zi`.
|
||||
|
||||
## Implementation work
|
||||
|
||||
- [ ] Implement instruction encoding for every emitted opcode and addressing form, including immediate widths, extension prefixes, branch displacement, vector encodings, and target feature validation.
|
||||
- [ ] Define symbolic fixups independently of object format. Resolve local labels, literal pools, branch relaxation, long-branch veneers, alignment, and padding to a stable final layout.
|
||||
- [ ] Print assembly directly from the same allocated/finalized instruction records used by the encoder. Annotate function, source origin, bytes, CPU requirements, stack offsets, and generated instructions.
|
||||
- [ ] Provide a reader for the emitted textual listing that reconstructs its supported instruction/directive subset. This enables round-trip inspection without requiring text parsing during ordinary compilation. Do not silently imply support for every external assembler dialect.
|
||||
- [ ] Keep existing user `#asm` syntax support a separate compatibility task: parse and bind the supported templates and constraints, including labels/directives where allowed. On the direct assembly target, require a matching declared target/feature implementation and issue a stable diagnostic when absent; do not execute the portable body or invoke another backend.
|
||||
- [ ] Write relocatable ELF, COFF, and Mach-O objects for required rows. Include text/data/readonly/BSS/TLS sections, symbols, visibility, alignment, relocations, unwind records, and debug references.
|
||||
- [ ] Implement archive reading and symbol extraction, COMDAT/coalescing rules where required, weak symbols, unresolved references, duplicate definitions, section garbage collection, and retained exports/callback roots. Landed slice: a `NAME.library` registration may name an `ar(1)` archive of ELF64 x86-64 objects ([`compiler_x86_archive.zi`](../cmd/compiler_x86_archive.zi)); the reached members' text, read-only data, writable data, zero fill, GOT entries and relocations go into the static Linux ELF and each capability's veneer calls its member directly. Anything outside that subset (TLS, `init_array`, an undefined or duplicate symbol, an unsupported relocation) is the stable `assembly.gap.machine-archive` diagnostic naming the capability, the member and the symbol.
|
||||
- [ ] Link supported executable/shared-object forms: ELF program headers and dynamic records, PE imports/exports and relocation tables, and Mach-O load commands/fixups as required by the maintained targets.
|
||||
- [ ] Implement startup/entry handling and runtime helper linkage for console programs and libraries. Preserve command arguments, exit status, global initialization, thread/runtime setup, and foreign callbacks.
|
||||
- [ ] Resolve ordinary OS and third-party libraries through explicit target search paths and format-aware symbol handling. Existing compiled foreign libraries are valid inputs; compiling their C sources is outside Ziran code generation.
|
||||
- [ ] Inventory C-compiler-driver conveniences previously supplied by `CC`: CRT selection, sysroot, libc, dynamic loader, TLS, compiler support routines, and default libraries. Replace each with explicit native driver configuration and diagnostics.
|
||||
- [ ] Define the supported native link-option surface. Preserve C-target pass-through options on the C backend; reject options that have no new-native equivalent instead of ignoring them.
|
||||
- [ ] Implement platform-required executable authentication/signing integration where needed for a runnable artifact. Use installed OS signing facilities and explicit credentials; do not claim that a written Mach-O/PE file alone proves launchability.
|
||||
- [ ] Write outputs atomically, preserving the last valid executable on failure. Cache object contributions using target, ABI, backend, flags, dependencies, and runtime identities.
|
||||
- [ ] Produce relocation/link maps, section sizes, resolved symbol addresses, inserted stubs, padding, and a source-linked disassembly from actual final bytes.
|
||||
- [ ] Expose the same encoder and relocation primitives to the in-memory loader in step 09; do not create an unrelated JIT instruction encoder.
|
||||
|
||||
## Tests
|
||||
|
||||
Add Ziran encoding/object/linker test programs. Compare individual instruction bytes against an independent assembler/disassembler; test boundary immediates, all register forms, branch expansion, relocation overflow, and malformed input objects.
|
||||
|
||||
Round-trip the supported listing form through parsing/encoding and compare resulting sections and fixups. Link new-native objects with independently compiled C callers/callees and, where useful, the system linker as a reference. Then run the fully internal link path with external C compiler, assembler, and linker commands unavailable.
|
||||
|
||||
Exercise executable launch, dynamic imports, TLS, callbacks, shared libraries, debug/unwind loading, missing symbols, archive ordering, failed writes, and preservation of installed outputs on each required OS. Run all builds through `build-queue --`; use private display fixtures where needed.
|
||||
|
||||
## Exit gate
|
||||
|
||||
Required standalone builds produce runnable binaries using the internal code generator, encoder, object writer, and linker. Listings match the encoded instruction stream; final disassembly accounts for linker-added code. No external-tool or alternate-engine fallback exists on the direct path; a missing internal facility is a visible Gap.
|
||||
|
||||
## Handoff
|
||||
|
||||
Deliver encoded-image APIs, relocations, link maps, independent byte/ABI fixtures, platform signing requirements, and final byte-to-source mappings to steps 09–10.
|
||||
@@ -0,0 +1,138 @@
|
||||
# Step 09 — Integrate native ZX execution, AOT builds, caching, and hosts
|
||||
|
||||
Status: in progress. Linux x86-64 has an AOT slice and native ZX loading,
|
||||
and Linux AArch64, Android included, has native ZX loading; `ziran run
|
||||
app.zx` and the embedding API use it by default on those rows,
|
||||
with the engine's pointer checks; a persistent code cache, the element-type
|
||||
check on pointer access and the remaining targets are still planned. The current startup/syscall work is not a completion claim. Depends on
|
||||
[steps 04](04-portable-instruction-engine.md)–[08](08-assembler-objects-and-linker.md).
|
||||
Next: [inspection and final cutover](10-inspection-performance-and-cutover.md).
|
||||
|
||||
## Objective
|
||||
|
||||
Run `.zx` through the explicitly selected shared native backend or explicitly
|
||||
selected new instruction interpreter. Integrate source builds, packages,
|
||||
libraries, hosts, cache, and embedding APIs without relying on generated C for
|
||||
new-native code generation and without switching engines after a gap is found.
|
||||
|
||||
The experimental pipeline is source → `.zir` → linked LIR → verify →
|
||||
LIR optimization → portable ZX bytes → verified read, followed by either the portable interpreter or direct target
|
||||
lowering to a platform binary. Generated C and Go routes can also produce
|
||||
binaries through their own toolchains, but they are not native here and cannot
|
||||
substitute for the direct route.
|
||||
|
||||
Host capabilities remain portable typed interfaces. Each direct target owns
|
||||
separate ABI veneers for entry, calls, operating-system services, and exit. The
|
||||
initial Linux x86-64 console contract uses a static executable with its own
|
||||
`_start`, no libc/CRT/dynamic linker, `write` syscall 1 through a `write_all`
|
||||
loop that handles partial progress and `EINTR`, and `exit_group` syscall 231
|
||||
rather than syscall 60. That opt-in AOT slice is implemented and executed.
|
||||
A program that calls host capabilities links them instead from registered host
|
||||
libraries by name: PT_INTERP and PT_DYNAMIC name the system dynamic linker and
|
||||
each library, one System V veneer per capability
|
||||
([`compiler_x86_host.zi`](../cmd/compiler_x86_host.zi)) calls through the slot
|
||||
its GLOB_DAT relocation fills, and the process entry, console and exit stay
|
||||
Ziran's own.
|
||||
Standard output is buffered, 8 KiB at a time and line by line on a terminal as
|
||||
in C, and written before any write to another descriptor, before a trap's exit
|
||||
and at exit, so its bytes and their order match direct writes. Its resize runtime, emitted with the x86 encoder
|
||||
([`compiler_x86_runtime.zi`](../cmd/compiler_x86_runtime.zi)), recycles freed
|
||||
blocks through power-of-two size classes instead of mapping and unmapping each
|
||||
growth; a block over 1 MiB is its own mapping and grows by `mremap`.
|
||||
|
||||
Native ZX loading on linux-x86_64, linux-aarch64 and linux-armv7
|
||||
([`zir_host_native.c`](../cmd/zir/zir_host_native.c), with each architecture's
|
||||
veneers and relocation fields in `zir_host_native_<arch>.c`; ARMv7's also
|
||||
hold the 64-bit divide and int64/float conversion helpers A32 lacks)
|
||||
compiles the bundle's verified program with the same machine pipeline, copies
|
||||
the image into RW pages, resolves its relocations against the instance's own
|
||||
data, host veneers, trap stub and resize runtime, and only then makes the code
|
||||
RX; no mapping is ever writable and executable. Compiled code is shared by
|
||||
open bundles of the same content digest on the same CPU and kept briefly
|
||||
after the last closes. Each instance owns its globals, fuel counter, stack
|
||||
limit and resizable storage. A trap returns through `longjmp`, prints a
|
||||
`zx.runtime` diagnostic naming the function, block and (with a debug
|
||||
attachment) source line, and ends that instance; nothing restarts on the
|
||||
engine.
|
||||
|
||||
With checks on, native data pointers are checked as the engine checks them
|
||||
(checks are opt-in with `#checks`). A pointer is a
|
||||
token naming a slot of the instance's pointer table, version and offset; every
|
||||
load, store, byte comparison and platform-service argument resolves it
|
||||
against a live slot of the same version, within its size and, for writes,
|
||||
writable. Each run of `allocate` takes fresh zeroed bytes from the frame arena
|
||||
under a slot on the frame's chain, and `Return` ends the chain and gives the
|
||||
arena back. `resize` ends the old block's slot once the runtime has moved or
|
||||
freed it; a request that does not fit gives null and keeps the old block.
|
||||
Globals are slots 1..G, read-only ones without the writable flag. The host
|
||||
bridge resolves the views it copies and gives returned views read-only slots.
|
||||
The engine also checks a pointer's element type on each access; native code
|
||||
does not yet.
|
||||
|
||||
`ziran build FILE.zi` composes `zi2zx` and `zx2native`, so source-native output
|
||||
serializes and reads the same ZX image as direct `zx2native`; neither route
|
||||
lowers source-side LIR directly. The required payload is stripped of source
|
||||
origins; `zi2zx --debug` writes them to the optional debug attachment, bound
|
||||
to the program section's identity, and `zx2native --emit map` names source
|
||||
lines from it without changing a byte of the executable. Bundles and the
|
||||
bundle Wasm tier use this shared instruction route.
|
||||
|
||||
For literal-only hello, direct instruction selection emits no stack frame or
|
||||
spill slots, uses short constants, and writes the literal from read-only data.
|
||||
The ELF file places `.rodata` immediately after `.text`, with congruent file
|
||||
offsets and virtual addresses on distinct RX/R pages, and carries `.data` only
|
||||
as a zero-length section header when no writable storage exists. `_start` and
|
||||
each function's symbol retain positive bounded text extents;
|
||||
inlined platform service declarations are omitted from the symbol table,
|
||||
so the static executable has no undefined symbols or misleading trap aliases.
|
||||
|
||||
## Existing integration points
|
||||
|
||||
- [Embedding API](../include/ziran_host.h), [bundle lifecycle](../cmd/zir/zir_host.c) and the [engine bridge](../cmd/zir/zir_host_exec.c), which translates host values for the [portable instruction engine](../cmd/compiler_exec.zi) and for the [native ZX loader](../cmd/zir/zir_host_native.c).
|
||||
- [Wasm lowering](../cmd/compiler_zx_wasm.zi) and [browser integration](../cmd/zir/zir_zx_wasm_web.c).
|
||||
- [Package entry](../cmd/package_entry.zi), [options](../cmd/package_options.zi), [bundle run](../cmd/package_bundle_run.zi), and [capability reporting](../cmd/package_capabilities.zi).
|
||||
|
||||
Proposed modules: `cmd/compiler_native_load.zi`, `cmd/compiler_native_cache.zi`, `cmd/compiler_exec_instance.zi`, and a native backend command entry integrated into the existing package driver.
|
||||
|
||||
## Implementation work
|
||||
|
||||
- [ ] Expose one compile API taking verified executable IR, target description, optimization policy, and runtime ABI. AOT objects and in-memory images differ in output handling, not instruction semantics.
|
||||
- [ ] Implement in-memory layout, symbol resolution, relocations, executable-memory allocation, write/execute transitions, instruction-cache synchronization, unwind registration, and teardown for supported platforms.
|
||||
- [ ] Do not trust persisted executable bytes solely because a neighboring metadata file claims they were verified. Define cache integrity, ownership, atomic installation, invalidation, and refusal behavior explicitly.
|
||||
- [ ] Key cache entries by executable content, linked libraries, target/ABI, actual selected CPU features, backend/runtime identities, optimization settings, and instrumentation semantics. Keep mutable instance state outside cached code.
|
||||
- [ ] Preserve concurrent compilation, concurrent instantiation, nested calls, independent globals, reentrant host capabilities, cancellation, failures, and lifecycle retirement. Cache cleanup must not unload code still referenced by a live instance.
|
||||
- [ ] Implement typed host trampolines using the shared ABI layer. Preserve aggregate/string/slice/function signatures, checked host returns, error propagation, and callback roots.
|
||||
- [x] Implement and verify the first target-owned console ABI veneer for the
|
||||
opt-in Linux x86-64 AOT path. Its Ziran-owned formatter accepts literal
|
||||
format strings, strings/text views, booleans, every fixed signed and unsigned
|
||||
integer width, and `%%`; `write_all` retries partial progress and `EINTR`.
|
||||
Floating-point formatting and every unavailable target service remain stable
|
||||
named gaps. Other target rows remain unchecked.
|
||||
- [ ] Preserve execution budgets, stack checks, source-aware traps, parallel workers, persistent state, migration, snapshots, and module/library initialization across native and interpreted modes.
|
||||
- [ ] Make the engine-selection contract explicit. A native request fails
|
||||
clearly if unsupported and never starts the interpreter. A portable request
|
||||
never executes native code. A command may have one documented default, but
|
||||
preflight failure never changes that selection.
|
||||
- [ ] Add direct-native build/run targets to the package driver and target capability reports. Keep existing C/Go/wasm commands and legitimate target-specific bindings usable.
|
||||
- [ ] Integrate package dependency recipes, native artifact caching, sysroots, host providers, assets, executable entries, libraries, install paths, and incremental rebuild dependencies.
|
||||
- [x] Replace the browser's generated-C bundle compilation path with direct wasm output from the same portable IR. Interpreter execution remains an explicit separate mode where browser/runtime policy permits it, never a direct-Wasm fallback.
|
||||
- [ ] Build runtime helpers through the new backend and verify self-hosting of the new compiler modules. Retain the established bootstrap mechanism; regeneration must be deterministic and locally checked.
|
||||
- [x] Remove TinyCC and generated-C dependencies from the new native ZX path after their replacement tests pass. Remove build/library dependencies only when no other maintained consumer needs them. TinyCC, the generated-C ZX route and `libziran-vm.a` are gone.
|
||||
- [x] Reconcile embedding API changes deliberately. Preserve semantic contracts, update callers through their owning projects, and reject retired entry points where repository policy requires a clean cutover. `BundleUsePortableVm` and `BundleInstantiatePortable` are deleted; Kryon calls neither.
|
||||
- [ ] Verify installation from the current working tree at the stable executable path. Do not require a commit first, replace the owner's running application, or produce alternate task-specific binaries.
|
||||
|
||||
## Tests
|
||||
|
||||
Extend [native run](../tests/native_run.sh), [portable entry](../tests/portable_entry.sh), [bundle providers](../tests/bundle_provider_cases.zi), [cache tests](../tests/native_cache.sh), [object reuse](../tests/native_object_reuse_cases.zi), [build concurrency](../tests/native_cache_parallel.sh), [browser lifecycle](../tests/zx_web_lifecycle.sh), and [install tests](../tests/install_user_cases.zi).
|
||||
|
||||
Add cold/warm cache correctness, interrupted writes, incompatible CPU cache reuse, stale runtime ABI, corrupted entries, load/unload races, nested host callbacks, parallel failure, and mutable-state separation. Test from stripped bundles with no C compiler available. Run independent native AOT and native ZX instances against the same fixture expectations.
|
||||
|
||||
Use the full native local stack. All builds go through `build-queue --`; tests remove inherited display variables or use private displays. Dedicated performance measurement belongs on Alpha, not the desktop.
|
||||
|
||||
## Exit gate
|
||||
|
||||
The new-native standalone and ZX paths share code generation and encoding, all required hosts/packages work, cold/warm execution is correct, and current-tree installation is verified. No AST, generated-C or interpreter fallback remains on a path advertised as the new native engine. Every required downstream gap has a stable error and remains incomplete until implemented and executed.
|
||||
|
||||
## Handoff
|
||||
|
||||
Deliver API/CLI behavior, cache/runtime identities, lifecycle tests, package/host integration evidence, installed-path verification, and remaining platform limitations for final inspection and cutover.
|
||||
@@ -0,0 +1,70 @@
|
||||
# Step 10 — Complete inspectability, validate performance, and cut over
|
||||
|
||||
Status: in progress; [lowered instruction dumps, optimization counters and bounded native byte-range maps](README.md). Complete pipeline inspection, profiling, performance validation and cutover remain pending. Depends on all preceding steps. This is the only step that may declare the complete upgrade finished.
|
||||
|
||||
## Objective
|
||||
|
||||
Make bottlenecks traceable from source to executed instructions, validate the complete feature/platform matrix, replace the old ZX execution contract, and install the locally verified toolchain. Inspection functionality is developed alongside steps 02–09; it is not postponed until this final gate.
|
||||
|
||||
## Existing integration points
|
||||
|
||||
- [Inspection command](../cmd/inspect.zi), [compiler profiling](../cmd/zir/zir_profile.h), and [package explain](../cmd/package_explain.zi).
|
||||
- [Compiler command](../cmd/package_entry.zi), [compile-command reporting](../cmd/package_compile_commands.zi), and [feature reporting](../cmd/package_features.zi).
|
||||
- [Check discovery](../tests/check_plan.zi), [build/test rules](../Makefile), and [benchmark instructions](../bench/README.md).
|
||||
- [Architecture](../docs/ARCHITECTURE.md), [ZIR](../docs/ZIR.md), [ZX](../docs/ZX.md), [usage](../docs/USAGE.md), and [implementation status](../docs/IMPLEMENTATION_STATUS.md).
|
||||
|
||||
Proposed modules: `cmd/compiler_inspect_exec.zi`, `cmd/compiler_debug_map.zi`, and `cmd/compiler_profile_native.zi`. Final CLI spellings are implementation decisions; document them as proposed until they actually exist.
|
||||
|
||||
## Inspectability deliverables
|
||||
|
||||
- [ ] Provide deterministic dumps for ZIR, initial portable IR, optimized portable IR, selected machine IR, allocated machine IR, assembly, object metadata, link map, and final executable disassembly.
|
||||
- [ ] Map source spans and inline/generic origin chains to instructions, addresses, symbols, and stack locations. Preserve many-to-many mappings when optimization combines or duplicates operations.
|
||||
- [ ] Explain eliminated checks, folded expressions, inlining decisions, missed vectorization, dispatch selection, spills/reloads, frame sizes, call sites, and linker-generated stubs/padding.
|
||||
- [ ] Produce human-readable output and structured JSON for each stage. Large programs support bounded function/block/address selection; tools must not require dumping an entire binary to inspect one function.
|
||||
- [ ] Keep assembly/listing output tied to the actual encoder and final disassembly tied to actual bytes, including relocated addresses. Label estimated costs separately from measured costs.
|
||||
- [ ] Generate source/line and unwind metadata suitable for platform debuggers and profilers. Register JIT functions and address ranges where supported, unregister on retirement, and keep sampled addresses attributable after code moves/unloads.
|
||||
- [ ] On Linux, integrate available `perf`/JIT symbol-map facilities; supply the corresponding supported mechanisms on other maintained platforms. Record missing hardware counters explicitly rather than fabricating cycle data.
|
||||
- [ ] Attribute samples to functions, instructions, inline frames, CPU variants, and host bridges. Report hot-path execution, spills, cache/branch evidence, and host-call overhead only when measured data supports the claim.
|
||||
- [ ] Make stripped and debug artifacts share an explicit build identity and compatible sidecar maps. Inspection output must state the code identity, target, variant, optimization policy, and whether addresses describe AOT or loaded code.
|
||||
|
||||
## Correctness and integration closure
|
||||
|
||||
- [ ] Close every required cell in the step-01 matrix with fresh real execution evidence. Keep target-specific exclusions distinct from missing implementation.
|
||||
- [ ] Verify the [gap policy](gap-policy.md): every remaining Gap has a stable
|
||||
diagnostic and no side effects; capability and inspection output expose it;
|
||||
no fallback, downgrade, skip, emulation or legacy engine is counted as support.
|
||||
- [ ] Run source/saved-IR/new-ZX, optimized/unoptimized, AOT/native-ZX/interpreter, optional variants, foreign ABI, callbacks, concurrency, assets, libraries, persistence, and malformed-input suites.
|
||||
- [ ] Run every retained local test with `make check` and `make check-bootstrap`. Do not substitute filtering, sharding or the retired `make check-full` workflow for the repository's physically pruned suite.
|
||||
- [ ] Run sanitizer/fuzz/resource-bound campaigns against new decoders, verifiers, object readers, loaders, and instruction execution. Store minimized cases as Ziran fixtures and fix relevant failures.
|
||||
- [ ] Verify new-backend self-hosting and bootstrap reproducibility, standalone output without external compilation/link tools, browser wasm execution, and supported downstream hosts on the full local stack.
|
||||
- [x] Confirm old-format rejection and retire old ZX-specific AST execution and C/TinyCC generation only after replacements pass. Preserve compile-time/law tooling evaluators and optional C/Go backends still in use. A file of another revision is rejected with no fallback reader; the semantic bundle writer and reader, the portable VM, bundle libraries and the TinyCC ZX route are removed.
|
||||
|
||||
Run every build and compiling test through `build-queue --`; remove `DISPLAY` and `WAYLAND_DISPLAY` unless a private display fixture supplies them. Missing target hardware or local integration dependencies are blockers to their completion cells, never a reason to substitute a CI promise.
|
||||
|
||||
## Performance acceptance
|
||||
|
||||
- [ ] Define workload-specific regression budgets before measuring. Cover arithmetic, branch-heavy loops, records/arrays, strings, calls, register pressure, SIMD/codec kernels, parallel regions, host crossings, cold compile/startup, warm-cache startup, memory use, and binary size.
|
||||
- [ ] Benchmark only on Alpha's physical host directly, rejecting
|
||||
virtualization and preserving the actual host, CPU/OS features, toolchain
|
||||
identities, flags, workload inputs, selected engine, and output correctness.
|
||||
If Alpha is unavailable, leave performance verification pending.
|
||||
- [ ] Compare new-native AOT and native ZX with the M0 receipts of the removed TinyCC path, portable instruction execution, and independent C/Go controls where meaningful. Compare matched semantics, safety checks, and feature levels.
|
||||
- [ ] Retain all raw samples and excluded indices. Apply the same symmetric 1.5×IQR rule with inclusive interpolated quartiles to every target/platform comparison.
|
||||
- [ ] Investigate regressions using source-linked final disassembly and measured profiles. Fix common lowering/allocation/runtime causes before adding workload-specific instruction cases.
|
||||
- [ ] Report gains and losses by workload. Do not replace missing measurements with an “absolute fastest” claim or confuse cross-compilation with benchmark execution.
|
||||
- [ ] Deliver the owner's requested full before/after ZX comparison when the implementation is finished: old portable VM and old C/TinyCC-native ZX against the new portable instruction engine and new-native ZX, plus direct AOT and matched C/Go/Wasm controls where supported. Show absolute timings, speedup/slowdown ratios, cold compilation and startup, warm-cache startup, warm throughput, memory use, generated code/bundle size, raw samples, excluded indices, and named missing measurements. The old engines are removed, so their before measurements are the receipts and correctness oracles captured on Alpha at [milestone](milestones.md) M0; historical results from a different host or workload are not the before measurement. Interim comparison 1 followed M1, and interim comparison 2 follows M3; this final report supersedes them.
|
||||
|
||||
## Documentation, installation, and publication
|
||||
|
||||
- [ ] Update format/opcode specifications, language/native target boundaries, capability reporting, CLI help, embedding API docs, error guides, and inspection examples.
|
||||
- [ ] Update `CHANGELOG.md` under `Unreleased`. Regenerate affected documentation/site outputs through existing scripts; translate touched locale content where applicable.
|
||||
- [x] Install from the current working tree at the stable path and verify the installed tool can compile, inspect, and run representative new-format programs. Do not terminate the owner's running applications. Done on Omega on 2026-11-15 with `make install-user` from the working tree. The installed `ziran` runs the examples, and `ziran bundle` writes revision-28 `.zx`. `zi2zx --emit lir` and `zx2native --emit map` inspect it. `ziran run app.zx` executes it natively: a bounds trap reports "native execution failed", where `--backend engine` reports "portable execution failed", and its `zx2native` ELF exits with 125. The local receipt is `build/check-logs/m3-installed-tool-2026-11-15.txt`.
|
||||
- [ ] Keep implementation uncommitted until the complete feature set and meaningful required local tests pass. Missing required verification leaves the work uncommitted.
|
||||
- [ ] Follow the owner's applicable commit/push authority at implementation time, preserving unrelated work. A release/version bump/tag requires an explicit release request and the existing version workflow.
|
||||
- [ ] If pushed under applicable authority, report “pushed, CI not checked yet” without waiting for or polling CI. Website publication follows the existing GitHub workflow only; verify deployment separately when it is actually requested/performed.
|
||||
|
||||
## Final exit gate and completion receipt
|
||||
|
||||
All ten steps are complete only when the portable instruction format, reference engine, complete required native target matrix, internal encoders/linkers, native ZX runtime, inspection/profiling surfaces, self-hosting, and installation have executed successfully under their required tests. Any Gap, Unknown, fallback, downgrade, skip, emulated substitute, or legacy-engine substitute keeps the corresponding gate open. Record exact remaining limitations instead of rounding partial coverage to 100%.
|
||||
|
||||
The final receipt names changed components, local test coverage, benchmark host/results, target execution coverage, installed behavior, and independently confirmed commit/push/release/deployment states. A successful build, commit, or agent handoff alone is not a completion receipt.
|
||||
@@ -0,0 +1,353 @@
|
||||
# Direct assembly implementation
|
||||
|
||||
## State
|
||||
|
||||
The upgrade is not finished: the M4-M6 rows are open work in
|
||||
[plans/open-work.md](../plans/open-work.md). `zi2zx` lowers checked source or
|
||||
saved `.zir` to verified, typed SSA, and `zx2native` directly encodes a Linux x86-64 ELF
|
||||
executable. Every `.zx` is the [revision-28 executable
|
||||
container](zx-executable-format.md) of those verified instructions: `zi2zx`
|
||||
writes it, and `ziran run` and the embedding API
|
||||
run it on the portable instruction engine. The C, Go and wasm source-output
|
||||
routes are separate.
|
||||
Delivery order and the plan review are in [milestones](milestones.md).
|
||||
The [gap policy](gap-policy.md) is normative: unsupported direct-target work
|
||||
fails with a stable diagnostic and remains visible in the completion matrix;
|
||||
portable, legacy and alternate backends are never fallback success paths.
|
||||
|
||||
The experimental direct pipeline is:
|
||||
|
||||
```text
|
||||
.zi -> .zir -> lowered LIR -> verifier -> LIR optimizations -> .zx
|
||||
| |
|
||||
--emit lir verified ZX reader
|
||||
|
|
||||
portable interpreter OR target lowering
|
||||
|
|
||||
ELF + native range map
|
||||
```
|
||||
|
||||
The compiler tools still use the normal compiler bootstrap. Once built,
|
||||
`zx2native` writes machine bytes itself: it does not generate C or launch an
|
||||
assembler, C compiler, or system linker to produce this executable.
|
||||
|
||||
## Implemented boundary
|
||||
|
||||
- Fixed-width signed/unsigned integers, bools, float32 and float64, local scalar
|
||||
bindings, arithmetic, ordered/unordered comparisons and checked conversions.
|
||||
- Branches, lazy `&&`, `||` and `ifx`, while and counting loops, loop exits, and
|
||||
direct scalar calls including recursion. Portable calls support the checked
|
||||
value shapes below. Machine-native calls support at most six general-register
|
||||
arguments and one general-register result; float, vector, aggregate and
|
||||
stack-passed call forms fail before encoding as named gaps.
|
||||
- Record and fixed-array construction, extraction, local field/index mutation,
|
||||
record-returning direct calls, nested value copies and simultaneous aggregate
|
||||
block transfers in lowered IR and the portable engine. Local fixed arrays
|
||||
accept dynamic integer indices with signedness-aware bounds checks. Assignment
|
||||
destinations and every nested index are evaluated once before the right side.
|
||||
Machine-native aggregate call arguments and results remain explicit gaps.
|
||||
- Portable procedure values, arguments/results and indirect calls through local
|
||||
slots, record fields and fixed-array elements. Procedure slots are checked
|
||||
tokens with explicit signatures: null, invalid and wrong-signature targets
|
||||
trap instead of becoming arbitrary machine addresses. Dispatch is currently an
|
||||
unoptimized matching scan. External C/System/Host callbacks remain unsupported.
|
||||
- Static integer/bool constant globals and zero-default records/fixed arrays,
|
||||
including nested field mutation, imported globals, file-private definitions
|
||||
and local shadowing in source/saved IR and the portable instruction engine.
|
||||
Global/record-field addresses, pointer arguments/results and dereference
|
||||
reads/writes also lower to checked address operations. Assignments evaluate
|
||||
the destination once before the right-hand side; compound assignments retain
|
||||
the preceding value even when a call mutates an alias. Local bool, integer,
|
||||
float, pointer, record, fixed-array and procedure-value bindings can have
|
||||
their address taken; such locals become checked frame allocations. Dynamic
|
||||
fixed-array element addresses
|
||||
rooted in globals or checked pointers are bounds-checked, including nested
|
||||
records/arrays and addresses returned across procedure calls.
|
||||
Retained tests compare C, Go and the portable instruction engine, including
|
||||
a call-valued dereference assignment. Dependency-ordered
|
||||
runtime module initializers execute once per portable instance before entry;
|
||||
a failed initializer is sticky and entry is not started. Native ELF runs the
|
||||
same ordered initializer list before entry. Mutable global state, readonly
|
||||
constant storage and initializer state are owned by the execution instance.
|
||||
- Block-parameter SSA with simultaneous edge copies, explicit ordered effects,
|
||||
copied source origins, and a bounded verifier that rejects invalid definitions,
|
||||
dominance, CFG edges, types, and effect order.
|
||||
- Deterministic raw x86-64 encoding and ELF output with `.text`, `.rodata`,
|
||||
`.data`, `.bss`, `.symtab`, `.strtab`, `.dynamic` and `.shstrtab` section
|
||||
headers. `_start` and each program function's symbol carry their linked
|
||||
address and byte extent, so final disassembly, debuggers and profilers have
|
||||
meaningful labels; the section table describes the same bytes the program
|
||||
headers map.
|
||||
- Static globals and checked global/record-field pointer slots in direct ELF,
|
||||
with zero/scalar initialization, packed aggregate loads/stores, pointer
|
||||
parameters/results and separate RX text, read-only data and RW data segments.
|
||||
Writes through read-only data tokens trap. Native code checks a pointer
|
||||
token's liveness, version, writability and bounds in constant time from the
|
||||
token itself; unlike the engine it does not yet check the pointee's element
|
||||
type. No generated-C bridge is used.
|
||||
- Verified lowered IR supports frame-local allocation of every current scalar,
|
||||
record, fixed-array and procedure-value type in both the portable engine and
|
||||
native ELF.
|
||||
Every execution receives fresh zero-default or explicitly initialized storage.
|
||||
Native active-frame descriptors preserve aliases through calls and recursion;
|
||||
stale, wrong-type, forged, and exhausted-generation tokens trap with status 125.
|
||||
- `#foreign host_api` calls lower to bodiless `Host` functions and explicit
|
||||
`host.call` instructions from source and saved IR. A host value is a bool,
|
||||
integer, float, pointer, which crosses as an opaque handle, or a record,
|
||||
fixed array or view (`string`, `[]T`) of host values, nested at most 64
|
||||
deep. Procedure values and types that reach themselves through a view are
|
||||
rejected. The platform services are the named functions of the
|
||||
`ziran.platform` module; a function of that name elsewhere is an ordinary
|
||||
host capability. The revision-28 container records the recomputed capability
|
||||
count. Embedders use `LirExecBindHost` for the scalar ABI or
|
||||
`LirExecBindHostTyped` for the typed ABI. Typed scalars and pointers cross in
|
||||
`bits`. Every other value crosses in `bytes` as one host image: the value's
|
||||
own bytes, then the elements of each view inside it. In the image a view's
|
||||
two words are the byte offset of its first element from the start of the
|
||||
image and its element count; an empty view is two zero words. Arguments are
|
||||
validated and copied. Returned views become instance-owned read-only storage
|
||||
that remains valid for globals and later calls; a malformed image fails the
|
||||
call and keeps nothing. A host's changes to an argument image are not copied
|
||||
back yet.
|
||||
A `--bind` provider already present in the checked Ziran program lowers to a
|
||||
direct portable call. Native output accepts only the exact typed
|
||||
target-owned console services described below; arbitrary host capabilities
|
||||
still fail until native host trampolines exist.
|
||||
- A registered host library may instead be an `ar(1)` archive of ELF64 x86-64
|
||||
relocatable objects (`cc -c`, `ar rcs`). The Linux executable links the
|
||||
members its capabilities reach, once each, carrying their text, read-only
|
||||
constants, writable data, zero fill and relocations, and each capability's
|
||||
veneer calls its member directly, so the executable stays static and has no
|
||||
dynamic record. Absolute, PC32/PC64, PLT32, 32/32S, SIZE and GOT-relative
|
||||
relocations are applied; TLS, constructor arrays, an undefined or duplicate
|
||||
symbol and an unsupported relocation are the stable
|
||||
`assembly.gap.machine-archive` diagnostic naming the capability, member and
|
||||
symbol. A Windows image links no archive yet.
|
||||
- `string` lowers to the record `{data: *u8, count: s64}`. Literals become
|
||||
deduplicated read-only byte-array globals (empty literals use a null data
|
||||
pointer); copies, reassignment, returns, `.count`, `.data`, checked indexing,
|
||||
slicing and equality/inequality work in source, saved IR and the portable
|
||||
engine. Slices use checked `{data, count}` views over fixed arrays or other
|
||||
byte views, including empty/null views. Stores through read-only bytes trap.
|
||||
Machine-native output supports the read-only data section, checked indexing,
|
||||
byte equality and checked text views over frame-allocated fixed byte arrays,
|
||||
including nonzero and nested slices, with allocation generation, owner-frame,
|
||||
extent and lifetime validation. Slice shapes outside the verified
|
||||
checked-token forms remain outside this implemented subset.
|
||||
String concatenation is not a current checked-language string operation.
|
||||
- A verified, target-neutral [machine IR](machine-ir.md) boundary is the only
|
||||
`zx2native` lowering path. It lowers the current LIR subset for Linux x86-64
|
||||
SysV with virtual registers, fixed-register constraints, explicit flags, call
|
||||
clobbers and parallel copies. Deterministic allocation, an allocated-program
|
||||
verifier and x86-64 encoding feed the internal ELF writer.
|
||||
- The machine Linux x86-64 console veneer emits a static ELF with its own
|
||||
`_start`, Linux `write` syscall 1 through a partial-write/`EINTR` retry loop,
|
||||
and `exit_group` syscall 231. Standard output is buffered (line by line on a
|
||||
terminal) and flushed before other descriptors' writes, traps and exit. It has no libc, CRT, `PT_INTERP` or `PT_DYNAMIC`.
|
||||
Literal formatting covers strings/text views by byte length, bools, every
|
||||
fixed signed/unsigned integer width, float32/float64 values and `%%`. Other
|
||||
platform services are named hard gaps.
|
||||
- `--emit lir` and `--emit map` inspection views. Map ranges are half-open,
|
||||
relative to `.text`, and identify function, block and instruction.
|
||||
Native always reads the verified, optimized ZX image, even for source input;
|
||||
the current required ZX payload strips source origins, so native map origins
|
||||
are empty. Source LIR inspection retains origins. Debug attachments and full
|
||||
source-to-native mapping remain a hard gap. LIR schema 4 rejects older ZX
|
||||
payloads at a rebuild boundary. Textual names are quoted and escaped rather
|
||||
than allowed to inject extra lines into the instruction listing. Metadata
|
||||
names and paths must be nonempty, NUL-free valid UTF-8; malformed wire metadata
|
||||
is rejected before reaching JSON output, while valid Unicode is preserved.
|
||||
- `--emit zx` always optimizes and writes the deterministic portable executable;
|
||||
`--input zx` verifies and consumes it without source or `.zir`.
|
||||
Source ELF output serializes and reads that same ZX boundary first, so a ZX
|
||||
image gives byte-identical native output through either entry route. No
|
||||
standalone `.lirb`, `--emit exec` or `--input exec` route remains. The internal
|
||||
instruction codec is only a ZX payload.
|
||||
- `--run` executes the same verified instructions in the bounded portable
|
||||
engine that runs every bundle, with independent fuel, work and frame limits.
|
||||
- Recoverable errors for unsupported constructs and atomic file replacement;
|
||||
rejected programs do not overwrite an existing output.
|
||||
- ZX production always transforms a separately owned copy of verified instructions
|
||||
with exact scalar constant folding, identity-copy propagation, common
|
||||
subexpression elimination, constant-branch CFG simplification and
|
||||
nontrapping dead-instruction removal. Each enabled pass
|
||||
is verified. Source `--opt --emit lir` exposes the transformed program, while
|
||||
`--opt --emit opt-report` emits deterministic JSON transformation counters.
|
||||
Trapping operations, ordered effects and executed fuel checkpoints remain
|
||||
observable. This is not the complete optimization pipeline or register allocator.
|
||||
|
||||
This is a stack-slot backend, **not** an optimizing register allocator. It has
|
||||
no demonstrated performance advantage. Native `Fuel` records emit no bytes and
|
||||
appear as zero-length map ranges: execution is unmetered AOT, not the proposed
|
||||
budgeted ZX instruction engine. Explicit native traps terminate with status 125.
|
||||
|
||||
## Build, inspect, execute
|
||||
|
||||
From the repository root:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY build-queue -- sh -eu <<'SH'
|
||||
make zx-tools JOBS=2
|
||||
build/bin/zi2zx --root tests/spec --entry assembly_scalar:Answer \
|
||||
--emit lir -o build/assembly_scalar.lir tests/spec/assembly_scalar.zi
|
||||
build/bin/zi2zx --root tests/spec --entry assembly_scalar:Answer \
|
||||
-o build/assembly_scalar.zx tests/spec/assembly_scalar.zi
|
||||
build/bin/zx2native --emit map -o build/assembly_scalar.map.json build/assembly_scalar.zx
|
||||
build/bin/zx2native --emit elf -o build/assembly_scalar build/assembly_scalar.zx
|
||||
status=0
|
||||
build/assembly_scalar || status=$?
|
||||
test "$status" -eq 42
|
||||
SH
|
||||
|
||||
objdump -D -b binary -m i386:x86-64 --start-address=0x80 --adjust-vma=-0x80 build/assembly_scalar \
|
||||
> build/assembly_scalar.disasm
|
||||
```
|
||||
|
||||
The address adjustment makes disassembly addresses match the map's text-relative
|
||||
offsets for this ELF layout. These offsets are neither source line numbers nor
|
||||
addresses from a running process. `--emit lir -o -` and `--emit map -o -`
|
||||
write inspection data to standard output; ELF output requires a file path.
|
||||
`--emit zx -o -` writes portable executable ZX bytes to standard output.
|
||||
`--diagnostics=json` includes structured diagnostic codes.
|
||||
|
||||
Maps report actual ELF file/text/data sizes, file offsets and virtual addresses
|
||||
in `image`. An image with no writable state has one program header and a
|
||||
128-byte text offset; one with globals, fuel, traps or buffered output has
|
||||
two and a 176-byte text offset, and its data follows the text in the file,
|
||||
mapped one page higher. Use the reported
|
||||
`text_virtual_address` rather than the scalar example's fixed adjustment when
|
||||
disassembling another image. Reported addresses describe the linked AOT ELF,
|
||||
not an observed running process or a future relocatable/JIT code allocation.
|
||||
`identity` is SHA-256 of the complete actual ELF, including initialized data
|
||||
and symbol metadata, so a sidecar can be checked against the exact executable.
|
||||
`variant` and `abi` label the baseline x86-64/internal-ABI implementation.
|
||||
`optimization_request` identifies the canonical verified-basic optimization
|
||||
boundary. `--opt` on ZX input does not rerun passes. Maps
|
||||
encode the image to obtain this identity; they are inspection work, not a
|
||||
cheap source-only preview or a runtime performance measurement.
|
||||
|
||||
Native maps support bounded output without renumbering identities:
|
||||
|
||||
```sh
|
||||
build/bin/zx2native --emit map --function-id 0 --block-id 0 \
|
||||
-o build/assembly_scalar.block.map.json build/assembly_scalar.zx
|
||||
build/bin/zx2native --emit map --address-begin 35 --address-end 80 \
|
||||
-o build/assembly_scalar.address.map.json build/assembly_scalar.zx
|
||||
```
|
||||
|
||||
Function/block IDs refer to the selected lowered program (after `--opt`, if
|
||||
enabled). A block filter requires a function ID. Address windows are nonempty,
|
||||
half-open text-relative byte ranges and can intersect a function/block filter.
|
||||
Matching instructions keep their complete original ranges rather than being
|
||||
clipped; zero-byte sites are included when their position lies in the window.
|
||||
Filtered maps retain full extents for selected functions and only referenced
|
||||
origins plus their parent chains. An empty intersection is explicit, not an
|
||||
error or an excuse to dump the whole program. `selection`, `selected_ranges`
|
||||
and `total_ranges` distinguish filtered output from a complete byte map.
|
||||
These options bound inspection output, not compilation work: the current
|
||||
encoder still verifies and lays out the complete program.
|
||||
|
||||
```sh
|
||||
build/bin/zi2zx --root tests/spec --entry assembly_scalar:Answer \
|
||||
-o build/assembly_scalar.zx tests/spec/assembly_scalar.zi
|
||||
build/bin/zi2zx --emit lir -o - build/assembly_scalar.zx
|
||||
build/bin/zx2native -o build/assembly_scalar build/assembly_scalar.zx
|
||||
build/bin/zi2zx run --fuel 10000 --work 100000 \
|
||||
build/assembly_scalar.zx
|
||||
build/bin/zi2zx --opt --emit lir -o build/assembly_scalar.optimized.lir \
|
||||
build/assembly_scalar.zx
|
||||
build/bin/zi2zx --opt --root tests/spec --entry assembly_scalar:Answer \
|
||||
--emit opt-report -o build/assembly_scalar.opt.json tests/spec/assembly_scalar.zi
|
||||
```
|
||||
|
||||
Only source `--emit lir` is unoptimized by default. All ZX, portable execution,
|
||||
native map and ELF production goes through optimization and verified ZX bytes.
|
||||
Reports require source input and `--opt` explicitly and can also use `-o -`.
|
||||
Their `work` and `scratch_bytes` fields are bounded compiler-accounting counters,
|
||||
not elapsed time, process RSS or a performance measurement. A shorter listing or
|
||||
smaller executable is not evidence of faster execution.
|
||||
|
||||
The scalar fixture deliberately returns **42**, not zero. Source and saved-IR
|
||||
tests require byte-identical lowered dumps, maps and executables. Native map
|
||||
tests check that ranges cover the exact encoded instruction bytes without gaps.
|
||||
|
||||
Retained regressions also compare successful source programs with the C backend
|
||||
and exercise integer/bool conversion, returning constant loops, loop exits,
|
||||
non-truncating shift counts and executable permissions on unchanged output.
|
||||
Generated ELF execution is required on Linux x86-64; other hosts still validate
|
||||
encoding and inspection data, without claiming target execution.
|
||||
|
||||
## Still required
|
||||
|
||||
The upgrade is not complete. Outstanding language and runtime work includes
|
||||
resizable owned vectors and other dynamic collections, their generated
|
||||
cleanup/move paths, nested or reentrant host-to-bundle calls, foreign
|
||||
C/system services, concurrency and the remaining matrix operations. The ZX
|
||||
container still needs complete library composition and capability metadata
|
||||
cross-checking; slice shapes outside the checked-token subset, native
|
||||
aggregate call forms and arbitrary host trampolines remain gaps. The open
|
||||
M4-M6 rows are tracked in [plans/open-work.md](../plans/open-work.md).
|
||||
|
||||
Unsupported constructs fail explicitly; there is no silent fallback to C, Go
|
||||
or another engine inside the portable/native assembly route. The C and
|
||||
Go backends remain separate source-output routes that can compile platform
|
||||
binaries when explicitly selected. Mixed signedness comparisons require explicit
|
||||
casts. The bounded revision-28 ZX reader validates container identities, the
|
||||
instruction schema, entry and declared capabilities before native lowering.
|
||||
Benchmark receipts live under `bench/results/` and
|
||||
[bench/zx_compare.md](../bench/zx_compare.md). An interim result does not
|
||||
close the full upgrade's feature or validation gates.
|
||||
|
||||
## Implementation and local tests
|
||||
|
||||
- [Lowered schema](../cmd/compiler_lowered_ir.zi) and
|
||||
[verifier](../cmd/compiler_lowered_verify.zi).
|
||||
- [Instruction codec](../cmd/compiler_exec_serial.zi),
|
||||
[wire format](lowered-format.md), [portable engine](../cmd/compiler_exec.zi).
|
||||
- [Executable container binding](../cmd/compiler_exec_link.zi) and
|
||||
[format](zx-executable-format.md); [machine IR](../cmd/compiler_machine_ir.zi),
|
||||
[lowering](../cmd/compiler_machine_lower.zi) and [verifier](../cmd/compiler_machine_verify.zi).
|
||||
- [Checked-language adapter](../cmd/compiler_zir_lower.zi),
|
||||
[CLI](../cmd/zi2zx/main.c), [build integration](../assembly.mk).
|
||||
- [Source/saved-IR integration tests](../tests/assembly_cases.zi),
|
||||
[verifier fixtures](../tests/spec/compiler_lowered_verify_test.zi),
|
||||
and [machine ELF/map tests](../tests/machine_elf.sh).
|
||||
- [Comparison processor](../bench/assembly_compare.zi),
|
||||
[report schema and methodology](performance-report.md), and
|
||||
[synthetic report tests](../tests/assembly_compare_cases.zi). These validate
|
||||
reporting, not a measured compiler/runtime speedup.
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY make
|
||||
make CHECK_FILTER=direct_assembly check
|
||||
make CHECK_FILTER=compiler_lowered_verify check
|
||||
sh tests/lowered_serial.sh build/bin/ziran
|
||||
make CHECK_FILTER=lowered_exec check
|
||||
sh tests/machine_elf.sh build/bin/ziran
|
||||
make CHECK_FILTER=assembly_compare check
|
||||
make check-bootstrap
|
||||
```
|
||||
|
||||
These are local tests, not GitHub CI results. Benchmarks must run directly on
|
||||
Alpha's physical host, with virtualization rejected. The final
|
||||
report must include matched before/after ZX startup, throughput, memory and
|
||||
artifact sizes, raw samples, excluded samples and any regressions; no speedup
|
||||
is claimed until those measurements exist. The report processor keeps absolute
|
||||
medians, favorable factors and candidate metric percentage changes distinct;
|
||||
missing or noncomparable cells remain visible.
|
||||
|
||||
## Ten-step completion plan
|
||||
|
||||
The steps define completion; [milestones](milestones.md) define the delivery
|
||||
order, per-row cutover and interim measurement points.
|
||||
|
||||
1. [Execution contract and completion matrix](01-contract-and-completion-matrix.md)
|
||||
2. [Lowered IR and verifier](02-lowered-ir-and-verifier.md)
|
||||
3. [Complete language lowering](03-language-lowering.md)
|
||||
4. [Portable instruction engine](04-portable-instruction-engine.md)
|
||||
5. [ZX format and linking](05-zx-format-and-linking.md)
|
||||
6. [Optimization and native backend](06-optimization-and-native-backend.md)
|
||||
7. [Architecture and platform coverage](07-architecture-and-platform-coverage.md)
|
||||
8. [Assembler, objects and linker](08-assembler-objects-and-linker.md)
|
||||
9. [Native runtime and integration](09-native-runtime-and-integration.md)
|
||||
10. [Inspection, performance and cutover](10-inspection-performance-and-cutover.md)
|
||||
@@ -0,0 +1,118 @@
|
||||
# Ziran execution contract
|
||||
|
||||
Status: decisions required by [step 01](01-contract-and-completion-matrix.md). This document is normative for the lowered portable instructions of [step 02](02-lowered-ir-and-verifier.md). The implementation is the checked tree represented by [compiler IR](../cmd/compiler_ir.zi), its [lowering](../cmd/compiler_zir_lower.zi), the [portable instruction engine](../cmd/compiler_exec.zi) that runs every `.zx`, and their retained fixtures.
|
||||
|
||||
The direct target follows the [gap policy](gap-policy.md): target selection is a
|
||||
contract, and an unsupported operation fails rather than selecting another
|
||||
engine or semantic implementation.
|
||||
|
||||
## Contract layers
|
||||
|
||||
1. **Checked language graph:** `.zi` or saved `.zir` produces one checked typed graph. Statements, expressions, source spans, foreign/effect facts, ownership facts, laws, and proof certificates remain in this layer; executable instruction text is not reparsed from statement text.
|
||||
2. **Verified portable program:** lowering turns each reachable function into typed basic blocks with explicit control flow, effects, value definitions, portable layouts, call/cleanup regions, and capability imports. Verification rejects malformed structure, type mismatches, invalid dominance, impossible layouts, and missing effects before an image can be loaded.
|
||||
3. **Immutable encoded image:** the `.zx` executable container owns immutable code, type/layout metadata, constants, entry identity, capabilities, assets, laws, and optional inspection metadata. It contains no host pointers, C structure padding, process addresses, or executable `.zir` requirement.
|
||||
4. **Loaded instance:** one immutable image may create many instances. An instance owns mutable global slots, call stacks, owned allocations, host handles, serial execution ownership, fuel state, and failure state. Code and metadata are never mutated by execution.
|
||||
5. **Target program:** a target description selects CPU architecture, ISA features, OS ABI, calling convention, endianness, pointer rules, and atomic/thread services. It cannot change portable arithmetic, ownership, call order, traps, or capability identity. A missing selected facility is a preflight error; it never changes the engine or lowers to a serial/CPU substitute.
|
||||
6. **Machine program and encoded object:** optimization and native lowering consume only the verified portable program and target description. Register allocation, physical stack frames, ABI call sequences, relocation, and encoding belong to these layers.
|
||||
|
||||
The backend APIs remain distinct: verify portable program, describe target, build machine program, encode image/object, load instance, run instance, inspect image or instance. No API accepts an unverified graph as executable code or exposes mutable process memory as program code.
|
||||
|
||||
## Numeric and scalar semantics
|
||||
|
||||
Current fixed integer types are `s8`, `u8`, `s16`, `u16`, `s32`, `u32`, `s64`, and `u64`. Abstract `int`/`integer` and pointer-sized `isize`/`usize` arithmetic use the 64-bit signed/unsigned operation policy on the portable target (matching `size_of(isize) == size_of(usize) == 8`). Bit representations, rather than host signed arithmetic, define operations; [scalar helpers](../cmd/zir/zir_scalar.h) mask to the declared width and reinterpret signed payloads.
|
||||
|
||||
- Addition, subtraction, multiplication, signed negation/overflow, and unsigned wraparound wrap at the operand width. Unsigned intermediates are used on all targets so C behavior is defined.
|
||||
- Signed minimum divided by `-1` wraps to itself; its remainder is zero. Integer division or remainder by zero is a failed execution/trap, not undefined behavior.
|
||||
- Left shift masks/uses the destination width after an unsigned-width shift; signed right shift sign-extends. A negative count or a count at or beyond the operand width fails on every target.
|
||||
- Narrowing casts truncate to the destination bit width; widening casts preserve or zero-extend according to source signedness. All 64 signed/unsigned conversion pairs are covered by generated boundary fixtures.
|
||||
- Comparisons use the operand's signedness and width. Equality on floating NaN is false; float division may produce infinity or NaN. Float-to-integer conversion requires a value representable in the destination type; a nonfinite or out-of-range conversion fails.
|
||||
- `float32` operations must round each float32 operation once. C, Go, native output and the portable instruction engine all do so; [numeric conformance](../tests/numeric_conformance.json) records the chained-literal case.
|
||||
- Enums have a checked integer backing width; enum comparison and conversion follow that representation without assuming a native `int` rank.
|
||||
|
||||
The current stable numeric cases and their exact fixture are published by [capability reporting](../cmd/package_capabilities.zi) and described in [numeric conformance](../tests/numeric_conformance.json); [numeric semantics](../tests/numeric_semantics.sh) and the [width matrix](../tests/numeric_width_matrix.sh) cover source and saved IR through C, Go, and ZX.
|
||||
|
||||
## Portable layouts, values, and memory
|
||||
|
||||
The lowered IR needs a deterministic **logical layout** distinct from native ABI layout. It records scalar kind/width/signedness, field order, byte size, alignment, inline/packed eligibility, array length and element layout, union alternatives, enum backing, and ownership/borrow class. Equivalent checked declarations must produce equivalent metadata under different allocation histories. Native alignment, padding, bitfield, vector ABI, calling convention, and address representation are selected only in the target program.
|
||||
|
||||
The portable image exposes logical offsets, not tagged C pointers or interpreter value layouts. The engine keeps values in packed instance-owned bytes and reaches them through checked address tokens; that is an implementation choice, not part of the image.
|
||||
|
||||
- Scalars, immutable strings, fixed arrays, and copyable records have value semantics. Assignment and parameter passing copy logical values unless an owned storage class explicitly moves.
|
||||
- Unions select one active alternative; reading the wrong alternative is a checked failure. Records containing references, opaque foreign members, or oversized representations retain explicit logical storage.
|
||||
- Fixed arrays and vectors have checked indexing and length. Proven-range optimizations may remove a bounds check only while the verifier can reconstruct the same proof.
|
||||
- `New(T)` allocates zero-initialized storage and returns a pointer class; `free(pointer)` releases it, ignores null, and rejects a freed or non-heap pointer. Types with owned vector storage cannot bypass cleanup. The current contract and physical-OOM boundary are documented in [heap allocation](../tests/heap_new.sh).
|
||||
- Bundle pointer parameters are opaque host handles: they may be stored, compared with null/equal, and passed to matching capabilities. They cannot be dereferenced as arbitrary process addresses. Native C pointers retain native lifetime rules; this is a target boundary, not a portable aliasing contract.
|
||||
- Immutable strings have byte length and may contain NUL. A `TextView` is a borrow of a place. Current C mutation observes borrowed bytes; Go and ZX snapshots isolate mutation, as reported by [capabilities](../docs/CAPABILITIES.md). Lowered IR must preserve each target's observable rule through an explicit borrow or snapshot operation rather than pretending one representation is universal.
|
||||
- Portable state export deep-copies owned strings, arrays, records, enums, scalar lanes, and vectors. Pointers, slices, growable vector backing, and other borrowed/host resources are rejected.
|
||||
|
||||
## Ownership and cleanup
|
||||
|
||||
The checked graph records move and borrow facts. Lowering must make each effect explicit; a backend may not invent an extra copy, drop, or mutation.
|
||||
|
||||
- Direct owned `Vec` locals and parameters drop at block close, return, `break`, and `continue`, including every path through nested control flow. Vectors reachable through record fields and fixed arrays drop recursively. Globals remain shared and are not automatically released.
|
||||
- A valid move source is a whole local binding, a fresh call result, or a plain record-member path rooted at a local aggregate. A direct move clears its source before a later drop. An aggregate move clears every reachable native vector field; the portable representation invalidates the corresponding logical slots. Moved storage is unreachable thereafter.
|
||||
- Indexed and pointer-backed member paths and paths rooted at a global remain rejected as move sources. Assignment over an owned direct or aggregate-held vector is rejected. A fresh vector expression statement drops immediately; a member/index access must first bind the fresh result.
|
||||
- `BuilderFinish` consumes the builder. Native C transfers nonempty bytes and retains them for process lifetime; Go copies an immutable snapshot. Empty native storage may be released. `Text` is an owned record wrapping a vector and follows aggregate move/drop rules.
|
||||
- Live vector slices and text views restrict mutation, resizing, moving, replacement, and calls whose checked effect summary writes their backing. Checks are field-sensitive where represented: sibling fields remain mutable. Raw foreign declarations have no checked read/write summary and remain the caller's responsibility.
|
||||
- Scoped cleanup is a region in the instruction graph, not a source-text transformation in the backend. Returns, breaks, continues, traps, and parallel-region exits follow the same explicit cleanup edge set. The current source pass and tests are in [cleanup lowering](../cmd/compiler_ir_cleanup.zi) and [owned values](../docs/OWNED_VALUES.md).
|
||||
|
||||
## Calls, effects, concurrency, and fuel
|
||||
|
||||
Call arguments evaluate left to right on every target. Named/default binding occurs after argument evaluation. Call results feed directly into the consuming call or operation, but earlier values are read before later calls can mutate them. Compound assignment reads its destination before evaluating the right operand. These rules are fixed by [call order](../tests/call_order.sh) and [compound order](../tests/compound_order_cases.zi).
|
||||
|
||||
Every callable and foreign capability carries an explicit effect class: pure, observing, mutating, external/host, allocation, trap, parallel, or combinations accepted by the verifier. Effects drive reordering restrictions, borrow checks, fuel placement, host preflight, and optimization barriers. A pure operation can be controlled only if its result and trap behavior remain indistinguishable.
|
||||
|
||||
- Direct, procedure-value, bound-provider, and foreign calls all declare parameter and result layouts. Host marshalling validates signatures and returned record field identities/types. Mutable slice arguments are copied back only after a successful synchronous host call; overlapping mutable slice arguments are rejected.
|
||||
- A call owns its local cleanup region. Evaluation temporaries remain rooted until the last consumer and call complete. A value a host call returns is released at a later host call once nothing the program can reach names it.
|
||||
- Portable engine calls nest up to the frame limit its host sets, 65,536 for bundles; a deeper run fails with "nested calls filled the stack". Native and Wasm tiers use explicit stack/budget guards. Recursion exhaustion is a failed execution, not allocator or stack corruption.
|
||||
- Ordinary native and portable runs are unbounded. A host may select a positive cumulative budget before global initialization. The portable engine, native and Wasm tiers count function entries and loop iterations, with literal-bound loops charged at region entry. Workers in one `#parallel for` region spend from the shared remaining budget, and the run charges all successful iterations when the region ends. Current behavior and tests are documented in [ZX execution](../docs/ZX.md) and [bundle step limits](../tests/bundle_step_limit.sh).
|
||||
- `#parallel for` currently runs forward C regions on worker threads; existing Go/ZX serial behavior is baseline evidence, not assembly-target support. The direct target rejects a parallel region until that target implements its declared parallel contract. Portable instances support concurrent execution only across distinct instances; each instance and host callback context has one executing owner.
|
||||
- `#parallel_gpu for` currently has no device backend. The direct target rejects the region with its Gap diagnostic; it never runs or reruns the region on the CPU. A future device implementation must preserve failure and budget semantics without substituting a different engine.
|
||||
|
||||
## Traps, capabilities, and isolation
|
||||
|
||||
Runtime failures stop the current run and leave the instance marked failed: out-of-bounds access, invalid union access, integer divide by zero, invalid float-to-integer conversion, invalid shift, unreachable code, allocation/cleanup contract failure, stack/fuel exhaustion, host contract violation, or a capability call returning an invalid value. A trap runs no later user code except cleanup already required by the verified failure edge; it must not read freed storage or synthesize a result. Diagnostics retain a source location when inspection metadata is present.
|
||||
|
||||
Required host services are capability identities, not dynamic imports: module/function pairs with checked ABI and argument-read/effect metadata. A provider check must reject an unsupported program without running initializers, opening a window, or executing the entry. Missing bindings fail before entry. Validated native code is **not an operating-system sandbox**: malformed-input rejection and capability restrictions do not confine memory, syscalls, signals, or bugs in linked OS libraries. Untrusted execution still requires a process or comparable OS boundary.
|
||||
|
||||
There is no native ZX engine yet. Every `.zx` runs on the portable instruction engine, or on the WebAssembly tier where a provider is installed; a tier that cannot run a program fails instantiation and never starts another. The planned direct native backend must preserve the same failure and capability model.
|
||||
|
||||
## Debug and release policy
|
||||
|
||||
Semantic checks, effects, layouts, control-flow validity, capability ABI, and trap/cleanup edges are mandatory in debug and release. Release optimization may remove only checks it can prove redundant. Stripping names, source spans, variable provenance, law evidence, or disassembly metadata is an explicit encoding choice selected by the producer and recorded in image metadata. Stripped inspection data never changes executable semantics. A debug image may be larger and slower, but a release image cannot rely on unverified assumptions.
|
||||
|
||||
## Lowered IR representation decisions
|
||||
|
||||
Use typed virtual registers in basic blocks, not source trees and not physical registers. Registers are immutable except explicit mutable-place instructions; SSA-like value definitions must dominate uses. Keep source spans and provenance out of the execution datum, attached in parallel side tables. Functions and blocks need stable IDs, not object pointers. Constants are typed, canonical, and owned by the image.
|
||||
|
||||
The graph verifier must prove block termination, edge arity, dominance, type equality, move/borrow validity, cleanup region coverage, layout consistency, effect ordering, fuel edge placement, and capability signatures. It must also reject process pointers, target-specific sizes in portable code, duplicate IDs, cycles among value definitions, and metadata that references missing declarations.
|
||||
|
||||
### Concrete opcode categories
|
||||
|
||||
Do not assign numeric opcodes in this step. Reserve stable categories, each with typed operands and a separate effects word:
|
||||
|
||||
| Category | Required forms | Representation decision |
|
||||
|---|---|---|
|
||||
| Constants | scalar, string bytes/range, enum, null pointer, zeroed aggregate, typed SIMD lanes | Intern by canonical typed value; never reparse literal text at run time. |
|
||||
| Data movement | copy, move, clear, zero-init, union select, view/borrow, snapshot | Destination and source carry logical layout and ownership class; moves clear source slots. |
|
||||
| Integer arithmetic | add/sub/mul/neg, div/rem, and/or/xor/not, shifts, min/max if currently checked | Parameterize width and signedness; checked div/rem/shift trap classes are explicit. |
|
||||
| Float arithmetic | add/sub/mul/neg/div/rem-if-supported, compare, classify, round, convert | Keep `f32` and `f64` distinct; no silent double intermediates. |
|
||||
| Conversion | integer width/sign, integer/float, enum/integer, bitcast only where portable | Model checked range failure; reinterpretation cannot change logical type. |
|
||||
| Aggregate memory | field read/write, fixed-array index, vector index, union field, slice bounds | Logical offsets and lengths only; target lowering selects ABI. |
|
||||
| Heap and ownership | allocate-zero, free, retain/release hooks, cleanup region enter/exit | Explicit region terminator handles return, break, continue, and trap edges. |
|
||||
| Control flow | conditional/unconditional branch, switch/complete enum, loop header, named break/continue, unreachable | One terminator per block; named control-flow IDs are resolved by verifier. |
|
||||
| Calls | direct, procedure value, bound provider, foreign capability, host marshalling, tail call only if semantics survive | Arguments are explicit ordered operands; defaults/names are lowered before encoding. |
|
||||
| Effects and fuel | checkpoint, budget set/consume, worker region enter/exit, explicit device/worker failure | A checkpoint is observable and blocks moving an unbounded call/loop; no CPU fallback opcode exists. |
|
||||
| SIMD | lane insert/extract, element-wise arithmetic/compare/select, reductions currently supported | Lane type/count is portable; ISA lowering is target-only. |
|
||||
| Text and collections | string length/index/equality, builder append/finish, vector operations currently supported | Preserve borrow versus snapshot and recoverable allocation failure. |
|
||||
| Capability and instance | capability require/call, state export/import, instance replace boundaries | Capability identity and ABI checks precede entry/upgrade. |
|
||||
|
||||
Keep target-specific assembler, OS syscall, atomic, thread, ABI call, and platform-library operations out of the portable opcode stream. Encode them as declared capabilities or explicitly selected native extension records with target descriptions; unsupported combinations must fail at target preflight.
|
||||
|
||||
## Non-goals and open boundaries
|
||||
|
||||
- The replacement `.zx` format is intentionally incompatible: it is revision 28, and a file of another revision is rejected.
|
||||
- Go-only opaque maps/types and C callback/assembly extensions do not become portable types by renaming. They remain target extensions with preflight rejection where the portable verifier cannot preserve them.
|
||||
- Raw native FFI has no checked aliasing/memory-effect contract. Differently typed aliases and arbitrary host-backed aliases remain outside current guarantees.
|
||||
- Cross-compilation, successful object encoding, a child-agent receipt, or a stored benchmark report does not prove target execution. Completion requires fresh evidence for the exact platform and fixture.
|
||||
- RISC-V and every architecture beyond the maintained x86-64, 32-bit ARM, AArch64, and wasm32 rows are explicit future extensions, not implicit completion.
|
||||
@@ -0,0 +1,100 @@
|
||||
# Current execution feature matrix
|
||||
|
||||
Status: current-tree baseline for [step 01](01-contract-and-completion-matrix.md).
|
||||
`Working` means the implementation and retained source/saved-IR fixture exist;
|
||||
it is not a claim that this documentation task reran the fixture. `Gap` means
|
||||
the direct assembly target lacks required work and must reject it explicitly.
|
||||
`Excluded` is a deliberate target-contract exclusion. `Unknown` means no fresh
|
||||
execution evidence for this cell is present. Current fallback or downgrade
|
||||
behavior is recorded only as baseline evidence and is a Gap for the new target;
|
||||
it never counts as support under the [gap policy](gap-policy.md). `Proposed`
|
||||
belongs to the ten-step ASSEMBLY plan, not today's implementation.
|
||||
|
||||
Primary evidence is [implementation status](../docs/IMPLEMENTATION_STATUS.md), [capability output](../docs/CAPABILITIES.md), [ZX behavior](../docs/ZX.md), the stable feature registry in [features](../docs/FEATURES.json), [capability reporting source](../cmd/package_capabilities.zi), and retained tests. Cross-compilation or presence of a script never counts as target execution evidence.
|
||||
|
||||
## Execution modes
|
||||
|
||||
The opt-in [direct scalar prototype](README.md) is separate from these existing
|
||||
engines. It emits Linux x86-64 ELF from checked source/saved IR, but does not
|
||||
replace ZX or establish portability/performance completion.
|
||||
|
||||
| Mode | Current status | Evidence | C | Go | Portable ZX | Native ZX | Wasm | OS boundary |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| Generated C output | Working, source and saved IR | [implementation status](../docs/IMPLEMENTATION_STATUS.md), [C target](../tests/c99_target.sh) | emits C | n/a | n/a | lowers to same C backend | can compile selected C to wasm32 | Linux current host; Windows/macOS/Android toolchains have separate fixtures |
|
||||
| Generated Go output | Working, secondary tier | [capabilities](../docs/CAPABILITIES.md), [call order](../tests/call_order.sh) | n/a | emits Go | n/a | n/a | n/a | Verifiable only where a compatible Go runtime/toolchain executes it |
|
||||
| Portable instruction engine | Working; runs every `.zx` through `zi2zx run` | [ZX contract](../docs/ZX.md), [engine](../cmd/compiler_exec.zi) | n/a | n/a | runs every bundle | n/a | separate target | Host capabilities and platform console services only |
|
||||
| Wasm execution tier | Working restricted subset; provider rejection is a hard `zx.wasm` error and never starts another engine | [Wasm tier](../docs/ZX.md) | emitter | n/a | explicit separate engine only | budget model shared | wasm32 | Scalars, owned strings, fixed arrays, records, typed `s64 -> s64` hosts; other constructs must fail direct-Wasm preflight |
|
||||
|
||||
## Portable language behavior
|
||||
|
||||
| Feature | Current status and target behavior | Evidence |
|
||||
|---|---|---|
|
||||
| Fixed-width integers | Working on C, Go, ZX source/saved IR: declared-width wrap, signed-min division/remainder, shifts, casts, bitwise and mixed-width behavior. Wasm uses the same scalar tier inside its subset; unknown outside available Wasm fixtures. | [numeric semantics](../tests/numeric_semantics.sh), [width matrix](../tests/numeric_width_matrix.sh), [manifest](../tests/numeric_conformance.json) |
|
||||
| Float32/float64 | Working arithmetic, compare, infinity/NaN and range-checked conversion on native C/Go/ZX. lowered IR must not preserve that gap. | [numeric manifest](../tests/numeric_conformance.json), [status](../docs/IMPLEMENTATION_STATUS.md) |
|
||||
| Implicit widening | Working for the checked feature contract on C, Go, ZX. | [feature registry](../docs/FEATURES.json), [features test](../tests/compiler_inventory_cases.zi) |
|
||||
| SIMD vectors | Working with identical lanes across native C tiers, Go lane loops, bundles and source/saved IR. C wasm32 may use SIMD128; bundles run vectors lane by lane. CPU feature selection is target-specific. | [status](../docs/IMPLEMENTATION_STATUS.md), [SIMD target](../tests/simd_target.sh) |
|
||||
| Scalars, strings, enums, plain records | Working in portable subset, including literals, copies, fields, scalar compound assignment, parameters and returns. Pointer-sized `isize`/`usize` lower as portable 64-bit signed/unsigned integers (matching `size_of` = 8); functions/statements outside the verifier subset are rejected. | [ZX subset](../docs/ZX.md), [verifier](../cmd/compiler_lowered_verify.zi), [size scalars](../tests/spec/zx_lowered_size_scalars.zi) |
|
||||
| Fixed arrays, slices, vector indexing | Working with checked bounds. Generated C may omit only proven bounds checks; portable host slices copy successful mutations back and reject overlapping mutable arguments. | [proven ranges](../tests/proven_index_ranges.sh), [host slices](../tests/host_slices.sh) |
|
||||
| Compile-time assertions, `#run`, laws | Working as checked language features on all advertised targets; unsupported proof/effect forms or exhausted budgets are rejected/unknown rather than guessed. | [feature registry](../docs/FEATURES.json), [compile run](../tests/compile_run.sh), [laws](../tests/laws.sh) |
|
||||
| Procedure defaults and procedure values | Working for advertised examples on C, Go, ZX; portable verifier checks slot signatures and rejects C callback procedure types. | [feature registry](../docs/FEATURES.json), [defaults](../tests/call_argument_cases.zi) |
|
||||
| Print and I/O | Working literal-format print on C, Go, ZX. Rich OS I/O is a library/capability contract, not a portable opcode. | [feature registry](../docs/FEATURES.json), [print](../tests/print.sh) |
|
||||
| Named imports and linking | Working; bundles follow direct calls, retain required startup/types/laws, and reject unresolved imports or unreachable unsupported code. | [ZX linker](../docs/ZX.md), [bundle provider cases](../tests/bundle_provider_cases.zi) |
|
||||
|
||||
## Memory, ownership, and cleanup
|
||||
|
||||
| Feature | C | Go | Portable ZX | Wasm | Evidence |
|
||||
|---|---|---|---|---|---|
|
||||
| Zeroed heap allocation/free | Working | Working | Working; rejected use after free/double free | Gap outside documented Wasm subset; direct Wasm rejects | [heap allocation](../tests/heap_new.sh), [Wasm tier](../docs/ZX.md) |
|
||||
| Owned `Vec` operations | Working | Working, physical OOM may terminate | Working, allocation failures recoverable where declared | Gap outside Wasm subset; direct Wasm rejects | [owned values](../docs/OWNED_VALUES.md), [vector test](../tests/vec.sh) |
|
||||
| Direct/aggregate vector drops | Working on block, return, break, continue | Working | Working | Gap; direct Wasm rejects until implemented | [aggregate safety](../tests/aggregate_vec_safety.sh) |
|
||||
| Vector field/member moves | Working with listed source restrictions | Working | Working | Gap; direct Wasm rejects until implemented | [aggregate safety](../tests/aggregate_vec_safety.sh), [move expression](../tests/vec_move_expression.sh) |
|
||||
| Text and `TextView` | Borrowed bytes observable | Snapshot | Snapshot | Owned strings in Wasm subset; other text forms are a Gap and reject | [capabilities](../docs/CAPABILITIES.md), [text view mutation](../tests/text_view_mutation.sh) |
|
||||
| Native pointers | Native lifetime/alias responsibility | Native Go pointer rules | Opaque host handles in bundle ABI | Linear-memory boundary/provider values | [ZX host ABI](../docs/ZX.md), [capabilities](../docs/CAPABILITIES.md) |
|
||||
| Instance global state | Native instance data | Go program state | Independent mutable slots per instance | Independent bindings/linear memory per instance | [component state](../docs/ZX.md), [component engine test](../tests/bundle_component_test.c) |
|
||||
|
||||
## Calls, concurrency, fuel, and traps
|
||||
|
||||
| Feature | Current behavior | Evidence |
|
||||
|---|---|---|
|
||||
| Argument and compound order | Working: left-to-right call arguments; destination read before compound right side on C, Go, ZX. | [call order](../tests/call_order.sh), [compound order](../tests/compound_order_cases.zi) |
|
||||
| Bounded execution | Working by explicit host selection. The engine and Wasm count calls and loop iterations; cumulative limited open includes initialization and every run. | [ZX limits](../docs/ZX.md), [step limit](../tests/bundle_step_limit.sh) |
|
||||
| CPU parallel regions | Current baseline: C threads on supported hosts; Go/ZX serial downgrade and reverse-region serialization are assembly-target Gaps. The direct target rejects them until their promised parallel implementation exists. | [parallel test](../tests/parallel.sh), [native worker pool](../tests/spec/native_parallel_windows_test.zi) |
|
||||
| GPU regions | Every target reports an explicit Gap and rejects GPU selection; there is no CPU fallback. | [capabilities](../docs/CAPABILITIES.md), [assembly blocks](../tests/assembly_blocks.sh) |
|
||||
| Runtime traps | Working failure boundary: bounds, unreachable, host/fuel/stack and numeric contract failures stop the run. | [ZX contract](../docs/ZX.md), [engine](../cmd/compiler_exec.zi) |
|
||||
| Host capabilities | Working checked module/function ABI with provider preflight, bindings, mutable slice copyback and no overlap. | [host capabilities](../tests/host_capability.sh), [ZX host ABI](../docs/ZX.md) |
|
||||
| Component replacement | Working transactional ABI/state migration/rollback for portable components and supported Wasm memory interface. | [component contract](../docs/ZX.md), [web lifecycle](../tests/zx_web_lifecycle.sh) |
|
||||
|
||||
## Native extensions and foreign runtimes
|
||||
|
||||
| Feature | Working behavior and restriction | Evidence |
|
||||
|---|---|---|
|
||||
| GNU assembly variants | Current C/Go behavior may use a checked portable body. For the direct assembly target, a missing matching target/feature implementation is a Gap and rejects at preflight; no portable body or cgo bridge satisfies the cell. | [assembly](../tests/assembly.sh), [ZX assembly](../tests/zx_native_asm.sh), [Go assembly](../tests/go_assembly_cases.zi) |
|
||||
| C callbacks / `#c_call` | Native C ABI only; Go and ZX target preflight reject it before output. | [capabilities](../docs/CAPABILITIES.md), [compiler inventory](../tests/compiler_inventory_cases.zi) |
|
||||
| Go foreign types/maps | Go target extension only; opaque identity and scalar-union checks reject unsupported portable lowering. Renaming does not create a portable layout. | [compiler IR](../cmd/compiler_ir.zi), [capabilities](../docs/CAPABILITIES.md) |
|
||||
| OS libraries | Explicit foreign/library dependencies remain allowed; native platform service portability is defined per OS row, not by opcode presence. | [executable bundle](../tests/executable_bundle.sh), [architecture](../docs/ARCHITECTURE.md) |
|
||||
| Runtime assembly/C cache | Current native bundle cache is keyed by bundle/libraries/CPU/compiler sources; cached code can bypass program recheck only under documented boundary. | [native execution](../docs/ZX.md) |
|
||||
|
||||
## Maintained platform rows
|
||||
|
||||
| Platform / target row | Current verified surface | Target-specific restriction | Unknown verification |
|
||||
|---|---|---|---|
|
||||
| Linux x86-64, C, ZX and direct ELF | Current development host; source/saved-IR C, Go, ZX, direct `zx2native` ELF, threads, SIMD tiers, OS libraries and retained tests. | Native C parallel threads; SIMD ISA dispatch; Linux process/thread services. | A complete matrix needs fresh named toolchain/hardware evidence per future gate. |
|
||||
| Linux/Android ARMv7 | Portable ZX and generated C/Go; C SIMD fixtures cover NEON, VFP-only and scalar lanes; Android API 21 streams and optional four-ABI link paths. | 32-bit ARM ABI/CPU feature restrictions; optional NDK/QEMU/phone tooling. | Specific Android OS version/device combinations and non-SIMD execution are not established by this documentation pass. |
|
||||
| Linux/Android AArch64 | Portable ZX and generated C/Go; NEON codegen and QEMU execution documented. | AArch64 hardware-capability assembly selection; Android toolchain. | Fresh physical-platform coverage beyond documented fixtures is unknown. |
|
||||
| Linux/Android other CPU | Portable ZX and generated C/Go are the supported route. | No direct native row. | New architecture execution, including RISC-V, is proposed/unknown. |
|
||||
| Windows generated C/Go | Compiler/runtime platform code and Windows fixtures exist. | No direct native row. | No fresh Windows host execution in this documentation task. |
|
||||
| Windows portable ZX | The engine has no Linux-only service assumptions. | No native tier. | Fresh Windows host evidence unknown. |
|
||||
| macOS generated C/Go and portable ZX | Darwin build definitions and package/file fixtures exist. | Darwin SHA/random system libraries and ABI differ. | No fresh macOS execution in this documentation task. |
|
||||
| Browser/WebAssembly tier | Bundles lowered to wasm32 with per-instance memory, state, budget and lifecycle, tested in headless Chromium. | Subset listed above; unsupported constructs and provider rejection are direct-Wasm gaps. | Other browsers/versions and non-Chromium Wasm hosts are unknown. |
|
||||
| Wasm32 standalone tools | `zx2wasm` lowers verified ZX; the bundle Wasm tier runs it under an Emscripten `libziran`; optional Emscripten/wasmtime probes for SIMD and file-tree fixtures. | Requires installed Wasm CC/runtime; skipped when probes absent. | Current machine's optional tool availability is not execution evidence for target hosts. |
|
||||
| Go output on OS | Generated source follows Go runtime. | Serial parallel regions, snapshots, foreign runtime restrictions. | Exact OS/Go version combinations not covered by a fresh matrix run. |
|
||||
|
||||
## Retained check surface
|
||||
|
||||
The retained suite is physically pruned. `make check` builds the retained tool and runs every discovered `.sh` check unless filtered; `make check-bootstrap` compares checked-in generated compiler sources; both run with desktop display variables removed. This is the suite that must accompany later implementation work. See [Makefile](../Makefile) and [check planning](../tests/check_plan.zi). Hardware/tool-dependent scripts may still skip when their required external probe is absent; a skip is not target execution evidence.
|
||||
|
||||
## Unknown and proposed work
|
||||
|
||||
**Unknown now:** fresh Windows/macOS/Android/browser execution for this exact revision; Wasm constructs outside the documented subset; Go behavior on every OS/runtime pair; pointer aliases and foreign effects lacking checked summaries; all future-backend target cells until a named fixture runs. Optional-tool skips, cross-compilation, child receipts, and stored benchmark reports remain non-evidence.
|
||||
|
||||
**Required step-01 follow-up:** lower the contract into typed basic blocks and verifier records; define portable layouts and effects; encode cleanup/fuel regions explicitly; separate target extension records from portable opcodes; then choose an incompatible `.zx` version against the actual writer in step 05. Feature completion requires fresh source/saved-IR execution evidence for every required matrix cell, with legitimate target exclusions named rather than silently skipped.
|
||||
@@ -0,0 +1,132 @@
|
||||
# Assembly-target gap and error policy
|
||||
|
||||
Status: normative for the direct assembly target and the revision-28 executable
|
||||
path. This policy applies to every delivery milestone and completion matrix cell.
|
||||
|
||||
## Why gaps are not fallbacks
|
||||
|
||||
A fallback makes an unsupported path look successful. It can hide missing
|
||||
lowering, CPU support, host services, or target validation behind a different
|
||||
engine, compiler, or semantic implementation. The assembly target therefore has
|
||||
no fallback state.
|
||||
|
||||
Each feature/target cell has exactly one of these states:
|
||||
|
||||
- **Implemented** — the named implementation ran on the required target and has
|
||||
fresh retained evidence.
|
||||
- **Gap** — required work is missing. Selecting the cell fails before output or
|
||||
execution with its stable diagnostic.
|
||||
- **Excluded** — the contract deliberately does not promise the feature for that
|
||||
target, and capability output names the exclusion.
|
||||
- **Unknown** — implementation may exist, but the required execution evidence is
|
||||
absent. Unknown never counts as implemented.
|
||||
|
||||
`fallback`, `downgrade`, `skip`, `emulated`, `cross-compiled`, and `legacy engine`
|
||||
are evidence annotations, not successful assembly-target states. A comparison
|
||||
may run a legacy or reference engine only when the command selects it explicitly;
|
||||
that result cannot close a direct-target cell.
|
||||
|
||||
## Required failure boundary
|
||||
|
||||
The compiler and loader reject a gap at the earliest boundary that has enough
|
||||
information to identify it:
|
||||
|
||||
1. source/lowering rejects unsupported language operations;
|
||||
2. target preflight rejects CPU, OS/ABI, runtime, capability, and native-extension
|
||||
mismatches;
|
||||
3. object/link validation rejects missing formats, relocations, libraries, entry
|
||||
support, or signing facilities;
|
||||
4. loading rejects unavailable executable-memory, cache, or host integration.
|
||||
|
||||
Every rejection has a stable diagnostic code and reports the selected target,
|
||||
engine, missing feature or facility, and source origin when one exists. It must
|
||||
not run module initializers, call a host, open a window, execute an entry, invoke
|
||||
another backend, or overwrite the last valid output.
|
||||
|
||||
Examples of required errors include:
|
||||
|
||||
- a native target without a matching `#asm` implementation;
|
||||
- a required ISA feature absent from the selected CPU contract;
|
||||
- a parallel or GPU region without its promised target implementation;
|
||||
- a WebAssembly operation outside the direct Wasm lowering;
|
||||
- a missing host capability or foreign ABI adapter;
|
||||
- an unsupported object format, relocation, linker input, or platform signing
|
||||
facility;
|
||||
- a request to run a legacy or incompatible executable revision.
|
||||
|
||||
## Host capabilities and ABI veneers
|
||||
|
||||
Host capabilities and platform ABI veneers are separate contracts. A host
|
||||
capability is a portable, typed service named by linked ZX instructions and
|
||||
bound by an embedder or runtime provider. A platform veneer is direct-target
|
||||
code for entry, calling conventions, syscalls or system libraries, error
|
||||
handling, and process exit. CPU instruction selection is a third concern.
|
||||
|
||||
An implemented host capability does not satisfy a missing direct-target veneer,
|
||||
and an implemented veneer does not bind a portable host capability. Generated C
|
||||
or Go bindings are also independent: they may produce working platform binaries
|
||||
without closing the direct-native target cell. A missing veneer, unsupported
|
||||
service, or unavailable binding is rejected at preflight or link time without
|
||||
starting another engine.
|
||||
|
||||
The opt-in Linux x86-64 direct console veneer is implemented around an owned
|
||||
`_start`, Linux `write` syscall 1, `exit_group` syscall 231, and no libc, CRT,
|
||||
or dynamic linker. Its `write_all` retries `EINTR` and partial progress; other
|
||||
write failures take the image's fixed trap exit. This is execution evidence for
|
||||
the experimental AOT slice, not a completed target-row or native-ZX claim.
|
||||
|
||||
The implemented machine print subset covers read-only literal format strings,
|
||||
strings and text views by exact byte length, booleans, every fixed signed and
|
||||
unsigned integer type, deterministic float32/float64 output, and `%%`. A
|
||||
missing target-owned formatter, veneer or service reports
|
||||
`assembly.gap.machine-platform-service-unavailable`. None permits a C/Go route
|
||||
or portable interpreter to start.
|
||||
|
||||
## Target preflight codes
|
||||
|
||||
Target preflight uses three stable codes, all hard errors:
|
||||
|
||||
- `assembly.gap.target-unimplemented` — the selected CPU/OS row is Gap,
|
||||
Excluded or Unknown. Only an Implemented row passes.
|
||||
- `assembly.gap.cpu-feature` — the row does not implement a required CPU
|
||||
feature, including a feature of another CPU family.
|
||||
- `assembly.gap.os-service` — the row does not supply a required operating
|
||||
system service.
|
||||
|
||||
The message names the selected row, the `assembly` engine, the row state and
|
||||
the missing feature or service. The check needs no input, so it runs before
|
||||
any source or saved `.zir` is read and both report the same gap. `ziran
|
||||
capabilities --json` lists every row's state and code under
|
||||
`assembly_targets`; `ziran explain` describes each code.
|
||||
|
||||
## Explicit engine and target selection
|
||||
|
||||
Portable execution, native execution, direct Wasm, C, and Go are separate
|
||||
targets. One may be the documented default of a command, but none is a rescue
|
||||
path for another. An explicit native request never starts the interpreter; an
|
||||
explicit portable request never invokes native code; direct Wasm never routes
|
||||
through generated C. Old executable revisions produce a rebuild error instead of
|
||||
selecting an old runtime.
|
||||
|
||||
CPU variants are also explicit target contracts. If the chosen variant requires
|
||||
features the selected or running CPU lacks, preflight fails. A lower-feature
|
||||
variant may be selected only when it is an independently declared implementation
|
||||
of that exact target cell, not a portable body or another engine disguised as
|
||||
successful native execution.
|
||||
|
||||
## Tests and completion accounting
|
||||
|
||||
Every Gap cell needs a negative fixture that checks:
|
||||
|
||||
- the stable diagnostic code and relevant target/feature fields;
|
||||
- failure before initializer, host, entry, or output replacement side effects;
|
||||
- identical rejection from source and saved `.zir` where both inputs apply;
|
||||
- capability and inspection output reporting the same gap.
|
||||
|
||||
Every Implemented cell needs positive source/saved-IR execution evidence on its
|
||||
named target. Optional tools or hardware may leave a cell Unknown, but tests may
|
||||
not silently skip it and completion reports may not round it up.
|
||||
|
||||
Milestones and final completion count only Implemented cells and explicit
|
||||
Excluded cells. Any Gap, Unknown, fallback, downgrade, skip, or substituted
|
||||
engine keeps its gate open.
|
||||
@@ -0,0 +1,285 @@
|
||||
# Lowered instruction binary format
|
||||
|
||||
Status: foundational codec for steps 02 and 05. This is not the ZX container
|
||||
revision from step 05, does not wrap checked `.zir`, and is not an installed
|
||||
execution format by itself.
|
||||
|
||||
The implementation is
|
||||
[`cmd/compiler_exec_serial.zi`](../cmd/compiler_exec_serial.zi). It serializes
|
||||
the complete current `LirProgram` record with explicit fields. It never copies
|
||||
a C struct, stores a host pointer, depends on host alignment, or uses native
|
||||
integer byte order.
|
||||
|
||||
## Public API and ownership
|
||||
|
||||
The exported Ziran API is:
|
||||
|
||||
```zi
|
||||
LirWrite(program: LirProgram, output: []u8) -> LirCodecResult
|
||||
LirRead(owner: *LirReadOwner, input: string, limits: LirLimits) -> LirCodecResult
|
||||
LirReadProgram(owner: *LirReadOwner) -> LirProgram
|
||||
LirReadFree(owner: *LirReadOwner)
|
||||
```
|
||||
|
||||
Normal generated-module naming applies. C consumers see the
|
||||
`compiler_exec_serial_` prefix; Go and portable callers use the generated module
|
||||
API rather than a separate ABI shim.
|
||||
|
||||
`LirWrite(program, [])` validates the program and returns the exact required
|
||||
`size`. A nonempty output shorter than that size returns `Output`, reports the
|
||||
same size, and changes no byte. A sufficient output receives exactly `size`
|
||||
bytes; any suffix beyond that size is unchanged. The writer traverses every
|
||||
table in stored ID order, so the same program produces the same bytes.
|
||||
|
||||
`LirReadOwner` must start zero-initialized (ordinary Ziran locals do). `LirRead`
|
||||
first releases any preceding value, makes three bounded passes (shape, copied
|
||||
data, then borrowed views), and calls `LirVerify` before reporting success. It
|
||||
copies all strings and constant byte arrays. The input may therefore be changed
|
||||
or released as soon as the call returns. On any failure the owner is empty.
|
||||
|
||||
`LirReadProgram` returns a borrowed program. Every table, nested slice and
|
||||
string in it expires at the next `LirRead` or `LirReadFree` on that owner.
|
||||
Consume those views first. Empty and repeated frees are harmless. The owner
|
||||
must not be moved or resized while a program view is live, and input to a new
|
||||
read must not alias the owner's preceding storage.
|
||||
|
||||
These rules use ordinary Ziran slices and owned vectors, so they apply to C,
|
||||
Go, and engine reads without a host-only allocator or garbage-collected
|
||||
lifetime exception.
|
||||
|
||||
## Integer and sequence encodings
|
||||
|
||||
Every integer is little-endian and has the width named below:
|
||||
|
||||
- `u8`, `u32`, `u64`: unsigned 8-, 32-, and 64-bit values.
|
||||
- `s32`, `s64`: the two's-complement bit pattern written as `u32` or `u64`.
|
||||
- `string` and byte slice: `u64 byte_count`, followed by exactly those bytes.
|
||||
- ID/type/value list: `u32 count`, followed by `count` `s32` elements.
|
||||
- record/table count: `u32 count`.
|
||||
|
||||
Strings and byte slices are binary. Embedded NUL is never a terminator. The
|
||||
current `LirVerify` policy still rejects NUL in module, source, global and
|
||||
function names; such a file reaches verification as binary data and returns
|
||||
`Verify`, rather than being truncated by the codec.
|
||||
|
||||
Counts are limited to `INT32_MAX`, because lowered IDs are signed 32-bit
|
||||
values. The whole encoded file and the default decoded-storage budget are at
|
||||
most 256 MiB. Caller-supplied `LirLimits` independently bound types, functions,
|
||||
blocks, values, instructions, decoded storage and graph work. All additions,
|
||||
multiplications, offsets and lengths are checked before allocation or slicing.
|
||||
|
||||
## Header and section directory
|
||||
|
||||
The fixed header is 64 bytes:
|
||||
|
||||
| Offset | Field | Required value |
|
||||
|---:|---|---|
|
||||
| 0 | `u32 magic` | `0x52494c5a` (`ZLIR`) |
|
||||
| 4 | `u32 format_version` | `1` |
|
||||
| 8 | `u32 lir_schema_version` | current `LirVersion` |
|
||||
| 12 | `u32 header_size` | `64` |
|
||||
| 16 | `u64 required_features` | bit 0 (`base`) only |
|
||||
| 24 | `u64 flags` | `0` |
|
||||
| 32 | `u32 section_count` | `1` or `2` |
|
||||
| 36 | `u32 reserved` | `0` |
|
||||
| 40 | `u64 total_size` | exact input byte count |
|
||||
| 48 | `u64 directory_offset` | `64` |
|
||||
| 56 | `u64 reserved` | `0` |
|
||||
|
||||
Each directory entry is 24 bytes:
|
||||
|
||||
```text
|
||||
u32 kind
|
||||
u32 flags
|
||||
u64 offset
|
||||
u64 size
|
||||
```
|
||||
|
||||
Entry 0 is always kind 1 (`core`) with flag bit 0 (`required`). Entry 1, when
|
||||
present, is kind 2 (`debug`) with flags zero. Directory and section order are
|
||||
canonical. The core begins immediately after the directory, debug immediately
|
||||
after core, and the final section ends at `total_size`. Gaps, overlaps, unknown
|
||||
sections, unknown flags, nonzero reserved fields, truncation and trailing bytes
|
||||
are rejected. Unknown required-feature bits are rejected before any table
|
||||
allocation.
|
||||
|
||||
Debug is present exactly when the program contains at least one source or
|
||||
origin. It is omitted when both tables are empty. A consumer that strips debug
|
||||
must also clear every function/instruction origin to `LirNoId` before producing
|
||||
a new verified file.
|
||||
|
||||
## Core section
|
||||
|
||||
Fields occur exactly in this order:
|
||||
|
||||
```text
|
||||
s32 program.version
|
||||
s32 program.entry
|
||||
|
||||
u32 module_count
|
||||
repeat module_count:
|
||||
string module
|
||||
|
||||
u32 type_count
|
||||
repeat type_count:
|
||||
u32 kind
|
||||
s32 bits
|
||||
u32 flags # bit 0 signed, bit 1 native_width
|
||||
s32 element
|
||||
s64 count
|
||||
s32 result
|
||||
list<s32> fields
|
||||
list<s32> parameters
|
||||
|
||||
u32 constant_count
|
||||
repeat constant_count:
|
||||
s32 type
|
||||
u64 bits
|
||||
bytes data
|
||||
|
||||
u32 global_count
|
||||
repeat global_count:
|
||||
s32 module
|
||||
string name
|
||||
s32 type
|
||||
s32 constant
|
||||
u32 flags # bit 0 writable
|
||||
|
||||
u32 function_count
|
||||
repeat function_count:
|
||||
s32 module
|
||||
string name
|
||||
list<s32> parameters
|
||||
s32 result
|
||||
u32 calling
|
||||
u32 flags # bit 0 external, bit 1 variadic
|
||||
list<s32> values
|
||||
u32 block_count
|
||||
repeat block_count:
|
||||
list<s32> parameters
|
||||
u32 instruction_count
|
||||
repeat instruction_count:
|
||||
u32 op
|
||||
s32 result
|
||||
list<s32> operands
|
||||
u32 edge_count
|
||||
repeat edge_count:
|
||||
s32 block
|
||||
list<s32> arguments
|
||||
u64 immediate
|
||||
s32 symbol
|
||||
u32 alignment
|
||||
s32 effect
|
||||
s32 origin
|
||||
s32 entry
|
||||
s32 origin
|
||||
```
|
||||
|
||||
This covers every current schema field, including currently verifier-gated
|
||||
types, constants, calling forms and opcodes. The decoder preserves their bytes
|
||||
and field values, then lets the authoritative verifier accept or reject the
|
||||
result. Enum values beyond the current declared range and flag bits outside
|
||||
the masks above are noncanonical format errors before verification.
|
||||
|
||||
## Checked array value operations
|
||||
|
||||
LIR schema 3 extends `extract` and `insert` with dynamic fixed-array indices.
|
||||
Their existing immediate-index forms remain: `extract` takes one aggregate
|
||||
operand, and `insert` takes an aggregate followed by the replacement value.
|
||||
The member ordinal is in `immediate`.
|
||||
|
||||
Dynamic `extract` takes an array and an integer index. Dynamic `insert` takes
|
||||
an array, a replacement element and an integer index. Their `immediate` is zero.
|
||||
The verifier requires an actual array type, a fixed integer index and an exact
|
||||
element/result type match; a record cannot use either dynamic form.
|
||||
|
||||
Execution rejects negative signed indices and indices greater than or equal
|
||||
to the count, including zero-sized elements and zero-length arrays. Narrow
|
||||
signed values are interpreted at their declared width. An accepted index
|
||||
selects the packed element interval; extraction copies that element, and
|
||||
insertion copies the array before replacing the selected interval. Array
|
||||
values retain value semantics.
|
||||
|
||||
Dynamic operations can trap even when their result is unused. Optimization
|
||||
must retain that check and its source/effect ordering. Source lowering captures
|
||||
every destination index and checks it before evaluating the right-hand side.
|
||||
The native encoder performs a bounds check followed by direct indexed frame
|
||||
addressing rather than an element-by-element dispatch scan.
|
||||
|
||||
## Debug section
|
||||
|
||||
```text
|
||||
u32 source_count
|
||||
repeat source_count:
|
||||
string source
|
||||
|
||||
u32 origin_count
|
||||
repeat origin_count:
|
||||
s32 file
|
||||
s32 line
|
||||
s32 column
|
||||
s32 end_line
|
||||
s32 end_column
|
||||
s64 begin
|
||||
s64 end
|
||||
s32 parent
|
||||
```
|
||||
|
||||
Source strings are copied like all other strings. Origin parent chains and
|
||||
file references are checked by `LirVerify`; hostile depth is handled by its
|
||||
bounded iterative validation.
|
||||
|
||||
LIR schema version 3 retains the checked source end-line/end-column coordinates
|
||||
introduced in schema 2.
|
||||
Coordinates are one-based; `end_line = end_column = 0` explicitly means the
|
||||
end position is unavailable. A known end cannot precede the start. Byte offsets
|
||||
are either an ordered nonnegative pair or `begin = end = -1` when unavailable.
|
||||
The source/saved-IR adapter preserves the checked graph's line/column positions
|
||||
and emits unknown byte offsets: that graph does not contain byte coordinates.
|
||||
It never rereads source text to invent offsets. Format framing remains version
|
||||
1, but readers reject previous LIR schemas with `Version`; rebuild `.zx`
|
||||
artifacts rather than mixing different instruction or debug contracts.
|
||||
|
||||
## Validation and error boundary
|
||||
|
||||
Framing errors are reported as `LirCodecProblem`: magic/version/feature,
|
||||
flags/field/section, overlap, truncation/trailing, count/limit/allocation,
|
||||
short output, or invalid owner. A structurally decoded program that fails the
|
||||
lowered verifier returns `Verify` and the complete `LirDiagnostic`.
|
||||
|
||||
The reader does not trust producer flags, a previous successful check, or
|
||||
optional debug data. It constructs no executable program until the full file
|
||||
is canonical, all caller limits hold, all owned storage is complete, and
|
||||
`LirVerify` succeeds. Re-encoding a successful decode is byte-exact.
|
||||
|
||||
## Heap blocks
|
||||
|
||||
`resize(pointer: *T, old_count, new_count) -> *T` is the one heap instruction.
|
||||
Its number follows `unreachable`, so every earlier instruction keeps its
|
||||
encoding. `T` is any sized value type a checked view may hold; both counts are
|
||||
integers and the result has the pointer's type. A null pointer with
|
||||
`old_count` 0 allocates, `new_count` 0 frees and gives null, and any other
|
||||
call gives a block that keeps the first `min(old_count, new_count)` elements
|
||||
and zero-fills the rest. When the engine cannot hold the request, the result
|
||||
is null and the old block stays valid. Only a block's own base pointer, with
|
||||
its exact element count, may be resized or freed. The instruction is effectful
|
||||
and produces a value, so optimization keeps it and its order.
|
||||
|
||||
## Current boundary
|
||||
|
||||
- This file has no imports, exports, capability/link tables, assets, native
|
||||
variants, proofs, signatures, compression, checksum, or content identity.
|
||||
Those belong to the future incompatible ZX revision and linker in step 05.
|
||||
- It does not execute instructions. The portable engine is step 04.
|
||||
- It accepts exactly the current verifier's semantic subset. In particular,
|
||||
verifier-gated schema fields remain explicitly encoded but cannot become an
|
||||
executable decoded program until verifier semantics exist.
|
||||
- Format version 1 has no compatibility promise with the planned final ZX
|
||||
container. Readers reject other versions with an explicit rebuild boundary.
|
||||
|
||||
Run the source/saved-IR C, Go and VM regression with:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY build-queue -- \
|
||||
sh tests/lowered_serial.sh build/bin/ziran
|
||||
```
|
||||
@@ -0,0 +1,296 @@
|
||||
# Target-neutral machine IR contract
|
||||
|
||||
Status: implemented for Linux x86-64 SysV as the verified pre-allocation boundary for the
|
||||
current lowered-IR subset, deterministic [register allocation](#register-allocation), a
|
||||
separate allocated-program verifier, and a [direct x86-64 encoder](#machine-code-encoder)
|
||||
that turns a verified allocated program into an in-memory code image with relocations.
|
||||
`zx2native` selects this encoder for its only native executable path; a native ZX loader
|
||||
remains unsupported. The implemented native call ABI is general-register only; float and
|
||||
vector call arguments and results and stack-passed arguments are [unsupported
|
||||
forms](#supported-call-forms) that fail with a stable diagnostic.
|
||||
|
||||
## Public boundary and ownership
|
||||
|
||||
The target surface is defined by `compiler_target.zi`:
|
||||
|
||||
- `TargetDescribe` describes supported architecture/OS combinations.
|
||||
- `TargetValid` checks that a description is canonical rather than accepting a caller-modified
|
||||
register or ABI model.
|
||||
- `TargetMachineLoweringSupported` separately states whether the current machine lowerer can
|
||||
execute that description. At present this is Linux x86-64 SysV only.
|
||||
|
||||
The owned machine-IR surface is defined by `compiler_machine_ir.zi`,
|
||||
`compiler_machine_lower.zi`, `compiler_machine_verify.zi`, `compiler_abi.zi`,
|
||||
`compiler_regalloc.zi`, `compiler_machine_verify_allocated.zi`, and `compiler_x86_64.zi`
|
||||
(which reuses the byte encoders in `compiler_x86_bytes.zi`):
|
||||
|
||||
- `MachineDefaultLimits` and `MachineDefaultOptions` provide bounded defaults.
|
||||
- `MachineLower(owner, lir, target, options, limits)` verifies the input LIR, copies its
|
||||
required metadata, lowers it, verifies the resulting machine IR, and publishes the owner
|
||||
only after success.
|
||||
- `MachineProgramView(owner)` returns a borrowed flat view while the owner is valid.
|
||||
`MachineFree(owner)` is repeatable and invalidates all prior views.
|
||||
- `MachineVerify(program, limits)` validates the target, table bounds, metadata, register
|
||||
classes, operand constraints, flags lifetimes, calls, stack objects, parallel copies, and
|
||||
relocations without repairing malformed input.
|
||||
- `compiler_abi.zi` is the only module that names target registers. The lowerer, allocator and
|
||||
verifiers ask it for argument and result registers, call clobbers, the fixed registers of
|
||||
division and shifts (`MachineAbiFixedRegister`), which call classes the native ABI
|
||||
implements (`MachineAbiCallRegisterClass`) and which relocation addends a target can hold
|
||||
(`MachineAbiRelocationAddend`). Its register enum is file-private.
|
||||
- `RegAllocAllocate(owner, target, limits)` replaces a verified `Virtual` program with a
|
||||
verified `Allocated` one ([register allocation](#register-allocation)).
|
||||
- `MachineVerifyAllocated(program, limits)` checks an allocated program independently of the
|
||||
allocator.
|
||||
- `MachineX64Validate`, `MachineX64Measure` and `MachineX64Encode` verify and encode an
|
||||
allocated program ([machine-code encoder](#machine-code-encoder)).
|
||||
|
||||
Schema version 2 adds the allocation stage. `MachineProgram.stage` is `Virtual` after
|
||||
lowering and `Allocated` after `RegAllocAllocate`; every operand carries the SSA `value` it
|
||||
reads or writes (or none), stack objects carry a frame `offset` and the `value` they hold,
|
||||
and allocated programs add one `MachineFrame` per function, explicit `Spill`/`Reload`
|
||||
opcodes with a `MachineSpill` record each, and the per-bank scratch registers.
|
||||
|
||||
`MachineOwner` owns every published table. Source names and function names are copied into
|
||||
its byte table and referenced by offsets; source origins, type shape, aggregate members,
|
||||
function signatures, globals, CFG records, operands, calls, copies, stack objects, and
|
||||
relocations do not borrow LIR storage. Lowering the same valid input and target produces the
|
||||
same table order and contents.
|
||||
|
||||
## Representation
|
||||
|
||||
`MachineProgram` is a deterministic collection of flat, index-addressed tables. Functions
|
||||
own contiguous block, virtual-register, and stack-object ranges. Blocks own contiguous
|
||||
instruction ranges. Instructions own contiguous operand and edge ranges. Edges reference
|
||||
contiguous simultaneous-copy ranges. Aggregate member and function-parameter type IDs share
|
||||
the owned `type_ids` table.
|
||||
|
||||
Operands distinguish virtual and physical registers, immediates, blocks, functions, stack
|
||||
objects, and globals. Each operand records its use/define role, register class, optional
|
||||
fixed register, and optional tie to another operand. Condition results use an explicit flags
|
||||
virtual: `Compare` defines it and the adjacent `SetCondition` consumes it. Calls carry fixed
|
||||
argument/result constraints plus general, float, and vector clobber masks. A `Fuel` check is
|
||||
explicit before liveness: its first operand is the amount, its second names the instance
|
||||
fuel counter through a `FuelCounter` relocation, and it defines (so clobbers) a fresh flags
|
||||
virtual. Relocations identify the exact instruction operand and symbol rather than hiding
|
||||
symbol references in an encoder-specific payload.
|
||||
|
||||
The current lowerer covers the verified LIR operations represented by the machine opcode
|
||||
enum: scalar integer and float operations, comparisons and conversions, aggregate pseudos,
|
||||
checked-memory/address pseudos, direct and indirect calls, CFG transfers, returns, fuel,
|
||||
traps, and unreachable control. These are pre-allocation pseudos; their presence does not
|
||||
claim that a complete native encoder can execute every lowered program.
|
||||
|
||||
`Allocate` remains an explicit effectful machine pseudo. Every dynamic execution must
|
||||
produce fresh storage whose lifetime lasts until that allocating frame exits, including
|
||||
repeated visits to one instruction in a loop or recursive activation. It therefore is not
|
||||
represented as `StackAddress` plus one static stack object per instruction site. Allocation
|
||||
and encoding must preserve the pseudo until they implement that exact dynamic frame-storage
|
||||
behavior.
|
||||
|
||||
Aggregate values are stack-class virtuals whose frame objects follow the plan of
|
||||
`compiler_machine_aggregate.zi`, the native counterpart of zx2wasm's aggregate slots. Values
|
||||
whose lifetimes never overlap share one object, so an `AggregateInsert` whose destination is
|
||||
its source's object changes only its member, and a block parameter that shares its
|
||||
arguments' object needs no edge copy. On x86-64 an extract read only by extracts in its own
|
||||
block is a view: `StackAddress` and `FieldAddress` or `ElementAddress` compute its address
|
||||
once, shared with an earlier view of the same storage and member that dominates it, and
|
||||
`AggregateExtract`/`AggregateInsert` forms whose aggregate operand is that pointer register
|
||||
read and change its members in place. A changed view put back where it came from emits
|
||||
nothing. A dynamic member's trailing immediate, like the optional fourth `ElementAddress`
|
||||
operand, is the bound the shared LIR facts prove its index below, or 0; a proven index is
|
||||
not checked.
|
||||
|
||||
## Linux x86-64 ABI facts
|
||||
|
||||
Register numbers follow x86-64 encoding order. General-register argument constraints are
|
||||
RDI, RSI, RDX, RCX, R8, and R9; float arguments use XMM0 through XMM7 independently. General
|
||||
results use RAX and float results use XMM0. Calls record the SysV caller-clobbered general
|
||||
registers and all sixteen XMM registers. Division fixes the dividend and result to RAX and
|
||||
clobbers RDX; shift counts use RCX. The lowerer obtains all of these from `compiler_abi.zi`
|
||||
queries for the described target rather than naming x86-64 registers itself.
|
||||
|
||||
The general allocatable mask is `0xffcf`; bits 4 and 5 are excluded by the `0x30` reserved
|
||||
mask, so RSP and RBP can never be assigned as ordinary virtual register locations. Float and
|
||||
vector registers are separate logical classes but share the same physical XMM bank
|
||||
(`float_vector_overlap = true`). Allocation must therefore treat a live float and vector
|
||||
assignment to the same physical number as interference.
|
||||
|
||||
Aggregate sizes use Ziran's packed internal layout. Aggregate arguments/results are
|
||||
represented through stack objects and are deliberately distinct from the external System V
|
||||
aggregate classification rules. C, System, and Host calling forms, including external
|
||||
aggregate ABI, varargs, and callbacks, are rejected explicitly; they are not silently
|
||||
treated as internal calls.
|
||||
|
||||
### Supported call forms
|
||||
|
||||
Machine IR describes the whole internal call shape: float arguments carry their XMM
|
||||
constraints, a seventh integer or any aggregate argument is counted in
|
||||
`stack_argument_bytes`, and allocation lays out the outgoing area. The implemented native
|
||||
call ABI is narrower. A call may pass at most six arguments, each a general-class value in
|
||||
its ABI register in order, and may return nothing or a general-class value in RAX.
|
||||
`MachineVerifyAllocated` rejects every other call with `Unsupported` at the first offending
|
||||
argument or result operand, or at the call when it reserves stack argument bytes: float and
|
||||
vector arguments and results, aggregate arguments, arguments beyond the sixth, and any
|
||||
outgoing stack bytes. The check runs before an encoder starts, so no unsupported call
|
||||
reaches encoding or another engine. Incoming stack parameters of a function that is not
|
||||
called natively remain representable and are verified against the parameter order. The full
|
||||
SysV argument/result classification, including float and stack passing, is later work,
|
||||
tracked in `plans/open-work.md`; it is not partially implemented.
|
||||
|
||||
## Described targets versus executable targets
|
||||
|
||||
Canonical descriptions exist for maintained x86-64, ARMv7, AArch64, and wasm32 OS
|
||||
combinations so later allocation and backend work shares one target model. A valid
|
||||
description is not an implementation claim. Linux and Android x86-64, AArch64 and ARMv7
|
||||
lower, allocate and encode; wasm32, Windows, macOS and WASI fail machine lowering with
|
||||
`UnsupportedTarget`.
|
||||
|
||||
## Register allocation
|
||||
|
||||
`RegAllocAllocate(owner, target, limits)` in `compiler_regalloc.zi` takes the owner's
|
||||
verified `Virtual` program and, on success, replaces it with a verified `Allocated` program.
|
||||
The allocation is built in a separate owner and verified with `MachineVerifyAllocated`
|
||||
there; only then are the two owners' tables exchanged with `VecSwap`, which moves storage
|
||||
without allocating, so no step after the owner starts changing can fail. On any failure,
|
||||
including one the allocated verifier finds in the built program, the owner keeps its
|
||||
original program and the `MachineDiagnostic` names the input function, block, instruction,
|
||||
operand and virtual: an allocated instruction maps back to the input instruction it rewrote,
|
||||
with operands at the same positions, and a transfer the allocator inserted reports only its
|
||||
function and virtual. Each function is processed in a fixed order:
|
||||
|
||||
1. `MachineVerify` and `MachineVerifyFuel` run first. Every control-flow cycle must pass a
|
||||
fuel check, and every function a direct call or a taken address can reach must charge fuel
|
||||
in its entry block before any call. A missing or malformed check fails with `Fuel`.
|
||||
2. Constraints become explicit transfers. A fixed input is moved into its register just
|
||||
before the instruction, a fixed result out of it just after, a register parameter out of its
|
||||
incoming register at entry, and a tied input without a fixed register is copied into a short
|
||||
interval that the result must reuse. Division keeps the dividend and quotient in RAX and RDX
|
||||
clobbered across the instruction, shift counts use RCX, and call arguments and results use
|
||||
their ABI registers.
|
||||
3. Block liveness is solved over the item order, then each SSA virtual gets one hull
|
||||
interval with its use positions. Block parameters are defined at the block start; edge-copy
|
||||
sources are used at the predecessor terminator.
|
||||
4. Linear scan runs per register bank (general; float and vector share the XMM bank on
|
||||
x86-64) inside the target's allocatable masks minus one scratch register per bank (R11 and
|
||||
XMM15). Fixed operands, early clobbers and call clobbers block registers. An interval is
|
||||
split where its register becomes blocked; under pressure the value with the farthest next
|
||||
required use goes to memory until that use. Values live across a call take callee-saved
|
||||
registers (RBX, R12–R15) or are spilled with reason `Call`.
|
||||
5. Split boundaries, fixed transfers, block-parameter copies and edge location fixes become
|
||||
`Move`, `Spill` and `Reload` instructions. Each edge's copies are one parallel copy,
|
||||
sequentialized with cycles broken through the scratch register or a frame `Temporary`; a
|
||||
branch edge that needs moves gets its own block (`lir_block` is -1). Allocator transfers
|
||||
preserve flags, so they may sit between a compare and its consumer. A transfer with equal
|
||||
source and destination register renames a value and encodes no bytes.
|
||||
6. The frame pointer is pushed on entry. Callee-saved registers the function writes get
|
||||
`CalleeSave` homes; values, spills and temporaries sit at aligned negative frame-pointer
|
||||
offsets; outgoing stack arguments occupy the 16-byte aligned bottom of the frame; incoming
|
||||
stack arguments start 16 bytes above the frame pointer in parameter order. The frame size is
|
||||
a multiple of 16.
|
||||
|
||||
Every `Spill` and `Reload` has a `MachineSpill` record with its value, slot, register,
|
||||
reason (`Pressure`, `Call`, `Fixed`, `Parameter` or `Cycle`) and nearest source origin.
|
||||
Flags-class operands or copies, a virtual read-modify-write operand, conflicting fixed
|
||||
registers, broken ties, call clobber masks that keep caller-saved registers or clobber
|
||||
reserved ones, non-internal calling forms, unsupported targets and exceeded limits fail
|
||||
explicitly. Nothing is routed to another engine.
|
||||
|
||||
`MachineVerifyAllocated(program, limits)` in `compiler_machine_verify_allocated.zi` is
|
||||
independent of the allocator. It rejects virtual operands, unresolved edge copies, registers
|
||||
outside the bank masks (scratch registers only in transfers), fixed-register mismatches,
|
||||
broken ties, malformed transfers, bad relocations, relocation addends the target cannot hold
|
||||
(a direct call, function address or fuel counter carries none; a global address carries a
|
||||
signed 32-bit addend), [unsupported call forms](#supported-call-forms), spill records that
|
||||
disagree with their instruction, misplaced fuel checks and frame layouts that are
|
||||
misaligned, overlapping, missing callee-saved homes or whose incoming stack arguments
|
||||
disagree with the parameter order. A forward dataflow over registers, flags and stack
|
||||
objects then proves that every use finds its value: a wrong value is `Interference`, a value
|
||||
lost to a call or clobber is `Clobber`, a missing one is `Undefined`, and a parallel copy
|
||||
that reads a source it already overwrote is `Copy`.
|
||||
|
||||
## Machine-code encoder
|
||||
|
||||
`compiler_x86_64.zi` encodes a program that passes `MachineVerifyAllocated` for Linux x86-64
|
||||
SysV into an in-memory image: code bytes, function, block and instruction offsets, and
|
||||
PC-relative 32-bit relocations for global addresses, the fuel counter and the trap handler.
|
||||
Direct calls and function addresses inside the image are resolved by the encoder. A
|
||||
measuring pass and an exactly sized writing pass must agree on every offset.
|
||||
`MachineX64Encode` publishes the image only after verification, form checks and measuring
|
||||
succeed; any diagnostic leaves the output owner unchanged. Every instruction form the
|
||||
encoder does not implement is a hard diagnostic, never another engine.
|
||||
|
||||
### ARMv7 (A32)
|
||||
|
||||
`compiler_armv7.zi` encodes for armv7a Linux and Android. LIR is target-neutral: pointers
|
||||
and function values are 8-byte slots and `s64` is the common integer, while the pipeline
|
||||
keeps one physical register per virtual. ARMv7 therefore describes its general bank as
|
||||
register pairs, so allocation, verification and lowering stay as they are:
|
||||
|
||||
- Pair n is (r2n, r2n+1) for n = 0..4; pair 5 is (r12, lr), the bank scratch, so r12 and lr
|
||||
are free inside any instruction and lr is saved by every prologue. r10 is the encoder's
|
||||
temporary and the base it rebases a frame slot beyond A32's 4 KiB reach into; r11 is the
|
||||
frame pointer. Calls clobber pairs 0, 1 and 5; pairs 2-4 (r4-r9) are callee-saved.
|
||||
- A value of 32 bits or less lives in the even register, a 64-bit value in both, low word
|
||||
first. Raw machine addresses are 32-bit. Floats are d0-d15 (VFPv3-D16), f32 in s(2n); d0-d7
|
||||
are caller-saved, d7 the float scratch.
|
||||
- Between generated functions: general arguments in pairs 0 and 1, floats in d0-d5, the rest
|
||||
on the stack in 8-byte slots; results in pair 0 or d0; the record-result address in r10.
|
||||
Indirect calls BLX pair 4. The entry widens a narrower result into r1 for its C caller.
|
||||
Generated code reaches C only through the loader's veneers, so softfp never meets it.
|
||||
- 64-bit arithmetic is pair sequences. 64-bit divide and remainder and int64/float conversions
|
||||
call loader helpers through a `RuntimeHelper` relocation (symbol = `MachineHelper`),
|
||||
operands and result at sp; the helper and resize veneers keep every register but lr.
|
||||
Addresses are MOVW/MOVT relocation halves (addend 0 and 2); calls and veneers are BL.
|
||||
- A dynamic element's address goes in lr (the address scratch), leaving r10 for the
|
||||
instruction's other frame operand, and the frame layout puts the pointer runtime's arena
|
||||
mark and chain beside the callee saves, so those sequences never rebase.
|
||||
- Copies and zeroing of 64 bytes or more run a word loop (r10 and lr walk the two sides, r0
|
||||
counts and is kept at sp meanwhile), as AArch64 runs a 16-byte q31 loop and x86-64 an xmm15
|
||||
loop, so code size does not grow with record size.
|
||||
|
||||
## Direct native code versus generated-code exporters
|
||||
|
||||
Direct native code means that Ziran's own encoders write machine code from verified IR, with
|
||||
no generated C, external assembler, C compiler or system linker. `zx2native` uses the
|
||||
machine-IR path: it lowers verified ZX through the machine pipeline, writes the resulting
|
||||
Linux x86-64 image as an ELF executable, and never reroutes unsupported forms to another
|
||||
engine. Source and saved `.zir` first go through optimized ZX serialization and
|
||||
verification. In-memory native ZX loading and runtime cutover remain milestone M3.
|
||||
|
||||
The C target (generated C compiled by a C toolchain) and the Go target (generated Go built
|
||||
by the Go toolchain) also produce runnable binaries, but they are separate exporters with
|
||||
their own toolchains and test rows. They are never a fallback for direct native code: a form
|
||||
the native path does not implement fails with its diagnostic and is not rerouted to C, Go,
|
||||
the portable engine or any other backend, as the [gap policy](gap-policy.md) requires. The
|
||||
focused tests below run their fixtures with `--target=c` only as the test harness; what they
|
||||
check is the direct native pipeline.
|
||||
|
||||
## Focused local test
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY HARMONY_DESKTOP_RECOVERY=0 \
|
||||
build-queue -- make CHECK_FILTER=machine_ir check
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY HARMONY_DESKTOP_RECOVERY=0 \
|
||||
build-queue -- make CHECK_FILTER=x86_encoder check
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY HARMONY_DESKTOP_RECOVERY=0 \
|
||||
build-queue -- sh tests/regalloc.sh build/bin/ziran
|
||||
```
|
||||
|
||||
The machine-IR fixture checks target descriptions, real LIR lowering, ABI constraints, owned
|
||||
metadata, deterministic output, dynamic-allocation representation, explicit unsupported
|
||||
targets/calling forms, bounded limits, malformed MIR rejection and repeatable cleanup. The
|
||||
x86 encoder fixture checks exact bytes, frames, relocations, fuel, traps, pre-encoding
|
||||
call/addend rejection and output preservation. The allocation fixture lowers real LIR and
|
||||
checks register pressure, call splitting, spills and reloads, division and shift registers,
|
||||
flags, register, memory and aggregate copy cycles, float and vector banks, frame and
|
||||
incoming stack-argument layout (including out-of-order incoming homes), fuel placement,
|
||||
deterministic output, explicit unsupported forms, and rejection of malformed allocated
|
||||
programs at the faulting location. Its late-failure fixtures allocate successfully and are
|
||||
then rejected by the allocated verifier (a float call argument, a float call result, an
|
||||
aggregate stack call argument and a direct call relocation with an addend); each checks the
|
||||
input-location diagnostic and that the owner still holds its unchanged `Virtual` program,
|
||||
and the addend fixture allocates the same owner once the input is valid. Float call
|
||||
arguments and results, stack call arguments and global-address addends outside 32 bits fail
|
||||
in `MachineVerifyAllocated` before any encoder pass runs.
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
# Delivery milestones and plan review
|
||||
|
||||
The ten step files define **what** 100% means. This file defines the **order**
|
||||
in which their checklist items are closed, so that real execution and speed
|
||||
evidence arrives in stages instead of only after every platform, object format
|
||||
and profiler is finished. No milestone below changes a step's exit gate, and no
|
||||
milestone is the completed upgrade; only [step 10](10-inspection-performance-and-cutover.md)
|
||||
can declare that.
|
||||
|
||||
## Review of the ten-step plan (2026-11-12)
|
||||
|
||||
What the plan gets right:
|
||||
|
||||
- One verified portable instruction program (LIR) feeds the interpreter, the
|
||||
ZX container; native always reads verified ZX before encoding. Listings are views of encoder records,
|
||||
not a write-and-reparse stage.
|
||||
- Every boundary is verified and bounded; unsupported constructs fail
|
||||
explicitly instead of silently falling back to another engine.
|
||||
- The [gap policy](gap-policy.md) makes missing work observable: a gap has a
|
||||
stable error and an open matrix cell, never a substituted engine.
|
||||
- Measurement rules (Alpha physical host, raw samples, symmetric 1.5×IQR) are
|
||||
strict enough to make the final comparison trustworthy.
|
||||
|
||||
What needed to change:
|
||||
|
||||
1. **Big-bang completion.** The owner's requested ZX speed comparison was gated
|
||||
behind step 10, which also requires AArch64/ARMv7/Windows/macOS/wasm
|
||||
backends, COFF/Mach-O linkers, signing and profiler integration. Nothing
|
||||
measurable would reach the owner until all of that existed. The milestones
|
||||
below deliver labeled interim comparisons on the first platform row.
|
||||
2. **The baseline came last.** Step 10 says to preserve the old engines'
|
||||
"before" measurement before replacing them, but scheduled it at the end.
|
||||
The plan now requires a direct physical-host baseline at milestone M0 and
|
||||
rejects virtualized receipts.
|
||||
3. **Breadth without a target workload.** Lowering grew construct by construct,
|
||||
while the actual comparison workload, [`bench/zx_compare.zi`](../bench/zx_compare.zi),
|
||||
still cannot lower: it needs `#foreign host_api` calls and string values.
|
||||
Step 03 work is now ordered by a measured corpus-coverage report, starting
|
||||
with the benchmark workloads.
|
||||
4. **Two native code paths existed.** The old LIR-to-x86-64 encoder and the
|
||||
[machine IR](machine-ir.md) boundary had overlapped, so every native feature
|
||||
risked being implemented twice. They have been merged onto the machine-IR
|
||||
path and the old encoder is deleted; new native features land only there.
|
||||
5. **Speed-critical shortcuts were not tracked as debt.** Native procedure and
|
||||
pointer tokens were dispatched by a linear scan, native code was stack-slot
|
||||
only, and native `Fuel` emitted no bytes. These became M2 exit criteria and
|
||||
are done: a pointer token carries its slot, version and offset and is checked
|
||||
in constant time, a procedure value is a code address called through a
|
||||
register, values live in allocated registers, and `Fuel` decrements the
|
||||
instance counter at loop headers and function entries.
|
||||
6. **Stale status.** Step 05 was still "planned" after the revision-28
|
||||
container landed, and the README listed the container and machine IR as
|
||||
wholly outstanding. The statuses now match the code.
|
||||
7. **Unbounded extras.** The textual-listing re-assembler, the GNU inline
|
||||
assembly template surface, 32-bit x86 and RISC-V are post-cutover
|
||||
extensions unless the step-01 matrix names them as maintained rows.
|
||||
|
||||
Recorded decision: the checked-IR-to-LIR adapter stays in C
|
||||
([`compiler_zir_lower.zi`](../cmd/compiler_zir_lower.zi)) because the checker's
|
||||
program records are C structures. Everything after LIR (verifier, codec,
|
||||
engine, optimizer, machine IR, encoders, container, linker) stays in Ziran.
|
||||
Step 03's proposed `compiler_lower*.zi` modules apply only if the checker
|
||||
itself moves to Ziran.
|
||||
|
||||
## Rules that apply to every milestone
|
||||
|
||||
- A new language feature lands in LIR, the verifier, the codec and the portable
|
||||
engine first. Native support follows on the machine-IR path.
|
||||
- Each row of the platform matrix is cut over separately. A row switches its
|
||||
default to the new format only after its own gate passes. Before that switch,
|
||||
the direct target is a named Gap and fails; an explicitly selected legacy
|
||||
command remains a comparison tool, never a fallback.
|
||||
- Portable, native, Wasm, C and Go execution are separate targets. A request for
|
||||
one never routes to another. Missing CPU features, host services, `#asm`
|
||||
variants, parallel/GPU support, object formats or loaders are preflight errors.
|
||||
- Every Gap has the stable diagnostic and side-effect-free negative fixture
|
||||
required by the [gap policy](gap-policy.md). A fallback, downgrade, skip,
|
||||
emulated run or legacy-engine result cannot close a milestone.
|
||||
- Interim measurements follow every rule in step 10, are labeled *interim*,
|
||||
and never replace the final full comparison.
|
||||
- Hostile-input hardening is mandatory at trust boundaries (ZX container and instruction
|
||||
decoders, loaders, host results). Internal stages rely on the verifier
|
||||
instead of duplicating its checks.
|
||||
|
||||
## Milestones
|
||||
|
||||
| Milestone | Scope | Exit evidence |
|
||||
| --- | --- | --- |
|
||||
| **M0** Integrate and baseline | Land the in-flight slices behind one passing local `make check` and `make check-bootstrap`. On Alpha's physical host, measure the old portable VM and old TinyCC native ZX with the M1 workloads, hashing and preserving the exact old binaries. | Green local suites; baseline receipt with raw samples under `bench/results/`. |
|
||||
| **M1** Workload-complete portable path | Typed host capability calls (`s64 -> s64` first, then scalar/string/record signatures), in-bundle `--bind` providers, immutable strings (literal, copy, `.count`, checked index), runtime global initializers. The revision-28 container lists capabilities recomputed from reachable `HostCall` instructions. Add a C embedding API for the new engine (open, list capabilities, bind, run with fuel) that the existing comparison harness can drive. Unsupported operations are Gap diagnostics, not calls into the old VM. | Corpus-coverage report shows every benchmark workload lowering; source, saved IR and new ZX agree with the oracle; negative fixtures account for every remaining Gap; **interim comparison 1**: explicitly selected new portable engine vs explicitly selected old VM. |
|
||||
| **M2** Register-allocated x86-64 | Liveness, linear-scan allocation with splitting and spilling, a post-allocation verifier, and machine-IR-to-x86-64 encoding that reuses the existing byte encoders. Fuel at loop back-edges and calls. Constant-time token dispatch. | Every x86-64 fixture passes on the sole machine-IR path; no alternate native encoder remains. |
|
||||
| **M3** Native ZX on Linux x86-64 (first cutover row) | In-memory loading with W^X pages, relocation of the same encoder output, host trampolines, stack and fuel checks, and a content/CPU/backend-keyed cache. `ziran run app.zx` runs revision 28 natively on linux-x86_64; unsupported native features fail preflight without starting the portable engine. | Full local suite on the new default for that row, including no-fallback negative fixtures; installed tool verified; **interim comparison 2**: explicitly selected new native ZX vs the M0 TinyCC native ZX receipts, plus AOT and C controls. |
|
||||
| **M4** ARM rows and direct wasm | AArch64 and ARMv7 (USB Moto) machine targets, and direct wasm lowering from LIR. Each row is cut over separately. | Per-row execution evidence; Moto comparison on the device. |
|
||||
| **M5** Objects, linker and foreign libraries | Relocatable ELF/COFF/Mach-O, archive reading, external C ABI and foreign libraries, Windows/macOS ABIs and required signing. | Step 07/08 rows with real launches. |
|
||||
| **M6** Inspection closure and final cutover | Unwind/debug/profiler mapping and the owner's **full before/after ZX comparison**. The TinyCC/generated-C ZX path is already removed. | The step-10 completion receipt. |
|
||||
|
||||
## Current position
|
||||
|
||||
The experimental `zi2zx` pipeline now optimizes verified LIR before producing
|
||||
ZX, and native source compilation serializes and reads those same ZX bytes.
|
||||
The standalone instruction artifact/CLI is removed; source LIR remains an
|
||||
inspection view. Direct Linux x86-64 hello has short constants, fallthrough
|
||||
edges, frame-free literal writes and compact adjacent read-only file data.
|
||||
Retained tests require text below 200 bytes, ELF below 1.5 KB and valid retained
|
||||
function extents, with inlined platform service declarations omitted rather than trap
|
||||
aliases. Pointer token runs lower with bounds-checked base/index arithmetic.
|
||||
On the machine-IR path, native code consumes the same fuel checkpoints as
|
||||
the engine (loop headers and function entries) and AOT executables start with
|
||||
the same unbounded budget as a bundle run (`zx2native --fuel N` sets one).
|
||||
Every calling function checks a stack limit and traps on runaway recursion.
|
||||
Host calls pass and return records, arrays and strings, and the optional ZX
|
||||
debug attachment (`zi2zx --debug`) gives native maps and native trap
|
||||
diagnostics source lines. Wasm lowers the same verified ZX, both for
|
||||
`zx2wasm` and for the bundle Wasm tier.
|
||||
|
||||
There is one ZX format. Every `.zx` is revision 28; the semantic bundle writer
|
||||
and reader, the portable VM with `run --vm`, `BundleUsePortableVm`,
|
||||
`BundleInstantiatePortable`, `libziran-vm.a`, bundle libraries, TinyCC and the
|
||||
generated-C native ZX route are removed. On linux-x86_64, `ziran run app.zx`,
|
||||
`zi2zx run` and the embedding API's `Auto` policy load the bundle's verified
|
||||
program as native code into W^X memory, with the engine's pointer, freed-block
|
||||
and bounds checks; a bundle native code cannot run fails before it starts with
|
||||
a named gap, and nothing falls back to the engine. A browser with the Wasm
|
||||
provider runs the Wasm tier and other CPUs the engine. The old VM and TinyCC
|
||||
measurements survive as the M0 baseline receipts.
|
||||
|
||||
Tier-0 check elision (2026-11-15, trust-tier steps
|
||||
0-2): `cmd/compiler_lowered_proven.zi` computes, once per verified program,
|
||||
each pointer's root (a global, or an `allocate` in the same function) and the
|
||||
fixed-array indices an interval analysis proves in range. x86-64 lowering
|
||||
turns a load, store or zero through a rooted pointer into `PointerDirect`
|
||||
(the root's raw start plus the token's offset); `MachineVerify` rejects any
|
||||
memory access whose address is not a `PointerResolve`, fresh `ArenaAllocate`
|
||||
storage or a `PointerDirect` it re-derives to the same root, and
|
||||
`zx2wasm` reads the same index proofs. A fact carries the pointer's room
|
||||
(bytes to its root's end that every execution may reach), so a direct read
|
||||
of a constant text through its view is covered too, and x86-64 drops the
|
||||
index check of an element proven below its bound (`ElementAddress` with an
|
||||
immediate bound). `tests/proven_pointer_cases.zi` prints the per-fixture
|
||||
counts and holds the hostile twins.
|
||||
|
||||
M0 integration is done (2026-11-15): the allocator fix, the AArch64
|
||||
encoder, the native default with checked pointers, the self-hosted C-backend
|
||||
build/cache/process ports and the legacy deletions are committed. M4's first slice, the explicit
|
||||
[target registry and preflight](07-architecture-and-platform-coverage.md#target-registry-and-preflight),
|
||||
lists every CPU/OS row with its gap-policy state; no row is Implemented yet,
|
||||
so every general registry selection fails preflight with
|
||||
`assembly.gap.target-unimplemented`. `zx2native` implements
|
||||
`--target x86_64 --platform linux` (ELF) and, as M5's first slice,
|
||||
`--platform windows` (PE32+ through kernel32) through the machine-IR pipeline;
|
||||
other target rows fail with the stable native platform-service gap before
|
||||
input or output, and AArch64 encodes machine code but has no AOT ELF writer. The revision-28 container, frame-local
|
||||
`Allocate`, local scalar address-taking and the pre-allocation machine-IR
|
||||
boundary are implemented. On Omega on 2026-11-15, with native as the
|
||||
linux-x86_64 default, a clean clone of master passes `make check-bootstrap` and
|
||||
265/266 of the full `make check`. The one failure is `zstd_go`, which needs
|
||||
Go 1.25 (Omega has 1.24.4). Native code does not re-check a pointer's element
|
||||
type: the load-time verifier makes a wrong-type access unrepresentable, and
|
||||
`tests/verified_loading_cases.zi` shows a retyped load refused by the reader,
|
||||
`zi2zx run` and `zx2native` before any native code (M3 step 2, closed).
|
||||
|
||||
M3 is done (2026-11-15). Interim comparison 2 ran on Alpha's physical host at
|
||||
`31d291f3` with all 72 samples oracle-verified and the M0 TinyCC rows
|
||||
byte-identical to their receipt:
|
||||
[`bench/results/zx-compare-alpha-physical-native-2026-11-15.json`](../bench/results/zx-compare-alpha-physical-native-2026-11-15.json),
|
||||
summarized in [Interim comparison 2](../bench/zx_compare.md#interim-comparison-2-native-zx-on-linux-x86-64-2026-11-15).
|
||||
Warm native ZX medians were 0.0483 ms scalar and 0.0633 ms structured per
|
||||
entry: 11.1× / 16.1× faster than the portable engine, 2.82× / 1.48× slower
|
||||
than the M0 TinyCC native tier (0.0171 / 0.0427 ms), and about 10× slower
|
||||
than the C control (0.0046 / 0.0063 ms). M0's Alpha physical-host baseline
|
||||
and M1's portable-engine comparisons are in
|
||||
[interim comparison 1](../bench/zx_compare.md#interim-comparison-1-new-portable-engine-2026-11-12)
|
||||
and the [final pointer-dispatch cohort](../bench/zx_compare.md#final-pointer-dispatch-cohort-2026-11-13).
|
||||
|
||||
M1 and M2 are done (2026-11-15): typed host capability calls, in-bundle
|
||||
providers, and Linux x86-64 SysV liveness, linear-scan allocation with
|
||||
splitting and spilling, the independent allocated-program verifier and direct
|
||||
encoding of verified machine IR. The implementation also covers
|
||||
dependency-ordered once-only runtime initializers, local aggregate/procedure
|
||||
address-taking, checked portable slices and string comparison, native
|
||||
readonly data, the no-libc Linux x86-64 console veneer and validated typed
|
||||
host values with instance-owned returned bytes, released once nothing the
|
||||
program can reach names them. Resizable collection ownership, reentrant
|
||||
callbacks and general native string/arbitrary-host instructions remain
|
||||
explicit gaps. Open work from M4 on is in `plans/open-work.md`.
|
||||
|
||||
## Review of M5 and M6 (2026-11-24)
|
||||
|
||||
The first review's diagnosis still holds, and M5 is the milestone where it
|
||||
repeats. M5's exit gate, "Step 07/08 rows with real launches", bundles four
|
||||
kinds of work whose evidence is not available in the same place:
|
||||
|
||||
- ELF static archives and the C ABI for the Linux row are testable in this
|
||||
checkout; the archive slice landed on 2026-11-24 and `tests/machine_elf.sh`
|
||||
links, runs and rejects them.
|
||||
- A real Windows launch is not available here. Wine parity is evidence that
|
||||
the PE32+ encoding, Win64 ABI, imports and unwind records are right, but it
|
||||
is emulation and cannot close a native row under the gap policy. The matrix
|
||||
needs an explicit emulated state: Wine results stay recorded as emulated,
|
||||
not as a Windows host result.
|
||||
- Mach-O objects, Apple64 and signing need an Apple host and credentials.
|
||||
They should stay a named Gap in the target registry until such a host and a
|
||||
signing identity exist; implementing the container speculatively cannot
|
||||
produce the required real launch.
|
||||
- The in-process loader is per row. Linux x86-64, AArch64 and ARMv7 load
|
||||
native ZX today; Windows and macOS loaders belong to their host slices, not
|
||||
to a shared "archives" item.
|
||||
|
||||
Order the remaining work by the evidence each item can actually produce here:
|
||||
|
||||
1. **M5a** Linux ELF: shared objects (done) and static archives (done). Keep
|
||||
each new C ABI shape and each archive subset behind `machine_elf.sh` plus a
|
||||
named gap for everything else.
|
||||
2. **M6a** inspection closure for rows that are Implemented: Linux unwind
|
||||
registration (`.eh_frame` or an equivalent without libc), the existing
|
||||
debug attachment, and a supported profiler map, with bounded
|
||||
source-to-byte attribution. This is local work and can land now.
|
||||
3. **M5b** a real Windows host run, on hardware or a dedicated CI Windows
|
||||
runner: the same `tests/zx_windows_parity_cases.zi`, with its current Wine
|
||||
rows kept as the emulated control. Until then the row stays open.
|
||||
4. **Native speed** next, because it is the owner-visible deficit and the
|
||||
receipts exist: Vec growth, unique-use Insert-in-place and borrowed call
|
||||
arguments, proof-carried bounds elision, the k-nucleotide copy loop, then
|
||||
the print-heavy examples. These are Alpha-only measurements; do not queue
|
||||
target breadth ahead of them.
|
||||
5. **M5c** Mach-O/Apple64 and signing, only when an Apple host and signing
|
||||
identity are available. **M5d** the Windows loader follows M5b.
|
||||
6. **M6b** the owner's full before/after comparison on Alpha's physical host
|
||||
last, because it must compare the finished implementation, not an interim
|
||||
slice.
|
||||
|
||||
Two smaller corrections: step 08 lists a textual listing re-assembler and
|
||||
every object format for all rows, while the review above intentionally keeps
|
||||
only maintained target rows and treats the listing as inspection, not a
|
||||
required assembler dialect; and a "real launch" must be defined in the step-07
|
||||
matrix as not emulated, so no Wine, emulator or cross-compilation result is
|
||||
counted as a row's execution evidence.
|
||||
@@ -0,0 +1,177 @@
|
||||
# Verified lowered-IR optimization pipeline
|
||||
|
||||
Status: bounded scalar pipeline, mandatory before experimental ZX production.
|
||||
Source `--opt` selects optimized LIR inspection and source optimization reports;
|
||||
ZX input is never reoptimized. This module does not select target
|
||||
instructions, allocate registers, or claim a performance result.
|
||||
|
||||
The implementation is
|
||||
[`cmd/compiler_opt.zi`](../cmd/compiler_opt.zi). It consumes a verified
|
||||
`LirProgram`, builds an independent owned copy, runs enabled transformations in
|
||||
a fixed order, verifies the program after every enabled pass, and exposes the
|
||||
verified result for inspection or later execution.
|
||||
|
||||
## Public API
|
||||
|
||||
```zi
|
||||
LirOptDefaultOptions :: () -> LirOptOptions
|
||||
LirOptBuild :: (owner: *LirOptOwner, program: LirProgram, limits: LirLimits,
|
||||
options: LirOptOptions) -> LirOptResult
|
||||
LirOptProgram :: (owner: *LirOptOwner) -> LirProgram
|
||||
LirOptFree :: (owner: *LirOptOwner)
|
||||
```
|
||||
|
||||
`LirOptOwner`, `LirOptOptions`, `LirOptPassCounters`, `LirOptCounters`,
|
||||
`LirOptResult`, and `LirOptProblem` are ordinary named exported records and
|
||||
enums. Generated C consumers use normal module-prefixed symbols and records.
|
||||
The default options enable constant folding, copy propagation, CFG
|
||||
simplification, and dead-instruction elimination with at most eight folding
|
||||
rounds.
|
||||
|
||||
The input is immutable. `LirOptBuild` first verifies it under the supplied
|
||||
limits and serializes it through the canonical owning lowered-IR codec before
|
||||
changing any instruction. The result therefore does not borrow a module name,
|
||||
function name, type member list, operand list, edge argument, constant, source,
|
||||
or origin from the caller.
|
||||
|
||||
`LirOptProgram` returns a view borrowed from the owner. The view and every
|
||||
nested slice or string expire at the next build or free on that owner. Building
|
||||
again from that same borrowed result is supported because the next owned copy
|
||||
is encoded before the preceding owner storage is released. A failed build
|
||||
empties a non-null owner. Empty and repeated frees are harmless. A null owner
|
||||
returns `Owner`.
|
||||
|
||||
## Pass order and verification boundaries
|
||||
|
||||
The order is fixed and deterministic:
|
||||
|
||||
1. Verify the immutable input.
|
||||
2. Fold exact scalar constants.
|
||||
3. Propagate proven identity copies.
|
||||
4. Simplify constant control flow and remove newly unreachable blocks.
|
||||
5. Remove unused, nontrapping pure instructions.
|
||||
6. Verify and expose the final owned program.
|
||||
|
||||
Each enabled numbered pass calls `LirVerify`, even when it reports no change.
|
||||
The folding pass re-encodes its appended constant table through the canonical
|
||||
codec, so no temporary vector or local slice escapes. Structural rewrites
|
||||
compact values, block parameters, operands, edge arguments, block IDs, entry
|
||||
IDs, and instruction result IDs together. Every remaining declared SSA value
|
||||
continues to have exactly one definition.
|
||||
|
||||
`LirOptResult.diagnostic` is the authoritative input or pass-verification
|
||||
diagnostic on failure. Successful results contain the exact input/output
|
||||
function, block, value, and instruction counts. The four per-pass counter
|
||||
records separately report runs and changed instructions, values, blocks, and
|
||||
constants. These counters follow stored function/block/instruction order and do
|
||||
not depend on allocator order or hashes.
|
||||
|
||||
## Implemented transformations
|
||||
|
||||
Constant folding implements exact boolean and fixed-width integer arithmetic,
|
||||
bit operations, negation, comparisons, same-width numeric bitcasts,
|
||||
boolean/integer conversions, and integer widening or narrowing. Integer
|
||||
overflow is masked to the declared width. Signed comparison, division,
|
||||
remainder, and right shift use the portable engine's two's-complement rules.
|
||||
Division and remainder fold only with a nonzero divisor. A shift folds only
|
||||
when its count is in range. Unsafe constant divide and shift instructions stay
|
||||
in the program and retain their traps. Float bitcasts preserve the bits, but
|
||||
float arithmetic and numeric float conversions are not folded.
|
||||
|
||||
Copy propagation currently proves only same-type `Bitcast` identities. It
|
||||
rewrites every dominated operand and edge argument to the original value.
|
||||
Dead-instruction elimination then removes the unused identity instruction and
|
||||
compacts its value ID. It does not guess that conversions or block-parameter
|
||||
cycles are copies.
|
||||
|
||||
CFG simplification turns a branch into a jump only when its condition is a
|
||||
verified boolean `Constant`. It keeps the selected edge and its arguments,
|
||||
computes reachability from the function entry, removes only blocks that are no
|
||||
longer reachable, and remaps every surviving block and value reference.
|
||||
Dynamic branches, loop headers, backedges, and phi-like block-parameter cycles
|
||||
are retained.
|
||||
|
||||
Dead-instruction elimination reaches a fixed point for unused `Constant`,
|
||||
`Null`, add/subtract/multiply, integer bit operations, negate, comparisons,
|
||||
`Bitcast`, `Aggregate`, and immediate-index `Extract` and `Insert` results.
|
||||
These operations are pure and nontrapping under the current verifier and
|
||||
portable engine. Dynamic-index `Extract` and `Insert` stay in the program
|
||||
because their bounds checks can trap, including when their result is unused.
|
||||
|
||||
## Preserved behavior
|
||||
|
||||
No pass changes the order, count, immediate, or effect number of `Fuel`
|
||||
instructions. Calls, indirect calls, host calls, loads, stores, allocation,
|
||||
copy, zeroing, traps, and all other effectful instructions remain ordered.
|
||||
Unused divide, remainder, shift, and conversion instructions remain because
|
||||
they can trap. Address operations are retained conservatively. An instruction
|
||||
that is folded or changed from branch to jump keeps its source origin. Retained
|
||||
instructions, functions, sources, and origin chains otherwise remain
|
||||
byte-for-byte data-equivalent through the owning codec.
|
||||
|
||||
There is no fast math, reassociation, speculative execution, speculative
|
||||
memory access, effect motion, or synthetic float behavior.
|
||||
|
||||
## Resource bounds
|
||||
|
||||
`LirLimits` bounds each input/pass verification, the owned decoded program,
|
||||
table sizes, instruction/value/block counts, and codec decode. Independently,
|
||||
the optimizer charges its own deterministic table visits against
|
||||
`limits.work`. `LirOptResult.work` is only this optimizer-accounted work. It
|
||||
does not include verifier or codec visits, elapsed time, CPU instructions, or
|
||||
performance.
|
||||
|
||||
Every explicit optimizer scratch vector and encoded buffer is charged against
|
||||
`limits.bytes`. `LirOptResult.scratch_bytes` is the cumulative logical scratch
|
||||
allocation charged during the build, including storage already released. It is
|
||||
not current or peak RSS and does not include the separately bounded owned
|
||||
decode. Counts and size arithmetic are checked before allocation, folding
|
||||
rounds are capped at 64, and allocation failure is recoverable.
|
||||
|
||||
The codec and verifier retain their own documented fixed format, allocation,
|
||||
and work bounds. Optimization does not recursively traverse
|
||||
attacker-controlled SSA or CFG depth.
|
||||
|
||||
## Inspection
|
||||
|
||||
Keep the original `LirProgram` for the before view and call
|
||||
`LirOptProgram(owner)` for the after view. Compare the result counters first,
|
||||
then walk functions, blocks, instructions, origins, and effects in stored
|
||||
order. The owner view can also be passed directly to `LirWrite`,
|
||||
`LirExecPlanBuild`, or a native encoder after inspection.
|
||||
|
||||
The pass manager does not print dumps or timing internally. A CLI integration
|
||||
can render the two explicit views and the deterministic counters without
|
||||
giving the optimizer filesystem or terminal ownership.
|
||||
|
||||
## Explicitly unimplemented passes
|
||||
|
||||
The following are not represented by placeholder counters or no-op names:
|
||||
|
||||
- float arithmetic folding and float numeric-conversion folding;
|
||||
- block-parameter coalescing, jump threading, and general block merging;
|
||||
- range propagation, redundant-check removal, common subexpression
|
||||
elimination, and load/store optimization;
|
||||
- inlining, loop transformations, vectorization, or fuel-aware code motion;
|
||||
- machine IR, instruction selection, register allocation, spilling, and ABI
|
||||
lowering.
|
||||
|
||||
Those transformations need separate semantic proofs and verifier boundaries.
|
||||
Their absence is visible rather than inferred from a generic optimization
|
||||
level.
|
||||
|
||||
## Local test
|
||||
|
||||
The retained Ziran fixture performs before/after portable-engine execution,
|
||||
including loops and block parameters, aggregates, function values, divide and
|
||||
shift traps, exact Fuel consumption, limits, invalid input, repeated builds,
|
||||
failed builds, and repeated free. Its launcher runs source and saved IR through
|
||||
generated C, generated Go, and bundle execution on the engine:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY build-queue -- \
|
||||
sh tests/compiler_opt.sh build/bin/ziran
|
||||
```
|
||||
|
||||
Performance compilation and measurement are separate work and run only on
|
||||
Alpha's physical host.
|
||||
@@ -0,0 +1,263 @@
|
||||
# ZX performance comparison receipts
|
||||
|
||||
`bench/assembly_compare.zi` is the reusable, measurement-free report processor for the ZX
|
||||
before/after campaign. It reads raw receipts produced on one physical host and atomically
|
||||
writes a Markdown report with absolute medians, per-case ratios, regressions, missing cells,
|
||||
raw samples, and audited outlier indices.
|
||||
|
||||
This is reporting and collection infrastructure, not a benchmark result. The strict
|
||||
five-core campaign has not run; that pending work is tracked in `plans/open-work.md`. The
|
||||
separately labeled portable-engine comparison has run on physical Alpha; it does not measure
|
||||
the missing new-native cell or establish a native ZX speedup.
|
||||
|
||||
## Invocation
|
||||
|
||||
```sh
|
||||
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY \
|
||||
build/bin/ziran run --target=c --root bench --module-path . \
|
||||
bench/assembly_compare.zi -- INPUT.json OUTPUT.md
|
||||
```
|
||||
|
||||
The processor does not invoke a compiler, VM, workload, timer, or remote host.
|
||||
`bench/assembly_collect.zi` is the separate collector. Its measurement-free plan validation
|
||||
may run locally:
|
||||
|
||||
```sh
|
||||
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY \
|
||||
build/bin/ziran run --target=c --root bench --module-path . \
|
||||
bench/assembly_collect.zi -- --validate PLAN.json
|
||||
```
|
||||
|
||||
Actual collection runs only in the canonical checkout on Alpha's physical host:
|
||||
|
||||
```sh
|
||||
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY \
|
||||
build/bin/ziran run --target=c --root bench --module-path . \
|
||||
bench/assembly_collect.zi -- PLAN.json bench/results/CAMPAIGN/raw.json
|
||||
```
|
||||
|
||||
The collector checks its plan completely before execution, then attests the fresh hostname,
|
||||
exact `lscpu` model name, `uname -srmo` result, and `systemd-detect-virt` result `none`. The
|
||||
plan must name physical host `alpha` and an `alpha...` hostname. A failed attestation occurs
|
||||
before input hashing, cache changes, or workload commands. This is a host guard, not
|
||||
permission to run the command from another machine with copied or edited provenance.
|
||||
|
||||
### Collector plan, version 1
|
||||
|
||||
The plan root has exactly ten members: `schema_version` (exactly `1`), `campaign`,
|
||||
`physical_host`, `hostname`, `cpu`, `os`, absolute `working_directory`, absolute
|
||||
`collector_work`, `required_cells`, and `jobs`. `collector_work` must be a child of the
|
||||
working directory. Required cells use the same four-member schema documented below and may
|
||||
include modes that have no job; those remain visible as missing cells in the generated
|
||||
report.
|
||||
|
||||
Each job has exactly these 24 members:
|
||||
|
||||
| Member | Contract |
|
||||
| --- | --- |
|
||||
| `receipt_id`, `case`, `engine`, `selector` | Unique receipt/cell identity and an exact supported engine/selector pair. |
|
||||
| `phase`, `metric`, `unit` | One documented phase triple: duration in `ns`, throughput in `ops/s`, memory in `KiB`, or size in `bytes`. |
|
||||
| `command` | Nonempty argv array. The absolute executable must be in `runtime_closure`; no shell parses it. |
|
||||
| `verification` | Optional argv array run outside the measured interval. Compile and size jobs require it. |
|
||||
| `runtime_closure` | Nonempty ordered list of `{path, sha256}` objects. It must contain every executable, runtime, header/module manifest, linked dependency, and helper needed to reproduce the selected baseline; every listed digest is checked before and after collection. |
|
||||
| `workload`, `input_path`, `input_checksum` | Exact workload identity, regular input/artifact path, and `sha256:` digest. |
|
||||
| `semantic_settings`, `correctness_expected` | Canonical common semantics including `process=fresh-child-per-sample`, and the exact `sha256:` of expected stdout. |
|
||||
| `iterations`, `repeats`, `warmups`, `timeout_ms` | Positive work per sample, 3–4096 raw samples, phase-checked warmups, and a bounded child timeout. |
|
||||
| `cache_policy`, `cache_directory` | `private-cold-each-sample`, `private-warm-across-samples`, or `immutable-artifact-no-engine-cache`. Private cache paths must be children of `collector_work`; only those paths are reset. |
|
||||
| `environment` | Ordered explicit `NAME=value` settings or bare names to remove. Display variables are always removed and desktop recovery is disabled. |
|
||||
| `artifact` | Measured build/size artifact under `collector_work`, or `-` when the phase does not produce one. |
|
||||
| `rss_tool` | Absolute GNU/BusyBox time executable for memory jobs, declared in the closure, or `-` for every other phase. |
|
||||
|
||||
Every sample starts a fresh child process. Warm phases require at least one discarded warmup
|
||||
and preserve their private cache across warmups and samples. Cold private caches are reset
|
||||
before every measured sample. Compile and size jobs remove only their declared artifact
|
||||
before each sample, then run their separate correctness command. Duration uses monotonic
|
||||
nanoseconds; throughput requires `timing=internal-kernel-ns`, reads a positive
|
||||
kernel-nanosecond value from the measured command, and divides exact iterations by that
|
||||
internal interval, so process startup is not mislabeled as sustained work. Throughput also
|
||||
requires a separate untimed correctness command. Memory uses the child launcher's peak-RSS
|
||||
KiB; size uses the freshly produced regular file. Correctness stdout must match the expected
|
||||
digest for every sample. Any command, timeout, checksum, correctness, or post-run closure
|
||||
failure aborts without replacing the raw receipt file.
|
||||
|
||||
The receipt's `toolchain` preserves the selector, cache/process policy, complete ordered
|
||||
runtime-closure identities, verification argv, and explicit environment; `flags` preserves
|
||||
the measured command argv after its executable. The collector emits only the strict
|
||||
version-1 four-member document accepted by the processor.
|
||||
|
||||
Current honest selectors are:
|
||||
|
||||
| Engine | Selector | Status |
|
||||
| --- | --- | --- |
|
||||
| `old-portable-vm` | `zx-vm` | Only a preserved pre-cutover `ziran` with `run --vm`; the current tree has no VM, and the M0 receipts hold its measurements. |
|
||||
| `new-portable` | `lowered-portable` | Supported with explicit `zi2zx run`, the engine that runs every `.zx`. |
|
||||
| `direct-aot` | `direct-aot` | Supported only by executing the exact hashed ELF artifact. It is never relabeled as native ZX. |
|
||||
| `control-c`, `control-go`, `control-wasm` | matching selector | Supported with an exact absolute command and complete hashed closure. |
|
||||
| `old-c-tinycc-native` | — | Missing: the TinyCC route is removed, and its pre-cutover CLI default never gave native-only selection proof. |
|
||||
| `new-native` | — | Missing: there is no native ZX engine until milestone M3. |
|
||||
|
||||
Requests for either missing execution mode fail plan validation. They may and should remain
|
||||
in `required_cells`, where the processor reports them as missing rather than manufacturing
|
||||
fallback receipts.
|
||||
|
||||
## Exact input schema, version 1
|
||||
|
||||
The root is an object with exactly these four members:
|
||||
|
||||
| Member | Type | Contract |
|
||||
| --- | --- | --- |
|
||||
| `schema_version` | integer | Exactly `1`. |
|
||||
| `campaign` | string | Nonempty campaign identity, at most 256 bytes. |
|
||||
| `required_cells` | array | 1–512 required cell objects. |
|
||||
| `receipts` | array | 1–2048 raw receipt objects. |
|
||||
|
||||
Each required cell is an object with exactly four nonempty string members:
|
||||
|
||||
| Member | Meaning |
|
||||
| --- | --- |
|
||||
| `case` | Stable comparison-case identity. This is not the workload checksum. |
|
||||
| `phase` | Measurement phase. |
|
||||
| `metric` | Metric name, which determines ratio direction when recognized. |
|
||||
| `unit` | Exact unit spelling expected from every engine in this cell. |
|
||||
|
||||
Every required cell requires one receipt from each core engine:
|
||||
|
||||
- `old-portable-vm`
|
||||
- `new-portable`
|
||||
- `old-c-tinycc-native`
|
||||
- `new-native`
|
||||
- `direct-aot`
|
||||
|
||||
Missing core receipts do not make the input malformed. They produce an incomplete status, a
|
||||
visible `missing` matrix entry, and an explicit item in the missing-cells section.
|
||||
`control-c`, `control-go`, and `control-wasm` are optional and are compared when present.
|
||||
|
||||
Each receipt is an object with exactly these 21 members:
|
||||
|
||||
| Member | Type | Contract |
|
||||
| --- | --- | --- |
|
||||
| `receipt_id` | string | Unique receipt identity, at most 256 bytes. |
|
||||
| `case` | string | Stable comparison-case identity. |
|
||||
| `physical_host` | string | Explicit physical-machine identity. |
|
||||
| `host_mode` | string | Must be `physical`. |
|
||||
| `vm` | string | Must be `none`. |
|
||||
| `cpu` | string | Exact CPU identity captured by the collector. |
|
||||
| `os` | string | Exact OS/kernel identity captured by the collector. |
|
||||
| `toolchain` | string | Exact compiler/runtime toolchain identity for this engine. |
|
||||
| `flags` | string array | Ordered explicit flags, at most 64 entries and 256 bytes each. |
|
||||
| `workload` | string | Exact workload identity. |
|
||||
| `input_checksum` | string | Checksum identity of the workload input/artifact. |
|
||||
| `engine` | string | Core engine, optional control, or an explicitly named future engine. |
|
||||
| `phase` | string | Measurement phase. |
|
||||
| `metric` | string | Metric name. |
|
||||
| `unit` | string | Raw sample and median unit. |
|
||||
| `semantic_settings` | string | Overflow, precision, feature, seed, and other semantic settings in canonical collector form. |
|
||||
| `correctness_expected` | string | Expected output/oracle identity. |
|
||||
| `correctness_actual` | string | Observed output identity; it must equal the expected identity. |
|
||||
| `iterations` | positive integer | Exact work performed by every sample. |
|
||||
| `repeats` | integer | 3–4096 and exactly equal to the raw sample count. |
|
||||
| `samples` | number array | Positive finite JSON numbers in original measurement order. |
|
||||
|
||||
All strings are nonempty, contain no control bytes, and are at most 1024 bytes unless a
|
||||
smaller bound is stated above. The complete input must be a regular file from 2 bytes
|
||||
through 4 MiB. Across the document, no more than 65,536 raw samples are accepted.
|
||||
|
||||
Duplicate required cells, duplicate `receipt_id` values, or duplicate
|
||||
engine/case/phase/metric cells are rejected. Unknown object members are rejected because
|
||||
every object has an exact member count and every required member is type-checked.
|
||||
|
||||
## Comparability gates
|
||||
|
||||
The entire accepted campaign must have one identical `physical_host`, `host_mode`, `vm`,
|
||||
`cpu`, and `os`, and every receipt must directly identify a physical host and no VM.
|
||||
Receipts for the same case/phase/metric must also have identical workload and input
|
||||
checksum, iteration count, unit, semantic settings, and expected correctness identity, and
|
||||
each receipt's actual correctness identity must equal its expected identity. Any changed
|
||||
host, VM, CPU, OS, workload, checksum, iteration count, unit, semantics, or correctness
|
||||
identity rejects the document before output replacement. Toolchains and flags remain visible
|
||||
per receipt but may differ between engines by design.
|
||||
|
||||
The processor never pools duplicate or incompatible batches. A collector that wants another
|
||||
batch must create a separately identified campaign input instead of relying on implicit
|
||||
aggregation.
|
||||
|
||||
## Statistics and ratio direction
|
||||
|
||||
Each receipt is analyzed by the canonical `bench/benchmark_statistics.zi::BenchmarkAnalyze`
|
||||
implementation:
|
||||
|
||||
- symmetric Tukey fences at 1.5×IQR, both tails checked;
|
||||
- linearly interpolated inclusive first and third quartiles;
|
||||
- a sample is excluded only when it is strictly outside a fence;
|
||||
- at least three retained positive finite samples;
|
||||
- the median is computed from retained samples;
|
||||
- original raw order and zero-based excluded indices are reported.
|
||||
|
||||
Recognized phase/metric pairs and intended normalized favorable factors are:
|
||||
|
||||
| Phase | Metric | Better direction | Favorable factor |
|
||||
| --- | --- | --- | --- |
|
||||
| `coldcompile` | `duration` | lower | baseline / candidate |
|
||||
| `coldstartup` | `duration` | lower | baseline / candidate |
|
||||
| `warmstartup` | `duration` | lower | baseline / candidate |
|
||||
| `warmthroughput` | `throughput` | higher | candidate / baseline |
|
||||
| `memory` | `memory` | lower | baseline / candidate |
|
||||
| `code-size` | `code-size` | lower | baseline / candidate |
|
||||
| `bundle-size` | `bundle-size` | lower | baseline / candidate |
|
||||
|
||||
A favorable factor above 1 is an improvement, below 1 is a regression, and exactly 1 is
|
||||
unchanged. Every comparable row separately reports candidate metric change as `(candidate -
|
||||
baseline) / baseline × 100%`, which keeps a lower-is-better duration increase distinct from
|
||||
the reciprocal favorable factor and never presents factor change as elapsed-time or size
|
||||
change.
|
||||
|
||||
If division of positive finite medians underflows or overflows, the row is marked
|
||||
`noncomparable: derived ratio outside finite range`; no infinity or NaN claim is written. An
|
||||
unknown metric is retained with its absolute medians and raw audit but its pair is
|
||||
explicitly marked `noncomparable: unknown metric direction`. No overall or geometric mean is
|
||||
calculated, so missing cells cannot disappear inside an aggregate.
|
||||
|
||||
The fixed primary comparisons for every available cell are:
|
||||
|
||||
1. `old-portable-vm` → `new-portable`
|
||||
2. `old-c-tinycc-native` → `new-native`
|
||||
3. `old-c-tinycc-native` → `direct-aot`
|
||||
|
||||
Optional C, Go, and Wasm controls are each compared against `old-portable-vm` when their
|
||||
receipts exist.
|
||||
|
||||
## Output and failure behavior
|
||||
|
||||
The Markdown output contains:
|
||||
|
||||
- campaign completeness and the same-host environment;
|
||||
- an absolute-median matrix for core and control engines;
|
||||
- the fixed per-case comparisons with ratio and improvement/regression;
|
||||
- every missing required engine/phase cell;
|
||||
- per-receipt workload, checksum, iterations, semantics, toolchain, flags, and correctness
|
||||
identities;
|
||||
- explicit sample counts, raw samples in original order, excluded indices, and retained
|
||||
medians.
|
||||
|
||||
All receipt-controlled Markdown and HTML metacharacters are encoded before rendering: pipes,
|
||||
backticks, backslashes, angle brackets, ampersands, asterisks, underscores, brackets, and
|
||||
hashes.
|
||||
|
||||
The output follows input order and is byte-deterministic for identical input. It is built
|
||||
completely in memory, then written through `ReplaceFile`, which writes and syncs a private
|
||||
sibling before renaming it over the destination. Malformed, statistically invalid, or
|
||||
incompatible receipts return failure without replacing an existing report. An atomic write
|
||||
failure also returns failure and removes its private sibling.
|
||||
|
||||
## Status
|
||||
|
||||
`bench/assembly_collect.zi` supplies the strict collector prerequisite for genuinely
|
||||
selectable modes but cannot complete the five-core matrix: the TinyCC route is removed (the
|
||||
M0 receipts are its only data), and there is no new-native ZX cell yet. The pending
|
||||
full-campaign item lives in `plans/open-work.md`. The older `bench/zx_compare.py` harness
|
||||
produced the labeled interim portable-engine comparison on physical Alpha; see
|
||||
[`bench/zx_compare.md`](../bench/zx_compare.md#older-receipts) and the retained raw receipt.
|
||||
That shell receipt is not the strict five-core campaign and cannot close the delivery gate.
|
||||
Synthetic fixtures validate this report processor independently of the measured interim
|
||||
results.
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
# Portable lowered execution
|
||||
|
||||
Status: implemented. This engine is the portable instruction engine:
|
||||
`libziran` embeds it, and `ziran run` and the embedding API execute
|
||||
revision-28 `.zx` containers on it.
|
||||
|
||||
## Public API
|
||||
|
||||
`compiler_exec.zi` exports:
|
||||
|
||||
- `LirExecDefaultLimits() -> LirExecLimits`
|
||||
- `LirExecPlanBuild(program, verify_limits, *plan) -> LirExecResult`
|
||||
- `LirExecPlanFree(*plan)`
|
||||
- `LirExecInstanceOpen(*plan, limits, identity, *instance) -> LirExecResult`
|
||||
- `LirExecInstanceClose(*instance)`
|
||||
- `LirExecRun(*instance) -> LirExecResult`
|
||||
- `LirExecCall(*instance, function, arguments) -> LirExecResult`
|
||||
- `LirExecResultCopy(*instance, output) -> bool`
|
||||
- `LirExecProblemName(problem) -> string`
|
||||
|
||||
A plan verifies the complete `LirProgram`, computes type layouts, indexes every
|
||||
function value slot, and computes global and frame layouts. It borrows the
|
||||
program's slices; their backing storage must remain alive and unchanged until
|
||||
`LirExecPlanFree`.
|
||||
|
||||
Plan build and instance open are reusable operations. They release an earlier
|
||||
value before rebuilding or reopening. A failure leaves the destination closed
|
||||
and not ready. `LirExecPlanFree` and `LirExecInstanceClose` are safe after
|
||||
partial initialization and safe to call repeatedly.
|
||||
|
||||
The plan and instance structs must be zero-initialized before their first build
|
||||
or open. This is automatic for ordinary Ziran locals; a generated-C caller uses
|
||||
the normal `{0}` initialization.
|
||||
|
||||
An instance owns all mutable state: global bytes, derived-address provenance,
|
||||
frame bytes and words, the explicit frame stack, the copied result, and
|
||||
resource counters. `identity` must be nonzero and unique among instances
|
||||
whose pointer values can meet. Reopening an instance reconstructs its globals
|
||||
from the program initializers.
|
||||
|
||||
`LirExecCall` accepts scalar arguments in `bits` and record/array arguments in
|
||||
`bytes`. `LirExecResultCopy` copies a record or array result from
|
||||
instance-owned result storage.
|
||||
|
||||
## Execution model
|
||||
|
||||
The engine runs verified instructions only. It does not load `.zir`, evaluate
|
||||
the source AST, evaluate generated C fragments, or fall back to another
|
||||
evaluator. When the plan is built, each verified function is translated once
|
||||
into compact code: one entry per instruction, specialized by operation and
|
||||
width, with its operands' frame words and storage offsets resolved and each
|
||||
edge's argument copies listed. One loop runs it. Constants, null, function
|
||||
addresses and fuel need no code: a frame starts with those words written.
|
||||
Common pairs run as one entry: a compare and the branch on it, an address
|
||||
derivation and the load or store that is its only use, a field address that is
|
||||
only the base of the next derivation, two word extracts, and an add before a
|
||||
jump. Anything the compact code does not run itself (calls through function
|
||||
values, host calls, allocation, resizing, traps) and every failure goes to the
|
||||
reference implementation, which runs one verified instruction at a time;
|
||||
`LirExecRunReference` runs a whole call that way.
|
||||
|
||||
Calls push bounded `LirExecFrame` records onto an explicit vector. Recursion
|
||||
therefore consumes the configured frame budget rather than the host language
|
||||
call stack. Each frame has packed storage for records and arrays and one word
|
||||
per scalar value. Values carry no definedness state: the verifier proves every
|
||||
use is dominated by its definition and has its operand's type, and values from
|
||||
outside the plan (call arguments, host results, global images) are checked
|
||||
where they come in. Block transfers whose arguments could overwrite each other
|
||||
first copy every argument to frame scratch and then publish all block
|
||||
parameters, so swaps and other parallel-transfer cycles retain their incoming
|
||||
values; transfers proven free of overlap copy in order.
|
||||
|
||||
Writable globals are instance-local packed byte storage. Pointer values are
|
||||
opaque tokens naming an instance identity and a checked global-derived
|
||||
provenance entry. `field.address` derives a checked record member provenance
|
||||
entry, while `element.address` checks a dynamic fixed-integer index against the
|
||||
array's count and derives the element's provenance. Both require the exact
|
||||
parent pointee type, and repeated equivalent derivations reuse a token;
|
||||
load and store require an exact pointee type. Function addresses use a separate
|
||||
nonzero function-index encoding and indirect calls recheck the full signature.
|
||||
|
||||
Integer arithmetic narrows after each instruction. Signed division implements
|
||||
the minimum-value divided by `-1` result without invoking host overflow.
|
||||
Division by zero and shift counts outside the left operand width are structured
|
||||
failures. A shift count is read using its own verified integer type, including
|
||||
mixed-width shifts. Numeric conversions implement the verified bool/integer and
|
||||
fixed integer/float matrix with checked float-to-integer ranges. Floating
|
||||
negation flips the IEEE sign bit, preserving signed zero and NaN payload bits.
|
||||
|
||||
Fuel is consumed only by explicit `fuel` instructions, making it a stable
|
||||
semantic checkpoint independent of dispatch implementation. Work is charged
|
||||
separately for instruction dispatch, copies, and aggregate/member traversal.
|
||||
The compact code charges the work and fuel of a run of instructions (up to the
|
||||
next one it hands over) when it enters it. When they do not fit, or anything
|
||||
in the run fails, it gives back what the instructions it has not run were
|
||||
charged and hands the run to the reference implementation from there, so a
|
||||
limit or failure stops at the same instruction, with the same remaining work
|
||||
and fuel, as charging instruction by instruction. Frames, live values, derived
|
||||
addresses, and total value bytes have independent limits.
|
||||
|
||||
Every runtime failure reports a `LirExecProblem`. Failures at an executing
|
||||
instruction also report function, block, instruction, source origin, remaining
|
||||
work and fuel, and a trap payload where applicable. Repeated calls reset
|
||||
transient execution state and counters while retaining the instance's globals.
|
||||
|
||||
## Verified coverage
|
||||
|
||||
The engine executes every operation and value type currently accepted by
|
||||
`compiler_lowered_verify.zi`:
|
||||
|
||||
| Surface | Implemented forms |
|
||||
| --- | --- |
|
||||
| Types | void, bool, fixed signed/unsigned integers, float32/float64, pointers, fixed arrays, records, function addresses |
|
||||
| Values | constant, null, global address, function address |
|
||||
| Numeric | add, subtract, multiply, divide, integer remainder, negate, bit operations, shifts, all comparisons, convert, bitcast |
|
||||
| Aggregate | aggregate, extract, insert |
|
||||
| Memory | field/checked dynamic fixed-array element address, checked allocate with optional initializer, load, store over instance globals and frame allocations; `resize` heap blocks |
|
||||
| Calls | direct and indirect portable calls, including bounded recursion |
|
||||
| Control | fuel, trap, jump, branch, return, unreachable |
|
||||
|
||||
Array extraction/insertion accepts both verified literal ordinals and dynamic
|
||||
fixed-integer indices. Dynamic indices preserve their declared signedness and
|
||||
width, reject negative and out-of-bounds values before copying bytes, and retain
|
||||
checks for empty arrays and zero-sized elements.
|
||||
|
||||
`Allocate` reserves pointee-sized storage for the executing frame and returns
|
||||
an identity-checked pointer token bound to that frame and its generation. The
|
||||
optional initializer must have the exact pointee type and is copied at
|
||||
allocation time; without one, the new storage has the pointee's zero value.
|
||||
Accepted pointees are bool, fixed-width integer, `f32`, `f64`, and pointer
|
||||
values. Aggregate pointees fail the `Allocate` operand rule, while pointers to
|
||||
function types are rejected by the type verifier. Allocated pointers compose
|
||||
with load and store; a token whose frame has returned, or whose identity no
|
||||
longer matches, fails with `.Pointer`. Every execution allocates fresh storage,
|
||||
including repeated execution of one instruction in loops and recursion, so
|
||||
allocated pointer values are not stable across executions and are never
|
||||
meaningful outside the instance that produced them. Total address slots,
|
||||
including allocations, are bounded by the `addresses` limit.
|
||||
|
||||
The conformance cases cover narrowing and wrap, signed-minimum division,
|
||||
division by zero, invalid shifts, mixed-width shifts, bool casts, checked float
|
||||
casts, float32 rounding, signed zero, NaN comparisons and payload-preserving
|
||||
negation, cyclic edge transfers, arrays and records, direct and indirect calls,
|
||||
initialized and zero-default scalar allocation, same-site loops and recursion,
|
||||
active aliases, stale and reused-frame pointer failure, instance isolation,
|
||||
pointer provenance, reuse and repeated close, all runtime limits, structured
|
||||
origins, repeated failure, and verifier rejection.
|
||||
|
||||
The test driver also runs a hand-built executor oracle from source and
|
||||
entry-pruned saved IR through generated C, generated Go, and bundles on the
|
||||
engine.
|
||||
|
||||
## Exact current boundary
|
||||
|
||||
The verifier rejects `copy`, `zero`, and `host.call`; it also rejects
|
||||
native-width integers, vectors, capabilities,
|
||||
external functions, non-portable calling conventions, variadics, and
|
||||
non-writable global addresses. Plan construction returns `InvalidProgram` with
|
||||
the verifier diagnostic for these forms. They are not silently skipped.
|
||||
|
||||
Heap blocks live in the instance-owned bytes beside host-returned storage. A
|
||||
block's address names the block and its generation. `resize` and free end that
|
||||
generation, so every address derived from the old block fails with `.Pointer`
|
||||
afterwards, as a pointer into a returned frame does. The last block of the
|
||||
owned bytes grows and shrinks in place; dead blocks at the end are given back.
|
||||
Heap bytes count against `value_bytes`, and a request beyond it gives a null
|
||||
result instead of a failure, so `VecPush` can report it.
|
||||
|
||||
Consequently this slice provides checked frame-local scalar allocation and
|
||||
typed heap blocks, but does not yet provide arbitrary byte memory,
|
||||
host callbacks, native-width or SIMD values,
|
||||
capability values, state serialization or
|
||||
migration, thread-safe concurrent use of one instance, or parallel/SIMD
|
||||
dispatch. The executable `.zx` reader, `ziran run`, and the embedding API
|
||||
route bundles through this engine; the Wasm tier and native ELF output are
|
||||
separate `zx2wasm` and `zx2native` lowering routes.
|
||||
|
||||
## Local verification
|
||||
|
||||
Run:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY build-queue -- \
|
||||
make CHECK_FILTER=lowered_exec check
|
||||
```
|
||||
|
||||
The focused test reports:
|
||||
|
||||
```text
|
||||
lowered exec: verified engine and source/saved C, Go and bundle local tests passed
|
||||
```
|
||||
|
||||
Performance comparison is intentionally absent here. The required before/after
|
||||
`.zx` benchmark belongs to the completed integrated objective and must run on
|
||||
the Alpha physical host, never on a desktop or VM.
|
||||
@@ -0,0 +1,68 @@
|
||||
# Inspect direct assembly in VS Code
|
||||
|
||||
The repository tasks run the experimental direct backend's real supported
|
||||
inspection path without rebuilding the compiler or falling back to C:
|
||||
|
||||
```text
|
||||
source -> .zir -> LIR -> verification -> LIR optimization -> portable .zx
|
||||
-> verified ZX read -> direct target lowering -> ELF + map -> disassembly
|
||||
```
|
||||
|
||||
Use **Terminal: Run Build Task** and select **Ziran: Inspect assembly (scalar
|
||||
fixture)**. It uses `tests/spec/assembly_scalar.zi` with entry
|
||||
`assembly_scalar:Answer`. The **choose source and entry** task prompts for a
|
||||
different source, entry and module root. The same operation is available at the
|
||||
repository root:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY \
|
||||
-u DBUS_SESSION_BUS_ADDRESS HARMONY_DESKTOP_RECOVERY=0 \
|
||||
build-queue -- python3 scripts/inspect_assembly.py \
|
||||
--source tests/spec/assembly_scalar.zi \
|
||||
--entry assembly_scalar:Answer \
|
||||
--root tests/spec
|
||||
```
|
||||
|
||||
Every successful run publishes only a complete stable
|
||||
`build/vscode-assembly/inspection/` set:
|
||||
|
||||
| Artifact | Contents |
|
||||
| --- | --- |
|
||||
| `checked/*.zir` | canonical checked compiler output |
|
||||
| `lowered.lir` | checked, unoptimized source LIR inspection |
|
||||
| `lowered.zx` | linked, verified and optimized portable executable |
|
||||
| `optimized.lir` | the selected `--opt` instruction listing |
|
||||
| `optimization.json` | deterministic optimization transformation counters |
|
||||
| `final.elf` / `final.map.json` | optimized native image and its byte map |
|
||||
| `final.disasm` | actual final ELF disassembly with text-relative addresses |
|
||||
| `manifest.json` | source, tool and artifact hashes plus exact commands |
|
||||
|
||||
The helper verifies that `final.map.json` identifies the complete SHA-256 of
|
||||
`final.elf`. It reads `image.text_virtual_address` from that map and passes its
|
||||
negative value to `objdump --adjust-vma`; no ELF base or scalar-fixture offset is
|
||||
hardcoded. `final.disasm` records the same ELF identity and adjustment, while the
|
||||
manifest hashes every advertised artifact.
|
||||
|
||||
`objdump` (normally from GNU binutils) is an explicit inspection dependency. It
|
||||
does not assemble or link the program: `zx2native` reads verified ZX and directly
|
||||
encodes ELF. Pass `--objdump PATH` when a compatible tool has another name. Missing
|
||||
tools, unsupported source, compiler errors, identity mismatches and disassembly
|
||||
errors stop at the failing stage. A failed run does not replace the last complete
|
||||
artifact set, and there is no fallback compiler.
|
||||
|
||||
The tasks require the existing `build/bin/zi2zir`, `build/bin/zi2zx`, and
|
||||
`build/bin/zx2native`. If
|
||||
native compiler work makes them stale, finish that work and rebuild through the
|
||||
shared queue before inspecting:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY \
|
||||
-u DBUS_SESSION_BUS_ADDRESS HARMONY_DESKTOP_RECOVERY=0 \
|
||||
build-queue -- make assembly
|
||||
```
|
||||
|
||||
This view exposes only the currently implemented ZIR, verified lowered
|
||||
instructions, basic optimization counters, native range map, ELF and
|
||||
disassembly. It does not claim machine IR, register-allocation state,
|
||||
source/unwind debug metadata, profiler/JIT mapping, or support for examples
|
||||
outside the direct backend's documented lowering boundary.
|
||||
@@ -0,0 +1,248 @@
|
||||
# ZX executable instruction container — revision 28
|
||||
|
||||
This document specifies the `.zx` executable format. The format owner is `cmd/compiler_bundle.zi`;
|
||||
`cmd/compiler_exec_link.zi` binds it to the deterministic LIR codec and
|
||||
verifier (current payload schema 4). `zi2zx` writes it; `ziran run`, `zi2zx run`,
|
||||
the embedding API (`include/ziran_host.h`), `zx2wasm`, and `zx2native` read it.
|
||||
Checked packages use the [ZX library format](zx-library-format.md).
|
||||
|
||||
## Integers, limits and ordering
|
||||
|
||||
All integers are unsigned little-endian unless a field is explicitly signed.
|
||||
The complete file is bounded to 268,435,456 bytes. Section count is 3–1,024.
|
||||
The instruction payload is non-empty and at most 268,435,456 bytes. Asset names
|
||||
and lengths use the existing u32 codec and its canonical validation.
|
||||
|
||||
Directory kinds are strictly increasing and unique. Every writer section uses
|
||||
alignment 8. A reader accepts power-of-two alignment through 4,096 for optional
|
||||
extensions, but requires the offset to equal the first aligned byte after the
|
||||
previous section and every intervening padding byte to be zero. It rejects
|
||||
integer overflow, unordered/duplicate entries, gaps, bad padding, overlap,
|
||||
truncation, and trailing bytes. There is no recovery scan or legacy fallback.
|
||||
|
||||
## Header (64 bytes)
|
||||
|
||||
| Offset | Width | Value |
|
||||
| ---: | ---: | --- |
|
||||
| 0 | 4 | `5a 58 00 00` (`ZX\0\0`) |
|
||||
| 4 | 4 | format revision `28` |
|
||||
| 8 | 4 | header size `64` |
|
||||
| 12 | 4 | directory record size `32` |
|
||||
| 16 | 8 | required feature mask, `1` for apps or `3` with module linkage |
|
||||
| 24 | 8 | optional feature mask |
|
||||
| 32 | 4 | section count |
|
||||
| 36 | 4 | container flags; zero |
|
||||
| 40 | 8 | exact total file length |
|
||||
| 48 | 8 | directory offset; `64` |
|
||||
| 56 | 4 | identity algorithm; `1` means SHA-256 |
|
||||
| 60 | 4 | reserved; zero |
|
||||
|
||||
Required feature bit 0 retains the manifest contract name `portable-lir-schema-3`.
|
||||
The internal payload independently carries and verifies current LIR schema 4.
|
||||
Required feature bit 1 advertises module linkage. A reader requires bit 0 and
|
||||
rejects unknown required bits. A revision-28 reader that knows only bit 0 rejects
|
||||
a module bundle. Optional bits are non-executable hints and may be ignored.
|
||||
Any other revision is unsupported, and the reader never sends a payload to the
|
||||
`.zir` parser.
|
||||
|
||||
## Directory record (32 bytes)
|
||||
|
||||
| Offset | Width | Meaning |
|
||||
| ---: | ---: | --- |
|
||||
| 0 | 4 | section kind |
|
||||
| 4 | 4 | flags; bit 0 means required |
|
||||
| 8 | 8 | absolute file offset |
|
||||
| 16 | 8 | byte length |
|
||||
| 24 | 4 | power-of-two alignment |
|
||||
| 28 | 4 | reserved; zero |
|
||||
|
||||
Implemented kinds are:
|
||||
|
||||
| Kind | Required | Meaning |
|
||||
| ---: | --- | --- |
|
||||
| 1 | yes | fixed executable manifest |
|
||||
| 2 | yes | deterministic stripped internal instruction payload |
|
||||
| 3 | yes | canonical assets, including an empty table |
|
||||
| 4 | not accepted as required | reserved native variants |
|
||||
| 5 | iff required feature bit 1 is set | module linkage bytes |
|
||||
| `0x80000001` | no | opaque debug attachment |
|
||||
| `0x80000002` | no | opaque source attachment |
|
||||
| `0x80000003` | no | host interface: the names an embedder sees (below) |
|
||||
| `0x80000100` and above | no | producer extension attachments |
|
||||
|
||||
An unknown optional section is bounded and skipped. An unknown required section
|
||||
rejects before LIR decoding. A required kind-4 section rejects as an unsupported
|
||||
native variant; arbitrary machine bytes are never selected or executed.
|
||||
|
||||
## Host interface (kind `0x80000003`)
|
||||
|
||||
The section is mandatory and nonempty when required feature bit 1 is set.
|
||||
Its directory flags are zero in both app and module bundles.
|
||||
|
||||
The instruction payload is structural: a record is its field types, a string
|
||||
is `{data, count}`. An embedder's host values carry names, so `zi2zx` writes
|
||||
them here, as UTF-8 text of tab-separated lines. Type nodes come
|
||||
first, each naming only earlier nodes:
|
||||
|
||||
node ID scalar|string|pointer SPELLING
|
||||
node ID slice|array SPELLING CHILD
|
||||
node ID record SPELLING NAME CHILD NAME CHILD ...
|
||||
|
||||
then one line per host capability, by LIR function index, with its result
|
||||
node (`-1` for void) and parameter nodes, and one with its declaration as
|
||||
written (variadic and reads-arguments flags, the declaration line, its
|
||||
parameters and its return type):
|
||||
|
||||
host FUNCTION RESULT PARAMETER ...
|
||||
abi FUNCTION VARIADIC READS SIGNATURE ARGUMENTS RETURN
|
||||
|
||||
then one line per module global, by LIR global index, with its type node,
|
||||
and the entry's parameters and return type as written:
|
||||
|
||||
global GLOBAL NODE
|
||||
entry ARGUMENTS RETURN
|
||||
|
||||
A spelling is the type as declared at that position, which a host sees as the
|
||||
value's type name. Declaration text has its tabs and line ends as spaces. The
|
||||
embedding API (`include/ziran_host.h`) uses these lines to translate host
|
||||
values, copy a host's changes to `[]T` arguments back, export and import
|
||||
module globals as state, and compare two files' capability ABIs. App bundles
|
||||
may omit this section.
|
||||
|
||||
## Manifest (kind 1, exactly 128 bytes)
|
||||
|
||||
| Offset | Width | Meaning |
|
||||
| ---: | ---: | --- |
|
||||
| 0 | 4 | manifest schema `1` |
|
||||
| 4 | 4 | LIR schema `3` |
|
||||
| 8 | 4 | signed entry function ID; nonnegative |
|
||||
| 12 | 4 | reachable host capability count, at most 4,096 |
|
||||
| 16 | 4 | required native-variant count; currently `0` |
|
||||
| 20 | 4 | asset count |
|
||||
| 24 | 4 | verified proof status; currently `0` |
|
||||
| 28 | 4 | reserved; zero |
|
||||
| 32 | 32 | program identity |
|
||||
| 64 | 32 | asset identity |
|
||||
| 96 | 32 | combined executable-content identity |
|
||||
|
||||
The program identity is SHA-256 of `ZX28-PROGRAM\0` followed by the exact kind-2
|
||||
bytes. The asset identity is SHA-256 of `ZX28-ASSETS\0`, the u32 asset count,
|
||||
then each sorted asset's u32 name length/name bytes and u32 data length/data
|
||||
bytes. For a bundle with required-feature mask `1`, the combined identity is
|
||||
SHA-256 of `ZX28-CONTENT\0`, the entry ID as a little-endian u32, the mask as
|
||||
a little-endian u64, the program identity and the asset identity.
|
||||
|
||||
For a bundle with required-feature mask `3`, the combined identity is SHA-256
|
||||
of `ZX28-MODULE-CONTENT\0`, the entry ID as a little-endian u32, the mask as
|
||||
a little-endian u64, the program identity, the asset identity, the linkage byte
|
||||
length as a little-endian u64, the exact kind-5 bytes, the host-interface byte
|
||||
length as a little-endian u64 and the exact kind-`0x80000003` bytes.
|
||||
|
||||
The owned reader checks all three identities before exposing the executable.
|
||||
Module linkage and its host interface affect the module bundle's content
|
||||
identity. Debug, source and unknown optional attachments are outside the
|
||||
combined identity. Proof status zero means no
|
||||
opaque producer law/proof claim becomes verified merely by being attached or
|
||||
hashed.
|
||||
|
||||
## Required instruction program (kind 2)
|
||||
|
||||
The payload uses the internal deterministic instruction codec from
|
||||
`compiler_exec_serial.zi`: header, required core section, and no debug section.
|
||||
It is not a standalone executable artifact: `.lirb`, `--emit exec` and
|
||||
`--input exec` have been removed. ZX is the portable program boundary.
|
||||
It contains LIR version, module identities, type graph, constants and binary
|
||||
constant bytes, globals and initializers, functions, parameter/value type IDs,
|
||||
blocks, instructions, operands, edges, symbol IDs, effect ordering, alignments
|
||||
and the entry ID. It has no host pointers or compiler/C record layouts.
|
||||
|
||||
The executable writer strips source names and origins, then calls the unchanged
|
||||
LIR verifier and codec. The reader copies all LIR strings, blobs and tables into
|
||||
`ZxExecOwner`, rejects a debug-bearing required payload, verifies it, checks that
|
||||
the manifest and program entry IDs agree, and exposes a borrowed `LirProgram`
|
||||
until `ZxExecReadFree`. The original container bytes can be released immediately.
|
||||
|
||||
Reachability starts at the entry. Direct calls, host calls and function-address
|
||||
constants add their symbol IDs; an indirect call conservatively adds every
|
||||
portable function, since host procedure values do not exist.
|
||||
Duplicate module identities, duplicate module/name function definitions and
|
||||
duplicate module/name globals reject. Each reachable bodiless `Host` function is
|
||||
one capability; its module, name and scalar signature are already in the
|
||||
verified program. The writer stores the recomputed count and the reader rejects
|
||||
a different manifest count (`capability-count`) instead of trusting producer
|
||||
metadata. Other external functions and non-portable calling conventions reject.
|
||||
The existing bounded portable engine then executes the verified program once
|
||||
the embedder has bound every capability.
|
||||
|
||||
Outer validation uses the caller's `LirLimits` as well as the inner codec and
|
||||
verifier. The reader rejects a container larger than `limits.bytes` before
|
||||
framing or hashing and charges `limits.work` for container bytes, program and
|
||||
asset hashing, module linkage and module host-interface hashing and copying,
|
||||
symbol-name bytes, hash-table initialization/probes, reachability and temporary
|
||||
copies. Temporary asset, symbol and reachability allocations are
|
||||
checked against the byte budget before allocation. Symbol uniqueness uses
|
||||
deterministic open-addressed tables; hash collisions remain explicitly charged.
|
||||
The first reachable indirect call adds every function once, and later indirect
|
||||
calls do not rescan that set. A budget failure returns `limit`, carries an LIR
|
||||
`Limit` diagnostic and leaves the owned reader invalid. The writer applies the
|
||||
same accounting with `LirDefaultLimits`; these limits do not change which
|
||||
instructions or sections the format accepts.
|
||||
|
||||
## Assets (kind 3)
|
||||
|
||||
The section is the existing asset codec: u32 count, then for each asset a u32
|
||||
name length, name bytes, u32 data length and exact data bytes. Names are sorted
|
||||
bytewise and unique relative paths. Empty, `.`, `..`, absolute-like, backslash,
|
||||
colon and NUL-containing names reject. Data is arbitrary binary, including NUL.
|
||||
The section must be consumed exactly.
|
||||
|
||||
The raw framing API returns asset views borrowing the file. The owned executable
|
||||
API validates and hashes them during the read; the embedding API copies them
|
||||
when it opens the file and exposes them through `BundleAsset*`. `zi2zx
|
||||
--asset-dir` stores them.
|
||||
|
||||
## Module linkage (kind 5)
|
||||
|
||||
The section is present exactly when required feature bit 1 is set. Its flags
|
||||
are `1`, alignment is `8`, and its payload consists of the compiler's canonical
|
||||
module linkage bytes. The payload must be nonempty and fits within the container
|
||||
and reader byte limits. The framing API treats the payload as bytes. The owned
|
||||
reader verifies the combined identity and copies the payload before returning.
|
||||
The linkage codec defines the interpretation of these bytes.
|
||||
|
||||
## APIs and failure behavior
|
||||
|
||||
`ExecutableEncode` measures when output is empty. A short output returns its
|
||||
required size and changes no byte. `ExecutableDecode` frames sections and assets
|
||||
without interpreting LIR. `ZxExecWrite` produces a stripped deterministic
|
||||
container; `ZxExecRead`, `ZxExecReadProgram`, and `ZxExecReadFree` provide the
|
||||
bounded owned verified program. Empty and repeated frees are safe.
|
||||
`ZxExecWriteModule(program, assets, output, interface, debug, module_linkage)`
|
||||
writes the module form when linkage is nonempty. Empty linkage produces the app
|
||||
form. `ZxExecReadModuleLinkage(owner)` returns bytes owned by a successful read
|
||||
and valid until that owner is reused or freed. It returns an empty string for
|
||||
an app bundle or an invalid owner.
|
||||
|
||||
The format-specific tools keep generated-output replacement semantics: they write a sibling
|
||||
temporary and replaces the requested path only after a complete successful
|
||||
write. `-o -` streams revision 28 to a pipe. A malformed input cannot replace a
|
||||
previous output. Diagnostics distinguish legacy/unknown versions, required
|
||||
features or sections, flags, ordering, alignment, overlap, truncation, trailing
|
||||
bytes, manifest fields, assets, content identity, LIR codec/verifier rejection,
|
||||
entry mismatch, capability, variant, external and symbol failures.
|
||||
|
||||
## Remaining gaps
|
||||
|
||||
- One file is one linked program: there are no library or add-on containers,
|
||||
cross-container symbol tables or partial-module composition.
|
||||
- Native target/CPU/OS/ABI variant metadata and template verification are not
|
||||
implemented; a required variant rejects, and no arbitrary machine blob is
|
||||
accepted.
|
||||
- Debug/source attachment codecs, optimization remarks, law witnesses and proof
|
||||
revalidation are not implemented; optional bytes remain non-executable and
|
||||
proof status remains unverified. Laws are checked from source.
|
||||
|
||||
The retained focused tests cover deterministic source/saved output, stripped
|
||||
portable execution, owned input lifetime, legacy and feature rejection, unknown
|
||||
required/optional sections, identity corruption, overlap, truncation, trailing
|
||||
bytes, binary/NUL assets, pipe output and failed-output preservation.
|
||||
@@ -0,0 +1,45 @@
|
||||
# ZX checked library format, revision 1
|
||||
|
||||
`ziran pkg zx pack-ir` writes `.zx` libraries for use by the package compiler.
|
||||
The package driver verifies the library and supplies its checked modules to
|
||||
the compiler by package identity. ZX runtime modules and applications use the
|
||||
[executable format](zx-executable-format.md).
|
||||
|
||||
All integers are unsigned little-endian. The 16-byte header has four fields.
|
||||
|
||||
| Offset | Width | Field |
|
||||
| --- | --- | --- |
|
||||
| 0 | 4 | Bytes `ZXLB` |
|
||||
| 4 | 4 | Format revision, `1` |
|
||||
| 8 | 4 | Section count, 3 to 4,098 |
|
||||
| 12 | 4 | Exact file length, up to 268,435,456 bytes |
|
||||
|
||||
Sections follow the header in increasing bytewise order by path. Each record
|
||||
has a four-byte path length, a four-byte payload length, a 32-byte raw SHA-256
|
||||
of the payload, and then the path and payload bytes. Records are contiguous.
|
||||
Paths are unique, relative, and 1 to 1,024 bytes long. Paths cannot contain
|
||||
empty, `.` or `..` components, control bytes below 32, a backslash or a colon.
|
||||
Payloads are nonempty. The final payload ends at the declared file length.
|
||||
|
||||
The required `checked-package.tsv` section is the literal `2`, package
|
||||
identity, toolchain identity, and profile, separated by tabs and terminated
|
||||
by one newline. Both identities have the form `p` followed by 16 lowercase
|
||||
hexadecimal digits. The profile is a registry path segment of up to 128
|
||||
ASCII letters, digits, hyphens, underscores, or periods, excluding `.` and
|
||||
`..`. The required `ziran.toml` section contains the provider manifest. All
|
||||
remaining sections hold serialized checked modules with `.zir` paths derived
|
||||
from the provider's module paths. At least one module is required.
|
||||
|
||||
The registry descriptor repeats the metadata fields and adds the full
|
||||
lowercase hexadecimal SHA-256 of the entire `.zx` file as a fifth field.
|
||||
The package driver matches these pins to the package and toolchain in the
|
||||
resolved dependency graph. The compiler checks module identities against
|
||||
that graph when it opens their checked payloads.
|
||||
|
||||
Development libraries use `ZXLD` as their magic. Their metadata starts with
|
||||
`dev` and adds a fifth field containing a lowercase hexadecimal source
|
||||
fingerprint. It covers the provider manifest and lock, scanned module and
|
||||
export source bytes, and feature defines. The writer checks the fingerprint
|
||||
again before installing the completed file. Production package and runtime
|
||||
readers reject this magic. A local development reader must be selected
|
||||
explicitly and still checks the package and toolchain identities.
|
||||
+272
-442
@@ -2,471 +2,301 @@
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
- A host library registered for `zx2native` may be an `ar(1)` archive of ELF64 x86-64 relocatable objects instead of a shared object. The Linux executable links the members its capabilities reach, each once, with their text, read-only data, writable data, zero fill, GOT entries and relocations, and the capability's veneer calls its member directly, so the executable stays static and has no interpreter or dynamic record. An unsupported section, relocation or symbol is the stable `assembly.gap.machine-archive` diagnostic naming the capability, member and symbol, and the old output is kept. `tests/machine_elf.sh` links and runs an archive, rejects an undefined member symbol, and keeps the shared-library case green.
|
||||
- `zx2native --platform linux|windows` supplies the ZX Runner's file and clock services itself, so a program that uses `std/guest_files` or `std/guest_clock` links into the same static ELF or PE32+ as any other instead of stopping at a host-capability gap. The linker names the nine `host_api` services by function and signature, keeps them apart from library imports so the ELF stays static and the PE imports only what a veneer calls, and emits each veneer after the library ones. Linux veneers make the system calls with the path in a 4 KiB stack slot; Windows veneers widen UTF-8 paths to UTF-16 with `MultiByteToWideChar`, convert listed names back with `WideCharToMultiByte`, and import `GetFileAttributesExW`, `CreateFileW`, `ReadFile`, `WriteFile`, `DeleteFileW`, `MoveFileExW`, `CreateDirectoryW`, `FindFirstFileW`, `FindNextFileW`, `FindClose`, `QueryPerformanceCounter`, `QueryPerformanceFrequency` and `GetSystemTimeAsFileTime` as needed. A read or a listing grows a heap block through the runtime's resize entry and shrinks it to the final length; the block stays allocated. `tests/machine_elf.sh` and `tests/zx_windows_parity_cases.zi` run one program that writes, reads, renames and removes a file (with a non-ASCII name), lists a directory and reads both clocks on Linux and under Wine.
|
||||
- `zx2native --platform windows` writes each line of standard output to a console once it ends, as the Linux ELF does, while a redirected or piped descriptor keeps whole buffers: the buffered runtime asks `GetConsoleMode` once, so an image with more than one console call imports it beside `GetStdHandle`, `WriteFile` and `ExitProcess`; hello, with one call, still imports the three. `tests/zx_windows_parity_cases.zi` runs a program that prints, works and prints again under a pseudo-terminal on both systems and times its first line.
|
||||
- `zx2native --platform windows` writes x64 unwind data for every function with a prologue: a `.pdata` `RUNTIME_FUNCTION` and a `.xdata` `UNWIND_INFO` record that walks the pushed frame pointer and the stack allocation. The record starts where the frame does, after an early return that leaves before any frame exists, so a Windows stack walker attributes frames from the first byte.
|
||||
- `zx2native --target armv7 --platform linux|android` writes a static ARMv7 ELF32 (EM_ARM, EABI5) with its own runtime, matching the AArch64 writer: the entry stub sets the stack limit, calls the initializers and the entry, and ends through the runtime's exit; the console writer is A32 machine code emitted from Ziran source. Both ARM rows run on their devices (Pixel 4a and Moto e6 play) and both report a named gap for a facility they do not carry.
|
||||
- `zx2native --target aarch64 --platform linux|android` writes a static AArch64 ELF with its own runtime: the entry stub sets the stack limit, calls the initializers and the entry, and ends through the runtime's exit; the console writer is AArch64 machine code emitted from Ziran source. The image resolves every relocation at link time, so it needs no loader. A program that calls a formatter or a host capability is still a named gap.
|
||||
## [0.8.0] - 2026-11-23
|
||||
|
||||
- Build native AArch64 and ARMv7 images with indexed relocation lookup, so each image relocation visits only its own instruction's machine relocations instead of scanning the whole program. Both devices pass the 81-program parity.
|
||||
|
||||
- ZX Runner: `make install-user` installs the `zx` command, the `.zx` file type (`application/x-ziran-bundle`, recognized by name and by its `ZX\0\0` header) and a desktop entry that file managers use to open `.zx` files. `zx app.zx` runs any bundle with the toolchain's runtime and hands it to no other program. It first explains a file that is not a ZX program or uses an older or newer ZX format, and names a bundle that needs platform capabilities, such as a window, that the runner does not provide. Started without a terminal, it also shows failures in a dialog.
|
||||
|
||||
- Removed `std/rss_scan` (feed item and tag scanning: `FeedNextItem`, `FeedTag`, `FeedCopyText`). The standard library has no replacement; a program that needs it copies `std/rss_scan.zi` from commit c3ef9fb2, the last one that has it, into its own module root.
|
||||
|
||||
- Removed `std/http_get_linux` (`GetHttps`, `GetHttpsCapped`). Use `std/net_http`: `SendCapped` with an `HttpRequest` whose `method` is `"GET"`. Commit 4c62f8b8 is the last one that has the old module.
|
||||
|
||||
- `#caller_location` names the call site's file relative to its module root, or by its package and the path inside that package, so the same sources build the same output from any folder or package cache.
|
||||
|
||||
- ZX embedders can request an active guest stop from another thread, including during initialization and library calls.
|
||||
|
||||
- Hosted ZX applications can open from a read callback with a smaller instruction store when running on the portable engine.
|
||||
|
||||
- Compile hot packed ZX integer instruction runs on Linux i386 with bounded executable storage and the interpreter's work, fuel and failure locations.
|
||||
|
||||
- Speed up large record and array loads in the ZX instruction engine.
|
||||
|
||||
- Check public API declarations and examples for a selected backend and platform with `ziran api`.
|
||||
|
||||
- Pack checked ZX libraries for explicit OS and CPU targets with `ziran pkg zx pack-ir --locked`.
|
||||
|
||||
- Reduce portable ZX integer execution overhead by reusing canonical operands and looking up edge metadata only at branches and jumps.
|
||||
|
||||
- Allow instruction-engine hosts to borrow packed read-only scalar slices for synchronous callbacks.
|
||||
|
||||
- Add optional bounded progress and cancellation callbacks to PNG/JPEG decoding while preserving the ordinary image readers.
|
||||
|
||||
- Add compact/reference instruction-budget parity coverage and retained i386 runtime comparisons; the unproven interpreter optimization candidate was withdrawn before installation.
|
||||
|
||||
- The portable ZX engine reuses frame storage for large record and array snapshots with disjoint lifetimes.
|
||||
|
||||
- Package locks preserve each dependency's own name and exports when multiple refs select the same local override.
|
||||
|
||||
- ZX supports indexing typed pointers. The engine and checked native backends use the backing allocation to reject invalid indices.
|
||||
|
||||
- The portable ZX engine can resize a heap block using adjacent free space on both sides, avoiding a replacement allocation when the combined space fits.
|
||||
|
||||
- The portable ZX engine reuses storage for temporary derived addresses across branches, so loops can traverse large buffers without filling the address table.
|
||||
|
||||
- Native ZX can run with a smaller temporary frame arena when the host cannot reserve 256 MiB of contiguous address space.
|
||||
|
||||
- Speed up SHA-256 verification on hosts without SHA instructions.
|
||||
|
||||
- Package tested native Ziran toolchains in Gitea by exact source revision and Linux host profile.
|
||||
|
||||
- Distribute checked packages as versioned `.zx` libraries for source-free imports in ZX and native builds.
|
||||
|
||||
- Publish and fetch verified `.zx` images and checked compiler companions through Gitea. Package locks can discover and pin compatible checked dependencies for source-free ZX builds.
|
||||
|
||||
- The engine-only ZX reader can decode directly into compact instruction storage and expand one function at a time for verification and planning.
|
||||
|
||||
- Compact ZX execution uses half the storage for value locations when the configured limits fit a signed 32-bit encoding. Larger plans retain 64-bit locations.
|
||||
|
||||
- C embedders can use `BundleOpenEngineReadAt` to reduce the engine’s verified instruction storage. A host allocator can release the unused storage through an optional shrink callback.
|
||||
|
||||
- C embedders can open seekable ZX app images through `BundleOpenReadAt` without keeping a full input buffer. The callback is needed only during verification, and images with assets, module linkage, or additional attachments use the byte-based API.
|
||||
|
||||
- Native x86-64 code copies and clears fixed-size values through 512 bytes with inline vector instructions, takes register hints from actual control-flow predecessors, creates a stackless leaf's frame only when a fuel check traps, and copies only the used members of record snapshots read through constant fields.
|
||||
|
||||
- `zx` hosts bundles in-process and gives them files, the clock, arguments and environment, and their own embedded assets (std/guest_files, guest_clock, guest_process, guest_assets); a capability it lacks is named in the error.
|
||||
|
||||
- `ziran api --json` exposes optional type-checked, runnable usage examples for public symbols.
|
||||
|
||||
- Native instances release temporary frame reservations while idle, so multiple bundles fit in a 32-bit address space without reducing the active frame limit or checked pointer protection.
|
||||
|
||||
- Embedders can route instruction-engine ZX output through a per-instance console callback, including output from global initializers.
|
||||
|
||||
- In-process native ZX resizes large heap blocks through the allocator instead of always allocating and copying a replacement. Growth remains zero-filled and checked aliases are invalidated even when the address stays the same. The Vectors kernel on Alpha took 38.19 µs instead of 40.04 µs in 11 matched rounds, against 34.07 µs for C.
|
||||
|
||||
- Wasm stores can copy a loaded record directly from its source when no intervening effect requires a snapshot. Copies through pointers preserve partially overlapping memory in either direction.
|
||||
|
||||
- The shared optimizer resolves calls through known function addresses, gives calls inside loops a larger inlining budget, and restores borrowed input on resource-limited specialization. Standalone ZX tools now rebuild when the specialization module changes.
|
||||
|
||||
- Source and saved module graphs can grow beyond 1,024 files, with bounds checked against available addressable storage.
|
||||
|
||||
- Platform conditions in modules with file-scope enum imports no longer force an otherwise ordinary import cycle to resolve at compile time.
|
||||
|
||||
- Executable ZX identities hash whole byte ranges through the runtime’s shared SHA-256 implementation, including CPU acceleration where supported, instead of feeding a separate hasher one byte at a time. Identity validation and resource limits are unchanged.
|
||||
|
||||
- The native disk cache reloads ARMv7 and AArch64 machine images, including the ARMv7 runtime helper relocations. Android apps reuse compiled code across launches.
|
||||
|
||||
- ZX lowering turns a range test with literal bounds, such as `code >= 12288 && code <= 12543`, on a stable local, record member or fixed-array element into one unsigned comparison. Kryon's TextIdeographic drops from 55 to 41 instructions, and the Text widget scenario ran faster in Wasm in 8 of 10 alternating Alpha rounds, with the paint result checked on every call.
|
||||
|
||||
- Wasm frames hold only the record slots a procedure still uses. A large record read in place, or a zeroed record that is never built, reserves no frame space, so Shovey, whose level replay reads single fields of a 306 KB global, compiles to Wasm instead of exceeding the 8 MB frame limit.
|
||||
|
||||
- On x86-64 and aarch64, native console prints read their arguments straight from the saved registers instead of decoding each by type. On Alpha, arrays.zi went from 1.018 to 0.490 µs per call, enums.zi from 0.353 to 0.177, below Wasm, and loops.zi from 1.560 to 0.720.
|
||||
|
||||
- Native ZX gathers standard output in the same console buffer as the engine and hands it to stdio once per run, and before standard error, a host capability call or a trap report. On Alpha, arrays.zi went from 1.150 to 1.023 µs per call, enums.zi from 0.392 to 0.360 and loops.zi from 1.780 to 1.600.
|
||||
|
||||
- Native host calls resolve each function's capability or platform service once per instance, keep up to eight arguments on the stack instead of allocating them, and format printed integers directly. On Alpha, arrays.zi went from 2.075 to 1.122 µs per call, enums.zi from 0.686 to 0.378 and loops.zi from 3.155 to 1.718.
|
||||
|
||||
- `BundleInstanceOptions.unbounded` runs an instance without step metering: native code for it is built without fuel checks, like an unbounded executable, and takes no step limit. The standard and example benchmark hosts use it, as C and Wasm run unmetered. A normal native run now leaves its output to stdio buffering, as the engine does, instead of flushing stdout and stderr on every call. On Alpha, enums.zi went from 1.213 to 0.688 µs per call, arrays.zi from 2.563 to 2.059, score.zi from 0.033 to 0.022, dijkstra by 24% and fannkuch-redux by 14%.
|
||||
|
||||
- In-process native ZX no longer makes a system call on every entry: each thread keeps its stack range, and a forked child looks it up again under its own limit. Records & calls (score.zi) went from 0.511 to 0.032 µs per call on Alpha and text_demo.zi from 0.512 to 0.033 µs; arrays, enums and loops took 13–30% less time.
|
||||
|
||||
- Fixes: native ARMv7 and AArch64 code reads and changes members of large records and globals in place, as x86-64 code does, instead of copying the whole record into the frame for every access. Shovey's `LevelReplayPump`, whose 12 MB frame stopped it at its frame limit when Play was pressed on an ARMv7 phone, now needs 1.8 MB on every target. A record or array built from zeros is zeroed in one pass instead of one store per member, so Shovey's native code shrinks from 6.4 to 1.4 MB on ARMv7 and from 2.8 to 0.9 MB on x86-64, and its AArch64 build, where one 4.7 MB function put branches out of range, now compiles.
|
||||
|
||||
- Native code is verified once: the encoder no longer verifies again a program register allocation just verified, which shortens a phone's on-device compile. The native disk cache now works in Android apps: a library linked without a GNU build ID, as reproducible APKs are, is identified by its code, and an app process caches in its own cache directory, so only the first launch after an install compiles a bundle.
|
||||
|
||||
- Fixes: generated C declares a generic procedure's copy for its caller when the copy's signature names a type through the template's own import alias and the caller has a module-scoped import of that name; GCC 14 rejected the call as an implicit declaration (Kryon's text Draw called from Terminal).
|
||||
|
||||
- ZX applications can load separately compiled libraries with verified typed imports, independent instances, export inspection and state-preserving replacement. The loader checks dependency graphs and accepts explicit module roots.
|
||||
|
||||
- Most of the compiler builds from Ziran source, bootstrapped from generated C seeds: source parsing, module discovery, declaration parsing, compile-time evaluation and condition selection, IR cleanup, the frontend IR, compiler contexts, source documents, diagnostics, paths, semantic IDs, SHA-256 and law checks, the checker (expressions, statements, values, functions, whole programs, generic linking, SIMD rules, borrow analysis), the C and Go backends with their SIMD and x86-64 assembly emitters, the checked IR codec, module loading, locked package resolution, executable ZX asset collection, entry linking for the C, Go and native backends, inline assembly checking and its C emission, and the ZX embedding API (`include/ziran_host.h`). The saved IR format and the C interfaces are unchanged.
|
||||
|
||||
- `ziran run app.zx` hands a bundle only to a runtime provider built by the same toolchain: a `.host` registration records `ziran version --identity` on its second line, and a provider of another build is refused with both identities.
|
||||
|
||||
- `ziran lock` and `ziran update` refresh checked-library entries saved under another toolchain instead of refusing; builds name the package and `ziran lock`.
|
||||
|
||||
- Generated C names a `#program_export` that two linked package revisions define, gives one type application one C type in every module that spells it, and keeps constants, globals and types off the runtime's and libc's names.
|
||||
|
||||
- Nested array literals work at file scope and in procedures: `table: [2][2]s64 = .[.[1, 2], .[3, 4]]`.
|
||||
|
||||
- Inside a project, `ziran api PACKAGE/MODULE` prints that package module; options may follow the input files, a module name that selects nothing is an error, and text output lists record fields and enum members.
|
||||
|
||||
- A syntax or import error says under it that checking stopped there, and a rejected `--bind` says which side is missing or which module already binds the capability.
|
||||
|
||||
- Go's `uintptr` is declared with `#type #foreign builtin "uintptr"`.
|
||||
|
||||
- New standard modules for Limbo ports: `std/list`, `std/pool`, `std/tuple`, `std/rune_text`, `std/zx_conc` and `std/bundle_guest`. `std/grapheme` answers ASCII text without its tables.
|
||||
|
||||
- Two dependencies that name one repository by different URLs share one module namespace under a local override.
|
||||
|
||||
## [0.7.0] - 2026-11-18
|
||||
|
||||
- Wasm now runs all three Kryon widget scenarios faster than Go, and two of them faster than C: Button takes 2.46 µs, Text 3.59 µs and Input 3.24 µs per two frames on Alpha, against 4.33, 3.89 and 6.59 µs in Go. Wasm code reads a record's fields where the record lies instead of copying it, builds records where their caller or parent keeps them, writes a single changed field in place, and writes zeroed records with wide stores or `memory.fill`. `zx2wasm --unbounded` makes a module with no step budget for runs that need none.
|
||||
- The optimizer inlines small procedures, reads record members through the inserts that built them, drops unused calls to procedures without side effects, specializes calls that pass a literal Boolean controlling a loop, and turns recursion such as `Fib(n-1) + Fib(n-2)` into an accumulator loop. It hoists fixed member reads, such as a slice's data and count, out of loops and rotates loops whose test loads from memory, so JSON round trips run 9.7% and radix sort 6.8% faster. It also folds interval checks such as `value > 1000 || value < 0` into one unsigned comparison. A Kryon widget's theme lookups become the constants they read.
|
||||
- Native x86-64 code is faster. Division and remainder by constants use multiplies and shifts, constant shifts use immediates, and floating-point values stay in XMM registers across calls that leave those registers alone. Small blocks are allocated in process, so binary-trees runs in under half the time of the C reference. Functions and loops are aligned, so an unrelated edit no longer moves a loop's speed, and `--checks` builds no longer branch around their traps. Float64 `sqrt` and `std/math.Sqrt` use the hardware square root on x86-64, AArch64 and ARMv7.
|
||||
- New standard library features: `std/base64` encodes and decodes RFC 4648 base64; `std/jpeg` reads baseline and progressive JPEGs and writes JFIF on every target; `std/png_linux` inflates PNG data portably; `std/finite` has inline `Finite32` and `Finite64`; and `std/parallel` adds `ParallelProcessors` and `ParallelInitLanes`.
|
||||
- Audio is part of the core standard library, independent of Kryon: mixing, PCM streams, WAV with IMA and Microsoft ADPCM, MP3, and Ogg/Vorbis with streaming and seeking, played through SDL, WebAudio, or AAudio and OpenSL ES on Android.
|
||||
- Fixes: integers format correctly across the full signed 64-bit range, including the minimum value. The native runtime builds on ARMv7 again. An in-process native run of an entry without a result reports zero. Register allocation no longer copies a register from an unrelated block across a block edge.
|
||||
- The Targets page on the website compares C, Go, native ZX and Wasm in microseconds, all measured on one physical host at one compiler revision. It covers a 29-workload standard suite with independent C and Go references, Kryon widgets and JSON/UTF-8 workloads, with raw samples and generated code to download.
|
||||
- Known issue: on ARMv7, native ZX can stop Kryon's `LevelReplayPump` at its frame limit. The fix is not in this release.
|
||||
|
||||
## [0.6.0] - 2026-11-16
|
||||
|
||||
- Ziran is manually safe like C by default: native x86-64, AArch64 and ARMv7 code, Wasm, generated C and the checks Ziran writes into Go carry no defensive runtime checks, so pointers are addresses and indexes are raw. Build with `--checks` to get every bounds check, pointer token and trap as before, or write `#checks` at the top of a module, before a block or statement, or before one index or slice access to check exactly there. The ZX header records how a bundle was built. The portable engine stays checked.
|
||||
- Native code is much faster: tail calls, functions without frames, small records held in registers one field per register, copy-free reads of large-record fields, `[base + index*scale]` addressing, hot blocks laid out to fall into each other, and register allocation that gives a loop-carried value and its copy one register. Kryon's widget scenarios run natively in 8.6 µs (Button), 9.6 µs (Text) and 13.1 µs (Input) per two frames on Alpha, 121–185× faster than 0.5.0 and within about 3× of C.
|
||||
- A native ELF carries only what the program uses: fuel, traps, stack checks, the pointer runtime, the heap and console buffering appear only when referenced, and `examples/hello.zi` is a 254-byte executable whose `main` is a few instructions.
|
||||
- `zx2native --target x86_64 --platform windows` writes a Windows x86-64 PE32+ console `.exe` from verified ZX, with no C runtime and only the kernel32 imports the program uses.
|
||||
- On linux-armv7, Android included, `ziran run app.zx`, `zi2zx run` and the embedding API run bundles as native code by default; ARMv7 code keeps 64-bit values in register pairs, and all 72 parity programs print the engine's output on an armeabi-v7a phone.
|
||||
- `zx2native` writes Linux x86-64 executables for programs that call host capabilities, linking each capability by name from a registered host library (`NAME.library` beside the `.host` players in `ZIRAN_HOST_PATH` or `~/.local/share/ziran/hosts`).
|
||||
- Native compilation is faster on very large programs: the 28.7 MB Unicode conformance bundle compiles in 7.4 s instead of 81 s.
|
||||
- The plain `ReadU16LE`, `ReadU32LE`, `ReadS32LE` and `ReadF32LE` read at any alignment, as C does.
|
||||
- The website's target and widget tables show fresh native measurements from Alpha, with the generated C, Go, ZX, checked IR and raw samples to download.
|
||||
|
||||
## [0.5.0] - 2026-11-16
|
||||
|
||||
- ZX runs as native code by default on Linux x86-64 and AArch64, Android included: `ziran run app.zx`, `zi2zx run`, the embedding API and Kryon's players run a bundle's verified program as native code in W^X memory. Stray and freed pointers, double free, out-of-range indices, read-only stores and runaway recursion trap; a native gap is a named error and nothing falls back to the engine. `--backend engine` picks the portable instruction engine.
|
||||
- Native code is fast: on Alpha's Intel Core i7-8700, warm native ZX runs a scalar and a structured workload 11× and 17× faster than the portable engine, Kryon's widget scenarios take 1.2–2.0 ms per two frames instead of the removed VM's 43–73 ms, and the Sieve, Records, Hash, Vectors and Printing kernels run within 1.3–4× of C. Shared frame slots, in-place member access, dropped checks where indices and pointers are proven, direct compare branches, buffered output and recycled vector blocks get it there.
|
||||
- Native code compiled for a bundle is cached on disk (`$XDG_CACHE_HOME/ziran/native`), keyed by content, CPU features and compiler build; `ZIRAN_NATIVE_CACHE=DIR` moves the cache and `ZIRAN_NATIVE_CACHE=off` turns it off.
|
||||
- Native bundles keep module state across hot reload and component replacement, return records, arrays and strings from host calls, start fresh locals as zeros and, built with `zi2zx --debug`, name the source line of a trap; `zx2native --emit map` shows the same origins, and `zx2native` executables take `--fuel N`.
|
||||
- `.zx` is one format: `zi2zx` and `ziran run` write and open revision-28 executable ZX only. The semantic bundle format, its VM and the TinyCC tier are removed; rebuild older `.zx` files.
|
||||
- WebAssembly has one route: `zx2wasm` lowers verified ZX with a typed host ABI and a heap. Wasm modules run faster (real loops, shared frame slots, buffered printing) and run in Asyncify runtimes such as Kryon's web player.
|
||||
- The portable instruction engine runs verified ZX about 4–5 times faster.
|
||||
- The embedding API runs revision-28 bundles with typed host calls: records, fixed arrays, strings, slices and handles cross the boundary, `[]T` changes copy back, globals read and write by name, and components carry state.
|
||||
- ZX covers every `Simd` operation, `#parallel` loops, the bit builtins, unions, `New(T)`, `free`, pointer fields, builders, owned `Text`, the remaining `Vec` operations, and long `if`/`else if` chains and case lists.
|
||||
- A closed C program carries only the code it uses: module headers declare only what other files name, runtime headers keep only the helpers it calls, and the entry is C's own `main`. Kryon's example headers shrink to a third of their size or less.
|
||||
- Modules take compile-time parameters with `#module_parameters(...)` and `#import "module"(NAME = value)`, and `#insert NAME;` splices a compile-time string into the module as checked source. Saved `.zir` is version 65; regenerate saved `.zir` files.
|
||||
- `std/temp` adds scoped temporary storage with mark/reset, `std/context` an explicit logger, scope tag and temporary allocator, and portable facades give one import for byte text, environment, timers, randomness, mapped files, streams, worker pools, directories and threads.
|
||||
- Environment, argument, binary, file, HTTP and host-byte readers return typed outcomes that name why input was refused.
|
||||
- `ziran learn on|off|status` keeps a local, size-capped corpus of native builds for a learning compiler. It is on by default and silent; `ZIRAN_LEARN=off` turns it off.
|
||||
- The experimental direct pipeline lowers verified ZX to static Linux x86-64 ELF files with register allocation and no libc, and `ziran capabilities --json` lists assembly targets.
|
||||
- `ziran inspect` shows each statement's source and what each expression means, and a saved ZIR file from another toolchain names both versions and how to rebuild.
|
||||
- The toolchain builds and runs on macOS again, on Apple Silicon and Intel.
|
||||
- The website's playground works again, and its Kryon widget table compares C, Go and native ZX with fresh measurements.
|
||||
- Fixes: generated C indexes slices of pointers; Go compiles `VecSlice` with mixed-width bounds and module initializers that register host-calling procedures; calls through a module alias accept types it re-exports; `std/unicode` lowercases ASCII A–Z correctly; a string constant holding `#import` is no longer read as an import; `ziran check` matches a law's returned record by its declared type; `zi2zx` rejects `--opt` on ZX input.
|
||||
|
||||
## [0.4.2] - 2026-11-11
|
||||
|
||||
- `make zx-tools` builds the experimental scalar Linux x86-64 ELF path with verified IR, inspection dumps and source-range maps; other backends unchanged.
|
||||
- Run a source file directly with `zi2zx run hello.zi`; website examples use the one-command `ziran run hello.zi` flow.
|
||||
- The website's target page adds six JSON and UTF-8 workloads measured on Alpha, with downloadable output and raw samples.
|
||||
- JSON readers scan long unescaped strings with SIMD, preserving borrowed text, escapes and error positions.
|
||||
- SIMD byte-vector loads read immutable strings with whole-access bounds checks, and multi-module SIMD programs keep their operations in generated C.
|
||||
|
||||
## [0.4.1] - 2026-11-11
|
||||
|
||||
- Portable ZX runs unchanged desktop loop bundles about 14 times faster, with records, text and arrays also improving.
|
||||
- The target page adds real Kryon widget scenarios with complete checked IR; Targets stays in shared navigation with its own IR inspector.
|
||||
- The target matrix compares warm execution on desktop, Android and web with raw samples; medians exclude anomalies with 1.5×IQR fences.
|
||||
- WebAssembly handles omitted slice bounds and empty slices at the end of arrays.
|
||||
- Fresh native builds avoid optimizing the temporary bootstrap compiler.
|
||||
- Generated C includes only the headers it uses and omits empty source files.
|
||||
- `ziran inspect` inspects portable `.zx` bundles, including checked modules and bytes.
|
||||
- Build WebAssembly with `ziran build --target=wasm`, including Hello World programs.
|
||||
|
||||
## [0.4.0] - 2026-11-10
|
||||
|
||||
- The website presents all four outputs in a target matrix: inspect C, Go,
|
||||
portable ZX, direct WebAssembly and checked IR, download generated files,
|
||||
run WebAssembly in your browser and compare measured target costs.
|
||||
- The website gains a target matrix across C, Go, portable ZX, Wasm and checked IR, with downloads, in-browser Wasm and measured costs.
|
||||
- `ziran run app.zx` discovers installed package runtime providers for host capabilities; console and graphical bundles share the command.
|
||||
- `pkg paths PACKAGE...` returns ordered resolved paths as JSON after one graph validation.
|
||||
- Reused compiler builds refresh embedded runtime headers by content, so restored timestamps cannot leave stale C helpers.
|
||||
- Linked functions keep their copied capacities consistent with storage, preventing heap corruption after dead-code pruning.
|
||||
- The parser, effect derivation, import linking, proof kernel, theorem checking and the `.zx` container run as Ziran code, with the same results.
|
||||
- `#run` evaluates text of any length with builders, pointers, slices and folded loops, and shares one evaluator with `#if`, `#ifx` and `#assert`.
|
||||
- `.Member` resolves against an enum imported from another module, and an imported constant can size an array.
|
||||
- Record fields and enums take `#c "SPELLING"` so generated headers match shared C code; `const char *` fields compile and headers stop macro-defining constants.
|
||||
- `#asm` takes slices, clobber ranges and one variant per line; `ziran run` runs them with TinyCC, bundles always run portable bodies.
|
||||
- `-DZIRAN_NO_HEADER_INLINE` keeps generated C calls external, so link-time interposition such as `ld --wrap` sees every call.
|
||||
- A `#target` procedure's SIMD-tier copies call that tier's `#inline` procedures; the AV1 decoder decodes 1080p frames 2–4% faster.
|
||||
- A unary operator inside a binary one keeps its grouping in generated C and Go.
|
||||
- Generated C proves away more bounds checks: pre-guard locals, fixed ranges, parameter fields, `else` branches, `ifx` picks; may-wrap checks stay and stored-before-read locals skip zeroing.
|
||||
- Native SIMD vectors such as `s16xN` hold as many 128-bit blocks as the code handles, every width gives the same results, and `#target` picks the best instructions once at startup.
|
||||
- Generated C includes only the SIMD helpers a program calls and compiles each tier in its own file; TinyCC compiles the AV1 decoder a third faster.
|
||||
- The portable VM keeps `std/simd` vectors inline, TinyCC and unoptimized C run operations inline, and Go emits typed code per operation (352p AV1 decode 346 → 44 ms).
|
||||
- `std/simd` adds `Simd.Sign` and `Simd.AbsDiff`, runs loads, stores, widening and 256-bit halves as single instructions, and its scalar fallback runs about nine times faster.
|
||||
- Standard SIMD vectors such as `u8x16` and 256-bit forms give the same bits on every target.
|
||||
- On 32-bit ARM, `f32` vector arithmetic keeps tiny values.
|
||||
- `std/resample` kernels use `std/simd` instead of assembly, up to twice as fast with Wasm SIMD128.
|
||||
- String constants over 4095 bytes build as strict C with escaped trigraphs, and generated C builds without warnings under `-Wall -Wextra`.
|
||||
- Standard libc bindings use `usize`/`isize` sizes so they link and run on wasm32.
|
||||
- `VecSlice` can view a global Vec or a Vec field, which cannot grow, be freed or be replaced while the view lives.
|
||||
- `build --target=c --exe` links with Emscripten, keeping the `.wasm` file.
|
||||
- Each `#load` file can store and index the same `Vec` or `Option`, and a public record with module-private field types builds in importing modules.
|
||||
- Fresh `Text` in checker edge cases is freed with its block, and assigning a Vec or Text field frees the old value.
|
||||
- Checking resolves constants through the lookup cache, `forall` laws check in half the time, and Breeze lowers 921 modules in under a second.
|
||||
- `#reads` follows strings through field paths and marks read-only procedures and foreign calls, so `Text` passed through is freed too.
|
||||
- A `Text` result only read in its statement or local is freed when its block closes; globals holding a `Vec` or `Text` can be assigned or moved.
|
||||
- `std/vec` gains owned UTF-8 `Text`; `TextView` borrows, `TextCopy` copies, producers like `JsonWrite` return it, and files naming it import `std/vec` automatically.
|
||||
- A local named like a C library function or Go builtin no longer hides it, and without a project `std/NAME` always loads the standard module.
|
||||
- `make install-user` keeps a `~/.local/bin/ziran` wrapper and says so instead of failing.
|
||||
- `for` loops, slicing and move-out work on Vec record fields; pushing or freeing while looping is rejected, and Go compiles `for` over a local Vec.
|
||||
- Integer literals with separators, hex, binary and `u64` values above `s64` work in globals, constants, tables, array sizes and ranges.
|
||||
- Shadowed locals such as `x := x + 5` in an inner block read the outer binding on every target.
|
||||
- Generated C inlines small same-module and cross-module calls, copies arrays once, keeps one vectorizable loop exit, and honors `#inline` and `#cold`.
|
||||
- Checked division, shifts and indexes run inline under TinyCC and unoptimized C, about 17% faster under `ziran run` and 24% faster at `-O0`.
|
||||
- Constant tables bind across several loops, file-scope initializers and nesting, and constant arrays are read from one shared read-only copy.
|
||||
- `ziran run` charges step budgets once per procedure and literal range, and portable programs use prepared function and global indices for calls and reads.
|
||||
- Generated C accepts checked pointer casts to imported C callback types.
|
||||
|
||||
- `ziran run app.zx` discovers installed package runtime providers for host capabilities; console and graphical bundles use the same command.
|
||||
- The website uses a simpler reading layout across the homepage, guides and API pages, with responsive navigation and the working browser playground.
|
||||
|
||||
- `pkg paths PACKAGE...` returns ordered resolved paths as JSON after one
|
||||
graph validation, sharing `pkg path` selectors and cache checks.
|
||||
|
||||
- Reused compiler builds refresh embedded runtime headers by content, so
|
||||
restored source timestamps cannot leave generated C using stale helpers.
|
||||
|
||||
- Linked functions keep their copied statement and expression capacities
|
||||
consistent with their storage, preventing heap corruption when later
|
||||
lowering appends nodes after dead-code pruning.
|
||||
|
||||
- Expression and initializer parsing build shared IR directly from Ziran,
|
||||
removing the C callback parser. Compile-time quoted searches share the
|
||||
Ziran source scanner.
|
||||
|
||||
- `#run` evaluates text of any length with builders, pointers, slices and
|
||||
folded loops, and iterates array literals directly.
|
||||
- `#asm` template, operand and clobber strings may name compile-time constants,
|
||||
including templates generated in the same file. Local blocks retain these
|
||||
strings through rechecking and saved IR; ARM NEON helpers support callers
|
||||
built without NEON and with only 16 D registers.
|
||||
- Effect-class derivation and `#law ... effect` evaluation run in Ziran
|
||||
instead of C, preserving law results and diagnostic details.
|
||||
- `.Member` resolves against an enum imported from another module, as in
|
||||
`F(.Two)` for a `B.Kind` parameter, and an imported constant such as
|
||||
`B.LIMIT` sizes an array.
|
||||
- Import linking, file-private renaming and the `#inline` self-call check
|
||||
run in Ziran instead of C, with the same diagnostics and checked names.
|
||||
- The scalar proof kernel behind `#proof` is written in Ziran instead of C,
|
||||
with the same proof results, diagnostics and step budget.
|
||||
- Theorems and their `#proof` certificates are parsed, prepared and checked
|
||||
by Ziran code instead of C, with the same results and diagnostics.
|
||||
- The `.zx` container (header, capability, law and waiver tables, assets
|
||||
and their limits) is written, read and checked against its program by
|
||||
Ziran code instead of C; bundles keep the same bytes.
|
||||
- Record fields and enums take `#c "SPELLING"` so a generated C header
|
||||
matches C code that shares the records: `const char *` or `char name[N]`
|
||||
fields, and enum constants with a prefix such as `ZIR_EXPR_`. Saved IR is
|
||||
version 63.
|
||||
- The compiler's IR records (modules, functions, statements, expressions,
|
||||
types, laws and proofs) are defined once in Ziran; C includes the header
|
||||
generated from them.
|
||||
- A record whose array size names a constant, such as `[NAME_MAX]u8`, keeps
|
||||
its fields' `#go_tag` and `#c` spellings; Go dropped the tags before.
|
||||
- Ziran code reading or storing a pointer field spelled `#c "const char *"`
|
||||
gets the right type in generated C, so it compiles without a const or
|
||||
pointer-sign error.
|
||||
- `#if`, `#ifx`, `#assert` and `#run` share one compile-time evaluator, and
|
||||
enum values read integer literals as the language does (`0b10_1`, `1_000`).
|
||||
- `#asm` routines take slices, clobber ranges such as `xmm0..xmm7` and
|
||||
`q0..q1`, and one variant per line; the checker rejects undeclared or
|
||||
reserved registers, and `-DZIRAN_ASM_CHECK` runs every variant against
|
||||
the portable body. TinyCC assembles SSE2-SSE4.2 variants.
|
||||
- `ziran run FILE.zi` runs `#asm` variants with TinyCC. Bundles keep them,
|
||||
but a bundle file always runs the portable bodies, so a downloaded bundle
|
||||
cannot run instructions of its own.
|
||||
- `-DZIRAN_NO_HEADER_INLINE` keeps generated C calls on the external
|
||||
definitions instead of header inline copies, so link-time interposition
|
||||
such as `ld --wrap` sees every call again.
|
||||
- A `#target` procedure's SSSE3, SSE4.1 and AVX2 copies call the same
|
||||
tier's copy of each `#inline` procedure of the module, which ran SSE2
|
||||
code or a call out of the tier's file before. The AV1 decoder decodes
|
||||
1080p frames 2-4% faster.
|
||||
- A unary operator inside a binary one keeps its grouping: Go read
|
||||
`a ^ -b` as `(a ^ 0) - b`, and C read a float `-(-x)` as `--x`.
|
||||
- A local such as `at := row * stride + column` declared before the guard
|
||||
that bounds `row`, `column` and `stride` proves reads such as
|
||||
`levels[at + stride]` in generated C, so they drop their bounds checks.
|
||||
- Generated C skips the zero fill of a local declared without a value when
|
||||
every element is provably stored before anything reads it, such as a
|
||||
block filled row by row with `Simd.Store` in `for i: 0..7`.
|
||||
- Generated C headers no longer define record and array constants as
|
||||
macros in Ziran spelling; uses carry the value, as in Go.
|
||||
- Native SIMD vectors such as `s16xN` hold as many 128-bit blocks as the
|
||||
code running them handles: two in a `#target` procedure's AVX2 copy and
|
||||
in AVX2 builds, one elsewhere. Loops step by `Simd.Lanes(s16xN)`, and
|
||||
every width gives the same results.
|
||||
- Generated C gets a copy of `ziran_simd_ops.h` holding only the SIMD
|
||||
helpers the program calls, with the same object code. TinyCC compiles
|
||||
the AV1 decoder's modules a third faster, which starts an uncached ZX
|
||||
`ziran run` about 230 ms sooner on 32-bit Android.
|
||||
- Generated C leaves out bounds checks that an `else` branch or a constant
|
||||
left shift proves: `view[i - 1]` in the `else` of `if i == 0`, `t[i]`
|
||||
under `if i != 8` in `for i: 0..8`, and `bytes[(row << 4) + t]`.
|
||||
- `ziran run` of a ZX bundle without a native cache starts about 18% sooner
|
||||
on 32-bit Android and 10% sooner on x86-64, with the same generated C.
|
||||
- Generated C keeps the bounds check behind a guard on a sum or product
|
||||
that may wrap: `if first + 1 + second > view.count { return }` no longer
|
||||
removes the check of `view[first]`, through a local, an `ifx` choice or a
|
||||
loop limit either.
|
||||
- Generated C leaves out bounds checks a guard on a parameter's field
|
||||
proves, such as `destination[i]` in `for i: 0..frame.count - 1` after
|
||||
`if destination.count != frame.count { return }`, until a call or a store
|
||||
through a pointer, slice or global could change the field.
|
||||
- String constants and string globals longer than 4095 bytes build as strict
|
||||
C (GCC and Clang `-pedantic -Werror`, TinyCC). Header string constants
|
||||
are escaped like other C strings, so `??` text no longer forms a trigraph.
|
||||
- std's libc bindings for `getcwd`, `readlink`, `read`, `write`, `poll`,
|
||||
`bcopy`, `mempcpy` and `curl_ws_recv` use `usize` and `isize` for size_t
|
||||
and ssize_t values, so they link and run on wasm32.
|
||||
- `VecSlice` and `values[a:b]` can view a global Vec or a Vec field of a
|
||||
global record. While the view lives, the Vec cannot grow, be freed or be
|
||||
replaced, here or in a called procedure; the view cannot be returned or
|
||||
kept outside its block.
|
||||
- `build --target=c --exe` links with Emscripten's `emcc`, keeping the
|
||||
`.wasm` file its launcher loads.
|
||||
- Each `#load` file of a module can store and index the same `Vec` or
|
||||
`Option` of a module-private record.
|
||||
- A public record whose fields hold module-private types builds in modules
|
||||
that import it: its C header now defines those types.
|
||||
- A fresh Text from a procedure that only reads through a pointer argument,
|
||||
as in `AwardsText(*awards)`, is freed with its block, and so is one read
|
||||
by a local whose name another block also declares.
|
||||
- A field of a local record or by-value parameter that holds a Vec or Text
|
||||
can be assigned: `shelf.label = TextCopy(name)` frees the old value, and a
|
||||
field moved out can be assigned again.
|
||||
- Fixed a use-after-free in the checker when a record literal field
|
||||
initializer was a fresh Text.
|
||||
- `Simd.Load`, `Simd.Gather` and a returned constant array read the shared
|
||||
table instead of copying it at every use, in C and Go, and `TABLE.count`
|
||||
no longer builds the table.
|
||||
- `std/simd` in the portable VM (`zi2zx run --vm`) runs about a quarter
|
||||
faster: each call site works out its operation and operands once.
|
||||
- Uncached `ziran run` of programs that use `std/simd` compiles in half the
|
||||
time: C that only names vector types includes their small types header,
|
||||
not every operation.
|
||||
- The portable VM holds `std/simd` vectors of up to 128 bits inline in its
|
||||
values: a 352p AV1 decode under `zi2zx run --vm` takes 4.9 s, from 6.5 s.
|
||||
- Under TinyCC on x86-64 (`ziran run`), `std/simd` operations run inline
|
||||
rather than as calls, and small records copy through registers: a cached
|
||||
1080p AV1 decode takes 503 ms, from 697 ms.
|
||||
- Under TinyCC and unoptimized C, `std/simd` multiplies, rounding shifts,
|
||||
widening, narrowing and gathers run inline, and bounds checks and whole
|
||||
slices (`a[:]`) cost no call: AV1's vector self-guided filter decodes
|
||||
352p in 76 ms under a cached `ziran run`, from 95 ms.
|
||||
- Go output computes each `std/simd` operation in its own typed code, which
|
||||
Go inlines, instead of through one general lane interpreter: a 352p AV1
|
||||
decode built as Go takes 44 ms, from 346 ms.
|
||||
- Under TinyCC on every target, as on x86-64, `std/simd` operations run
|
||||
inline, and vector loads and stores copy in place rather than through
|
||||
memcpy. On 32-bit ARM, small records copy through registers and constants
|
||||
build with movw and movt: a cached 352p AV1 decode under `ziran run` on a
|
||||
Cortex-A53 phone takes 1.8 s, from 3.6 s.
|
||||
- In C, locals, parameters and globals whose names begin with two
|
||||
underscores, which C reserves, are renamed as keywords are.
|
||||
- Under TinyCC and unoptimized C builds, checked division, shifts and index
|
||||
reads are right when an operand is named like one of their temporaries,
|
||||
such as `zi__a`.
|
||||
- zi2c writes the C for large programs far faster: it works out how each
|
||||
module's header includes its imports once, so Breeze's 921 modules lower in
|
||||
under a second instead of over two minutes, with the same output.
|
||||
- Checking resolves constants through the symbol lookup cache, as it does
|
||||
types and procedures: Breeze checks about 0.25 s faster, AV1 about 15%.
|
||||
`ZIRAN_VERIFY_SYMBOL_LOOKUPS=1` verifies constant lookups too.
|
||||
- `tests/compiler_kernel_benchmarks.sh` no longer stops when another
|
||||
commit lands during the run; it checks the tools, inputs and headers it
|
||||
built and measured.
|
||||
- `forall` laws check in about half the time, with the same results: each
|
||||
law's condition is parsed once, a procedure's parameter list is split
|
||||
once, and a call made again with the same arguments in a later case reuses
|
||||
its result.
|
||||
- The slice lifetime check finishes in a fraction of the time on large
|
||||
programs: each pass rechecks only procedures whose callees or globals
|
||||
changed, and callee summaries and recorded writes are looked up directly.
|
||||
`ZIRAN_PROFILE` now reports the slice lifetime and law gate checks as
|
||||
their own phases.
|
||||
- `#reads` follows strings through field paths: a record parameter copied into
|
||||
a local record's field is followed to its later uses, a later `=` into the
|
||||
field replaces the string, and nested record fields are checked. Fresh Text
|
||||
in a `:=` record local that is only read is freed with its block.
|
||||
- A local override whose own manifest gained, lost or changed dependencies
|
||||
since `ziran.lock` builds locally: its graph is resolved from the working
|
||||
manifests in memory, and the lock is left for `ziran lock`. Packages without
|
||||
an override and `--locked` builds keep the exact check.
|
||||
- `ziran COMMAND --help` and `-h` print that command's usage and do nothing
|
||||
else; `ziran update --help` used to rewrite the lock.
|
||||
- A local override checked out past its locked commit is validated against the
|
||||
graph its root dependency locks, so exact transitive pins of that package
|
||||
no longer fail with a dependency-count mismatch.
|
||||
- `std/simd` vectors such as `u8x16`, `s16x8` and `f32x4`, and 256-bit forms
|
||||
such as `s16x16`, with operations that give the same bits in C (SSE2 to
|
||||
AVX2, NEON and WebAssembly SIMD128), Go, bundles and the portable VM.
|
||||
- A `#target` procedure runs the best x86-64 SIMD instructions the CPU has,
|
||||
chosen once when the program runs. `ZIRAN_SIMD_TIER` lowers the choice,
|
||||
and `#asm` variants needing a vector feature beyond it are passed over.
|
||||
- `std/simd` works however it is imported or aliased, and short standard
|
||||
imports such as `#import "simd"` also resolve through
|
||||
`--module-path std=DIR`, as package tests pass it.
|
||||
- SIMD loads, stores, widening and 256-bit halves compile to single
|
||||
instructions instead of copies through memory.
|
||||
- `std/simd` under `ziran run`, TinyCC and `ZIRAN_SIMD_SCALAR` runs about
|
||||
nine times faster: each operation works on its own lane type, and TinyCC
|
||||
on x86-64 uses SSE2 for the common integer operations.
|
||||
- `Simd.Sign` and `Simd.AbsDiff`. 256-bit vectors run as two 128-bit halves
|
||||
without AVX2, and reductions, `MulWide`, `Narrow` and `AddPairs` use
|
||||
fewer instructions.
|
||||
- On 32-bit ARM, `f32` vector arithmetic keeps tiny values instead of
|
||||
flushing them to zero, and byte shifts of 256-bit vectors are correct.
|
||||
- `std/resample`'s kernels use `std/simd` instead of assembly. They make the
|
||||
same bytes and run faster: at least as fast with AVX2 and about 20% faster
|
||||
on large downscales, 3 to 10% faster with NEON on a Cortex-A53, and about
|
||||
twice as fast with WebAssembly SIMD128.
|
||||
- On 32-bit ARM, Clang builds `Simd.LoadLow` as one load instead of copying
|
||||
the bytes through the stack.
|
||||
- `Text` in `std/vec` is owned UTF-8 text that frees its bytes with its
|
||||
owner. `TextView(text)` borrows it, a `Text` passed where a `string` is
|
||||
expected lends the same view, and `TextCopy` copies a string into one.
|
||||
- A procedure can return `Text` to callers written for a `string` result:
|
||||
they get a string as before, while `result: Text = Render(...)` frees it
|
||||
with `result`. `BuilderFinish` gives a `Text` where one is expected.
|
||||
- Standard text producers such as `TextReplace`, `Float64Repr`, `JsonWrite`
|
||||
and `JoinPath` return `Text`. Existing callers still get a `string`;
|
||||
`json: Text = JsonWrite(...)` frees the text when `json` goes away.
|
||||
- A `Text` result only read within its statement, as in
|
||||
`Count(JsonWrite(...))`, `Render(a) == Render(b)` or `.count`, is freed
|
||||
when its block closes instead of kept for the program.
|
||||
- A local such as `line := Render(...)` that is only read, compared,
|
||||
counted or passed to a procedure that only reads it is freed when its
|
||||
block closes too.
|
||||
- Such a result passed through an `ifx` arm, a local, a procedure that
|
||||
returns it, or a record literal field such as `Props.{.text = Render()}`
|
||||
whose callee only reads that field is freed the same way.
|
||||
- Such a result handed to std/format's `Append` or `BuilderPrint`, whose
|
||||
first argument is the builder's address, is freed too.
|
||||
- A callee that copies its string parameters into a local `[N]string` and
|
||||
only reads the elements, or that points a `string` local at other views
|
||||
of them with `=`, as in `v = s[1:3]`, only reads them.
|
||||
- A procedure type marked `#reads` after its result, as in
|
||||
`Painter :: #type (label: string) -> s32 #reads;`, only holds procedures
|
||||
that read their strings, so Text passed through it is freed too. Saved IR
|
||||
is format 62.
|
||||
- Text read in an `else if` condition, after `&&` or `||`, or in an `ifx`
|
||||
that gives a number or `bool` is freed when its block closes.
|
||||
- A global holding a `Vec` or `Text`, alone or in a record, can be assigned,
|
||||
which frees its old value, and moved into a local or returned, which
|
||||
leaves it empty.
|
||||
- A file that names `Text` or `Vec(T)` imports `std/vec` automatically, so
|
||||
its C header, bundle and Go code see the same types as the code that made
|
||||
them. A parameter or return type that names no visible type is an error.
|
||||
- `#reads` before `#foreign` marks a foreign procedure that only reads its
|
||||
string and byte arguments, so Text passed to it is freed too.
|
||||
- A `-1` or a global argument before such a result no longer keeps it,
|
||||
unless the producing call may change a global.
|
||||
- A local named like a C library function, such as `free`, no longer hides
|
||||
it in generated C, and one named like a Go builtin no longer hides it in
|
||||
Go.
|
||||
- `make install-user` keeps a `~/.local/bin/ziran` that launches another
|
||||
tool, such as a build queue wrapper, and says so instead of failing.
|
||||
- `for h.items`, `for * h.parts`, `for it.tags` and `h.items[1:]` work on a
|
||||
Vec record field, and a record field holding Vecs moves out, as in
|
||||
`last := popped.value`. Pushing to or freeing a Vec while a loop over it
|
||||
runs is rejected, also through a field or a called procedure.
|
||||
- Go output of `for v` over a local Vec compiles again.
|
||||
- A constant table read in several loops of one function, or through
|
||||
`.count`, no longer fails with "cannot bind aggregate constant".
|
||||
- Integer literals such as `1_000`, `0xDEAD_BEEF`, `0b1010_0101` and `u64`
|
||||
values above the `s64` maximum work in globals, `::` constants, constant
|
||||
tables, array sizes and range bounds, and pass the portable VM's checks.
|
||||
- `x := x + 5` in an inner block, and `i := ...` in a `for` body over `i`,
|
||||
read the outer binding on every target; generated C no longer reads the
|
||||
new local, and the VM no longer steps the shadow instead of the loop.
|
||||
- Generated C leaves out bounds checks it proves always pass, such as
|
||||
`t[i]` in `for i: 0..7` over a `[8]T` array, `view[i]` in
|
||||
`for i: 0..view.count-1`, `table[x & 255]`, and `bytes[at]` after
|
||||
`line := row * 16` and `at := line + (offset & 15)`.
|
||||
- `#inline` after a procedure's result always inlines it in generated C,
|
||||
and `#cold` keeps a slow path out of line, including other modules' calls.
|
||||
- A procedure returning an array copies it to the caller once in generated
|
||||
C, and `return Make(n)` writes the caller's array directly.
|
||||
- A local array passed by value to a Ziran procedure is copied once in
|
||||
generated C, not by both the caller and the callee.
|
||||
- Generated Go shifts by a variable count without the general integer
|
||||
helper, and copies a constant table straight from its shared `var`.
|
||||
- A file-scope variable can start from a constant table of any length,
|
||||
such as `table: [4096]u8 = BIG`, instead of failing past 4 KiB.
|
||||
- Constant tables can be nested, as in
|
||||
`GRID :: [3]s32.[s32.[1, 2, 3], s32.[4, 5, 6]]` or a `#run` procedure
|
||||
that fills `g[a][b]`, and `GRID[i][j]` reads the table without a copy.
|
||||
- Generated C also leaves out bounds checks an earlier guard proves, such as
|
||||
`input[row * stride + column]` in loops over `row` and `column` after an
|
||||
`if` that returns when `input.count` is too small.
|
||||
- Those checks stay out when the loop body has an `if` that continues or
|
||||
returns, such as `if flag > 3 { continue }`, or an enclosing `if i < 32`,
|
||||
and for rows `stride` apart after a guard that `stride >= width`.
|
||||
- They also stay out for a row or column a flip picks with `ifx`, and after
|
||||
a guard written as `cast(s64)(height - 1) * stride + width`.
|
||||
- A long `||` guard with comparisons no index uses still proves the reads,
|
||||
and so does a filter window that starts `radius` rows and columns back.
|
||||
- `ziran run` spends its step budget more cheaply: each procedure finds its
|
||||
budget once instead of at every loop iteration, so an AV1 decode runs
|
||||
about 7% faster.
|
||||
- Code built by TinyCC (`ziran run`) or by GCC and Clang without
|
||||
optimization checks indexes, shifts and divisions in place instead of
|
||||
calling a helper, so an AV1 decode runs about 17% faster under `ziran run`
|
||||
and 24% faster at `-O0`. Optimized builds are unchanged.
|
||||
- `ziran run` charges a loop over literal bounds, such as `for i: 0..7`, its
|
||||
whole step count once as it starts rather than at every iteration.
|
||||
- Generated C emits a call of a small procedure of the same module as that
|
||||
procedure's body, so `ziran run` (TinyCC) and unoptimized builds skip the
|
||||
call: an AV1 decode runs about 7% faster under `ziran run` and 4% faster at
|
||||
`-O0`. A private procedure every caller inlined is no C warning.
|
||||
- Generated C builds without warnings under GCC and Clang `-Wall -Wextra`:
|
||||
an `ifx` comparison gets one pair of parentheses, a local nothing reads is
|
||||
cast to void, and a procedure named like `ReadSignedBits` no longer pulls
|
||||
in an unused helper.
|
||||
- Generated C builds the SIMD tier copies of a large `#target` procedure in
|
||||
their own files, such as `inverse_transform.avx2.c`, so a parallel C build
|
||||
compiles them at the same time. An AV1 decoder builds at `-O2` about 40%
|
||||
faster with 8 jobs.
|
||||
- A range over a computed bound, such as `for i: 0..count`, tests the bound
|
||||
once as it starts and then leaves only at its last value. Generated C has
|
||||
one loop exit, which GCC can vectorize, and an AV1 decode runs about 2%
|
||||
faster at `-O2`.
|
||||
- Generated C writes an array call result straight into the local or array
|
||||
lvalue it initializes or is assigned to, without a temporary and a copy.
|
||||
- Small public procedures are inlinable across modules in generated C
|
||||
without LTO: their header carries a `static inline` copy for other modules.
|
||||
- Generated C divides and shifts by a nonconstant operand through a checked
|
||||
helper of its width, and shifts signed values right by a constant with one
|
||||
arithmetic shift, keeping the zero-divisor and shift-count aborts.
|
||||
- Constant number and boolean arrays of any length (`TABLE :: s32.[...]`, also
|
||||
through `#run`) are read-only tables: `TABLE[i]` reads one shared copy on C,
|
||||
Go and the VM instead of copying the array at every read.
|
||||
- `clz`, `ctz`, `popcount` and `bswap` builtins for `u8`, `u16`, `u32` and
|
||||
`u64`, with the width as the count for zero, on C, Go and the VM.
|
||||
- A Vec can hold Vecs and records that own Vecs: `VecPush` moves the element
|
||||
in, `groups[i].parts[j]` reads and writes in place, and dropping frees the
|
||||
inner Vecs. A discarded owned record result, such as `VecPop`'s, is freed.
|
||||
- A local override that no longer matches `ziran.lock` now names the package, its source and the mismatched pin instead of "cannot fetch locked packages"; `GIT_TRACE` no longer makes a clean package cache look modified.
|
||||
- `std/thread_linux` links and polls on macOS, which has no `pthread_tryjoin_np`.
|
||||
- Array literals have no size cap and check in linear time; saved IR is
|
||||
bounded only by its 256 MiB read budget. Returning a view of a pointer
|
||||
parameter's own array storage is rejected; pass that storage as a slice.
|
||||
- Native C keeps an array literal of constant numbers or booleans as one
|
||||
static table instead of a store per element, so large tables compile fast.
|
||||
- `ziran edit` previews and applies checked source edits; `ziran compact` and
|
||||
`ziran expand` give `.zi` files an optional lossless compact transport.
|
||||
- JSON diagnostics keep each message within 2048 bytes and report cuts in a
|
||||
`truncation` field.
|
||||
- `std/unicode` adds Unicode 17 `NFCInto`, `LowerInto` and exact letter,
|
||||
number and white-space properties.
|
||||
- `std/json_document` owns its bytes per node, adds `JsonReset`, caller-owned
|
||||
`Into` accessors and erasers that wipe private buffers.
|
||||
- `std/file_tree_linux` adds `FileSnapshot` and `SameFileSnapshot` to tell
|
||||
whether a file was changed or replaced.
|
||||
- `std/process_channel_linux` accepts up to 32 arguments and can discard
|
||||
stderr; `std/socket_linux` adds `SocketCloseWrite`.
|
||||
- Curl HTTP accepts named header values up to 8191 bytes.
|
||||
- `std/image` adds fallible caller-owned resampling and bicubic resize;
|
||||
`std/float_text` adds `Float64ReprInto`.
|
||||
- `std/resample` gives programs Pillow's resize as allocation-free row
|
||||
kernels, with SSE2, AVX2, NEON (AArch64 and ARMv7) and WebAssembly SIMD128
|
||||
versions that make the same bytes.
|
||||
- `#asm` adds `arm+neon` for ARMv7, selected at run time, and
|
||||
`wasm32+simd128` for WebAssembly builds made with `-msimd128`.
|
||||
|
||||
- Native C generation accepts checked pointer casts to imported C callback types;
|
||||
Go and portable targets continue to reject C callbacks.
|
||||
|
||||
- Package overrides selecting one locked revision now share its dependency graph
|
||||
across older transitive revisions, including newly added dependencies.
|
||||
|
||||
- Without a project, `std/NAME` always loads the standard library's module, even
|
||||
when a search path or the importing package has its own module named NAME.
|
||||
|
||||
- Portable programs use prepared function and global indices for calls and reads, reducing repeated-call execution time.
|
||||
### Added
|
||||
- Owned vectors support fallible reserve, resize and capacity-bounded resize with
|
||||
matching C, Go and portable execution, initialized defaults and safe owned-element cleanup.
|
||||
- `std/web.WebBlobBytes` snapshots file or media bytes into a browser Blob
|
||||
without first making a separate typed-array copy. The snapshot remains valid
|
||||
after source changes or Wasm memory growth.
|
||||
- Project commands such as `ziran bundle --project` accept `--module-path DIR`
|
||||
for modules a build step generates. They join the project's own modules;
|
||||
dependencies still resolve only from the lock and never see them.
|
||||
- `--exe --release` builds with link-time optimization across modules.
|
||||
- `#parallel_gpu for` runs on the fastest GPU in native Linux and Android builds,
|
||||
falling back to CPU threads.
|
||||
- Python build tools can consume verified dependency artifacts and ordered
|
||||
native link metadata through the toolchain's shared artifact helper.
|
||||
- Dependency-owned native artifact recipes build and reuse declared output sets
|
||||
through the locked package graph, with explicit platform/ABI identities,
|
||||
resolved options, input validation and atomic publication.
|
||||
- `std/utf8` gained bounded `Copy`, which preserves valid bytes, repairs
|
||||
malformed input with U+FFFD, never splits an output sequence, and reports
|
||||
the written count and completion separately.
|
||||
- `std/text_tools` gained `TextHexDecodeInto`, which appends bounded
|
||||
uppercase or lowercase hexadecimal bytes and leaves its output unchanged on
|
||||
every failure.
|
||||
- Linux and Android hosts on x86-64, ARM and ARM64 run portable bundles as native code, compiled in memory and cached between launches.
|
||||
- Natively run bundles execute `#parallel for` regions on worker threads, one per processor.
|
||||
- `#parallel for` bodies can hand out results by writing their own slot of an array or slice the function owns, such as `out[it] = value`, or their own window of a slice, such as the row `pixels[it * width : it * width + width]`.
|
||||
- The new `zi2wasm` tool lowers a checked program's scalar subset to one wasm32 module: the portable control flow, calls, casts and wrapped integer widths, with a step-budget import matching the native tier's counting. Programs outside the subset fail with a `zx.wasm` diagnostic, and `tests/zx_wasm.sh` compares the module's result with the native tier and the portable VM under node (and wasmtime when installed).
|
||||
- The wasm execution tier and `zi2wasm` lower strings, slices and module globals: string values are i64 handles over interned data-segment literals with byte indexing, `.count` and equality through a generated compare helper; slices borrow their base's storage as (length, address) handles with bounds-checked element views; globals take fixed data-segment slots whose literal bytes reload fresh on every instantiation. Pointers cross as opaque handles. Probing Inner Breeze's real bundles now passes strings, slices and pointer signatures, leaving enums and expression-initialized globals as the remaining rejections.
|
||||
- The wasm execution tier and `zi2wasm` lower records and fixed arrays: fields laid out exactly as the checker sizes them, values as arena slots with lexical region lifetimes, literals, member and index places with bounds checks, value copies through calls and returns, and parameter slots the callee owns.
|
||||
- `BundleInstantiate` gained a WebAssembly execution tier behind a provider seam (`ZxWasmSetPlatform`): with a provider installed, bundles in the scalar subset run as WebAssembly lowered from their verified IR at open time, and everything else falls back to the portable VM; without a provider, behavior is unchanged. Native TinyCC hosts are untouched. `tests/zx_wasm_engine_test.c` checks the seam, handoff and fallback natively, and `tests/zx_wasm_web.sh` runs a bundle end to end through the wasm-built library and a JavaScript provider (skipped without emcc and node).
|
||||
- `std/vorbis` reads an in-memory Ogg Vorbis stream's channels, rate and length from its pages, without decoding or a library, so programs can bound a stream before decoding it.
|
||||
- `std/vorbis_linux` decodes whole in-memory Ogg Vorbis streams to 16-bit PCM over the platform libvorbisfile, with a frame limit and strict refusal of truncated, chained or damaged streams. Only programs that import it link the library.
|
||||
- Owned vectors support fallible reserve and resize with matching C, Go and portable behavior.
|
||||
- `std/web.WebBlobBytes` snapshots file or media bytes into a browser Blob without a typed-array copy.
|
||||
- Project commands accept `--module-path DIR` for generated modules; dependencies still resolve only from the lock.
|
||||
- `--exe --release` builds with link-time optimization.
|
||||
- `#parallel_gpu for` runs on the fastest GPU in native Linux and Android builds, falling back to CPU threads.
|
||||
- Python build tools consume verified dependency artifacts, and dependency-owned artifact recipes publish declared outputs atomically.
|
||||
- `std/utf8` gains bounded, repairing `Copy`; `std/text_tools` gains `TextHexDecodeInto`.
|
||||
- Linux and Android hosts on x86-64, ARM and ARM64 run portable bundles as native code, cached between launches, with `#parallel for` on one worker thread per processor.
|
||||
- `zx2wasm` lowers a checked program's scalars, strings, slices, globals, records and fixed arrays to one wasm32 module; other programs fail with named diagnostics.
|
||||
- `BundleInstantiate` gained a WebAssembly execution tier behind a provider seam; other bundles fall back to the portable VM.
|
||||
- `std/vorbis` reads a stream's channels, rate and length; `std/vorbis_linux` decodes whole streams to 16-bit PCM, linking the library only on import.
|
||||
|
||||
### Removed
|
||||
- The Python target: `zi2py`, `--target=py`, `py:` imports and the `std/*_py`
|
||||
modules. Run native scripts with `ziran run --target=c`.
|
||||
- The separate `zi2zx-vm` runner. `zi2zx run --vm FILE` runs a bundle on the
|
||||
portable VM instead.
|
||||
- The Python target: `zi2py`, `--target=py`, `py:` imports and the `std/*_py` modules. Run native scripts with `ziran run --target=c`.
|
||||
- The separate `zi2zx-vm` runner; `zi2zx run --vm FILE` runs a bundle on the portable VM instead.
|
||||
|
||||
### Changed
|
||||
- Native `--exe` builds default to `-O3`, and lowering a ZX bundle to C is
|
||||
faster because read-only field walks no longer copy each field.
|
||||
- Compiler commands run at low CPU and disk priority (`ZIRAN_NICE`) and use at most half of the CPUs, bounded by free memory (`ZIRAN_JOBS` lowers it). `zi2c` writes C on worker processes, and the lifetime check no longer rescans every global and function, which halves Breeze's front-end time. `--prune-stale` also cleans subdirectories.
|
||||
- Native `--exe` builds default to `-O3`, and lowering a ZX bundle to C no longer copies each read-only field.
|
||||
- Compiler commands run at low CPU and disk priority and use at most half the CPUs, bounded by free memory (`ZIRAN_NICE`, `ZIRAN_JOBS`).
|
||||
- Native builds run `#parallel for` regions on one thread per processor instead of four; `ZIRAN_PAR_THREADS` still chooses.
|
||||
- Saved IR (format 59) writes each string once and refers back to it, stores numbers in as few bytes as they need, and stores source positions relative to the previous one, so `.zir` files and `.zx` bundles carry about a third of their former code size at the same open cost. Rebuild format 58 IR and bundles from source.
|
||||
- Saved IR writes each string once and stores numbers compactly, so `.zir` files and `.zx` bundles carry about a third of their former size; rebuild format 58 files.
|
||||
|
||||
### Fixed
|
||||
- The later lines of a string that spans several lines keep their text: `int`
|
||||
and `float` there became `s64` and `float32`, and assembly such as
|
||||
`vmov.i32` was rejected as an old type spelling.
|
||||
- The standard vector reference includes capacity operations, and their portable
|
||||
regression test links correctly with an instrumented compiler library.
|
||||
- Portable record globals correctly initialize fields from open-import constants,
|
||||
including imports used only by initializers.
|
||||
- Keep caching native script runs when the compiler binary is larger than 16 MiB.
|
||||
- `ziran lock` and `ziran update` resolve a project that depends on a package and also pins the same repository commit as a source checkout, such as a game and its artwork. The source checkout gets its own lock entry instead of failing with "cannot update project lock"; existing locks still verify.
|
||||
- Android applications report portable execution errors in the system log, so failures can be diagnosed when no terminal is attached.
|
||||
- Artifact recipes accept up to 256 inputs, so a provider with a long source
|
||||
list no longer fails with "unknown or invalid artifact recipe".
|
||||
- Add-ons can use records, functions and globals that a shared library did not
|
||||
retain, even when both use the same module. Only such add-ons need portable
|
||||
bundle format 27; every other bundle is written as format 26, so hosts built
|
||||
before 27 still open it.
|
||||
- Native C builds keep globals and constants separate from foreign library symbols, so a variable such as `open` cannot replace the system file-opening function and crash the program.
|
||||
- `ziran lock` and `ziran update` lock one package when manifests name the same commit by a branch and by that commit; they failed with "cannot update project lock". A full-commit ref now matches a package locked at that commit.
|
||||
- Bundles accept arrays of fixed arrays as function and host capability parameters.
|
||||
- `#parallel for` regions reject mutating, foreign and procedure-value calls nested inside larger expressions.
|
||||
- Native parallel workers see every binding their body reads, including parameters and fixed arrays.
|
||||
- `#parallel for` bodies can write into arrays they declare themselves.
|
||||
- Saved IR keeps the result type of a call whose argument is another call with widened arguments, such as `!Open(board, Index(x, y))`, so builds from it no longer fail with "saved IR does not match the checked program".
|
||||
- `#parallel for` regions reject handing a shared slice to a callee that writes through it, directly or by passing it on.
|
||||
- Natively run bundles reach a bound Ziran provider exported under another symbol.
|
||||
- Go output converts a conditional's arms to its type, such as a float32 arm of a float64 conditional.
|
||||
- `StartProcess` and `RunProcess` open input, output and error files relative to the caller's working directory, before the child changes into `directory`.
|
||||
- Later lines of a multiline string keep their text instead of old type spellings.
|
||||
- Portable record globals initialize fields from open-import constants.
|
||||
- Caching native script runs survives compiler binaries larger than 16 MiB.
|
||||
- `ziran lock` and `ziran update` resolve a commit also pinned as a source checkout, and lock one package named by branch and by commit.
|
||||
- Android applications report portable execution errors in the system log.
|
||||
- Artifact recipes accept up to 256 inputs.
|
||||
- Add-ons can use records, functions and globals a shared library did not retain; only those bundles need format 27.
|
||||
- Native C builds keep globals and constants separate from foreign library symbols.
|
||||
- Bundles accept arrays of fixed arrays as parameters.
|
||||
- `#parallel for` regions reject mutating nested calls and shared-slice writes; native workers see every binding their body reads.
|
||||
- Saved IR keeps the result type of a call whose argument is another call with widened arguments.
|
||||
- Natively run bundles reach a provider exported under another symbol.
|
||||
- Go output converts a conditional's arms to its type.
|
||||
- `StartProcess` and `RunProcess` open redirected files relative to the caller's directory.
|
||||
|
||||
## [0.3.1] - 2026-10-23
|
||||
### Fixed
|
||||
- Source generation now preserves output errors on hosts that use file-backed text streams.
|
||||
- Website release links now follow the installed compiler version.
|
||||
- Source generation preserves output errors on hosts using file-backed text streams.
|
||||
- Website release links follow the installed compiler version.
|
||||
|
||||
## [0.3.0] - 2026-10-23
|
||||
### Changed
|
||||
- Portable executables and libraries now use `.zx`, the `zi2zx` tool, and the `zx` target. Source stays `.zi` and checked intermediate modules stay `.zir`. Rebuild previous `.zib` programs; renaming a file does not convert it.
|
||||
- Portable executables and libraries use `.zx`, the `zi2zx` tool and the `zx` target; source stays `.zi`, checked modules `.zir`. Rebuild previous `.zib` programs.
|
||||
|
||||
### Fixed
|
||||
- Go output no longer needs temporary filesystem space and reports output write failures instead of producing incomplete source files.
|
||||
- Go output no longer needs temporary filesystem space and reports output write failures.
|
||||
|
||||
## [0.2.0] - 2026-09-28
|
||||
### Added
|
||||
- `ziran version` (and `--version`) prints the compiler version.
|
||||
- Release tags now follow the compiler, so `ref = "v0.2.0"` in `ziran.toml` pins a release.
|
||||
- Release tags follow the compiler, so `ref = "v0.2.0"` in `ziran.toml` pins a release.
|
||||
|
||||
### Changed
|
||||
- A clean build of the compiler is much faster and uses at most eight cores.
|
||||
|
||||
@@ -1,105 +1,77 @@
|
||||
# Ziran
|
||||
|
||||
Ziran is a general-purpose language that compiles to C and Go. The toolchain checks source, saves checked modules, and builds portable
|
||||
programs you can run without a native compiler.
|
||||
Ziran is a general-purpose language with direct native, WebAssembly, portable
|
||||
ZX, C and Go output. Master includes Unreleased work; the current version is
|
||||
in [VERSION](VERSION) and [CHANGELOG.md](CHANGELOG.md).
|
||||
|
||||
[Website & playground](https://ziran-lang.org/) · [Compiler guide](docs/USAGE.md) · [Implementation status](docs/IMPLEMENTATION_STATUS.md)
|
||||
|
||||
The compiler and portable runner are under active development. Language
|
||||
coverage and target limits are listed in the implementation status.
|
||||
|
||||
## Try it
|
||||
|
||||
```jai
|
||||
main :: () {
|
||||
print("Hello, World!\n");
|
||||
}
|
||||
```
|
||||
|
||||
Edit and run this example in the [browser playground](https://ziran-lang.org/).
|
||||
[Website and playground](https://ziran-lang.org/) · [Compiler guide](docs/USAGE.md) · [Current support](docs/IMPLEMENTATION_STATUS.md)
|
||||
|
||||
## Quick start
|
||||
|
||||
You need Make, a C11 compiler, and GNU binutils. From the repository root:
|
||||
Build with Make, a C11 compiler and GNU binutils:
|
||||
|
||||
```sh
|
||||
make
|
||||
build/bin/ziran bundle --root site/examples --entry hello:main \
|
||||
-o build/hello.zx site/examples/hello.zi
|
||||
build/bin/ziran run build/hello.zx
|
||||
build/bin/ziran check examples/hello.zi
|
||||
build/bin/ziran run examples/hello.zi
|
||||
build/bin/ziran build examples/hello.zi
|
||||
```
|
||||
|
||||
This prints `Hello, World!`. To install the `ziran` command for your user, run
|
||||
`make install-user` and add `~/.local/bin` to your `PATH`. Then start a
|
||||
project from a template and run it:
|
||||
`run` checks and executes `main`; `build` defaults to a direct native binary.
|
||||
`make install-user` installs the tools in `~/.local/bin`.
|
||||
|
||||
```sh
|
||||
ziran new hello # or --template lib, or a package's template
|
||||
cd hello
|
||||
ziran run -- Ada # Hello, Ada!
|
||||
```zi
|
||||
main :: () { print("Hello, World!\n") }
|
||||
```
|
||||
|
||||
See [packages and projects](docs/PACKAGES.md) for templates, dependencies,
|
||||
and `ziran build`/`install`.
|
||||
## Tools
|
||||
|
||||
## Tools and formats
|
||||
|
||||
Use `build/bin/ziran` from the checkout, or `ziran` after installation.
|
||||
Source → ZIR → LIR → optimized LIR → ZX → native (ELF/PE, x86-64/AArch64/ARMv7).
|
||||
WebAssembly lowers from verified ZX through `zx2wasm`; C and Go export from ZIR
|
||||
through `zi2c` and `zi2go`.
|
||||
|
||||
| Command | Purpose |
|
||||
| --- | --- |
|
||||
| `check` | Validate source and imports. |
|
||||
| `build` | Generate C or Go output. |
|
||||
| `ir` / `inspect` | Save checked modules and read their contents. |
|
||||
| `bundle` / `run` | Build and run portable programs; `run --target=c FILE.zi -- ARGS` runs native scripts. |
|
||||
| `fmt` | Format source files. |
|
||||
| `guide` / `features` / `capabilities` | Explore syntax, support, and target limits. |
|
||||
| `api` | Query public declarations as JSON. |
|
||||
| `build` | Build native output, or select `--target=c`, `go`, `wasm` or `zx`. |
|
||||
| `ir` / `inspect` | Save checked `.zir` modules and inspect artifacts. |
|
||||
| `bundle` / `run` | Link `.zx` executables and run source or ZX. |
|
||||
| `learn` | Control native-build corpus recording and offline C-teacher verification/training. |
|
||||
| `fmt` | Format source. |
|
||||
| `guide` / `features` / `capabilities` | Query syntax and target limits. |
|
||||
| `api` | Query checked public declarations. |
|
||||
|
||||
Source files use `.zi`, checked modules use [`.zir`](docs/ZIR.md), and portable
|
||||
programs use [`.zx`](docs/ZX.md). Native targets and the portable runner have
|
||||
different limits.
|
||||
|
||||
## Standard library
|
||||
|
||||
The library includes text and UTF-8 helpers, generic values, sorting, queues,
|
||||
JSON scanning, ZIP archives, and explicit HTTP and process capabilities.
|
||||
Native Linux adapters provide file, socket, timer, and other system operations.
|
||||
|
||||
See the [standard library reference](https://ziran-lang.org/stdlib.html) and
|
||||
[compiler guide](docs/USAGE.md#standard-library) for imports and platform limits.
|
||||
Safety is manual by default, as in C. `--checks` opts a build into runtime
|
||||
checks; `#checks` keeps bounds checks in selected source regions. See
|
||||
[checks](docs/USAGE.md#checks) for target-specific behavior.
|
||||
|
||||
## Documentation
|
||||
|
||||
| Start here | What it covers |
|
||||
| Read | When you need |
|
||||
| --- | --- |
|
||||
| [Compiler guide](docs/USAGE.md) | Commands, imports, foreign functions, and standard modules. |
|
||||
| [Examples](https://ziran-lang.org/examples.html) | Small programs with source and output. |
|
||||
| [Implementation status](docs/IMPLEMENTATION_STATUS.md) | Supported features and remaining work. |
|
||||
| [Architecture](docs/ARCHITECTURE.md) | Compiler, runtime, and library boundaries. |
|
||||
| [Language direction](docs/LANGUAGE_DIRECTION.md) | Language design and tooling goals. |
|
||||
| [Jai parity roadmap](docs/JAI_PARITY_ROADMAP.md) | Planned language work. |
|
||||
| [Benchmarks](bench/README.md) | Compiler and runtime measurements. |
|
||||
| [Migration](docs/MIGRATION.md) | Repository migration details. |
|
||||
| [docs/USAGE.md](docs/USAGE.md) | The compiler and standard library guide |
|
||||
| [docs/IMPLEMENTATION_STATUS.md](docs/IMPLEMENTATION_STATUS.md) | Supported targets and limits |
|
||||
| [docs/PACKAGES.md](docs/PACKAGES.md) | Packages, projects, and lock files |
|
||||
| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | The compiler pipeline |
|
||||
| [docs/LANGUAGE_DIRECTION.md](docs/LANGUAGE_DIRECTION.md) | Language syntax and directives |
|
||||
| [docs/OWNED_VALUES.md](docs/OWNED_VALUES.md) | Owned values and recoverable failures |
|
||||
| [docs/DIAGNOSTICS.md](docs/DIAGNOSTICS.md) | Diagnostic codes and JSON output |
|
||||
| [docs/AUTHORING.md](docs/AUTHORING.md) | Tool-driven editing workflows |
|
||||
| [docs/LAWS.md](docs/LAWS.md) | Laws and proof certificates |
|
||||
| [docs/ZX.md](docs/ZX.md) | The portable ZX format |
|
||||
| [bench/README.md](bench/README.md) | Running benchmarks |
|
||||
| [plans/open-work.md](plans/open-work.md) | What is still open |
|
||||
|
||||
Kryon is a separate UI library that applications import explicitly.
|
||||
Standard library and package APIs: [ziran-lang.org/modules.html](https://ziran-lang.org/modules.html).
|
||||
|
||||
Kryon is a separate UI library imported by applications; console programs have
|
||||
no graphics dependency. Repository rules for agents live in
|
||||
[AGENTS.md](AGENTS.md).
|
||||
|
||||
## Development
|
||||
|
||||
Run `make check` for the language, backend, and portable runtime checks.
|
||||
Tests use four workers by default; set `CHECK_JOBS=1` to run them serially.
|
||||
|
||||
The native command and formatter are written in Ziran. Compiler scanners,
|
||||
declaration, foreign binding, and `using` modifier syntax, enum validation and
|
||||
evaluation, type spelling and field parsing, expression and nested initializer
|
||||
grammar, statement expression extraction, loop headers, optional `then`, and
|
||||
compile-time branch syntax are also written in Ziran. Ziran also parses multiple
|
||||
results and bindings, normalizes procedure-type parameters, expands formatted
|
||||
builder statements, and rewrites
|
||||
symmetric operators, procedure-name expressions, and local procedure names.
|
||||
The rest of the compiler is still being migrated from C.
|
||||
A fresh build uses the generated modules in `bootstrap/` to build a bootstrap
|
||||
compiler, then compiles their maintained `cmd/compiler_*.zi` sources for the
|
||||
ordinary tools. Run
|
||||
`make check-bootstrap` to verify that the generated seed matches the source.
|
||||
After changing a compiler module, use `make update-bootstrap` to refresh its seed.
|
||||
Run `make check` for the retained local suite and `make check-bootstrap` for
|
||||
bootstrap reproducibility. `CHECK_FILTER=text` selects matching tests. The
|
||||
compiler uses maintained Ziran and C sources; bootstrap seeds live in
|
||||
`bootstrap/`. Refresh affected seeds with `make update-bootstrap` after
|
||||
compiler changes.
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
ASSEMBLY_C := $(BUILD_DIR)/compiler-assembly
|
||||
ASSEMBLY_MACHINE_SOURCES := cmd/compiler_vector_form.zi cmd/compiler_vectorize.zi cmd/compiler_vector_x86.zi \
|
||||
cmd/compiler_target.zi cmd/compiler_machine_image.zi cmd/compiler_abi.zi cmd/compiler_machine_ir.zi \
|
||||
cmd/compiler_machine_verify.zi cmd/compiler_machine_aggregate.zi cmd/compiler_machine_fields.zi cmd/compiler_machine_select.zi cmd/compiler_machine_lower.zi \
|
||||
cmd/compiler_machine_verify_allocated.zi cmd/compiler_regalloc.zi cmd/compiler_x86_bytes.zi cmd/compiler_x86_64.zi cmd/compiler_x86_runtime.zi \
|
||||
cmd/compiler_x86_win64.zi cmd/compiler_x86_host.zi cmd/compiler_x86_image.zi \
|
||||
cmd/compiler_encode.zi cmd/compiler_aarch64.zi cmd/compiler_aarch64_runtime.zi cmd/compiler_aarch64_elf.zi cmd/compiler_armv7.zi cmd/compiler_armv7_runtime.zi cmd/compiler_armv7_elf.zi \
|
||||
cmd/compiler_arm_bytes.zi \
|
||||
cmd/compiler_machine_elf.zi cmd/compiler_machine_pe.zi cmd/compiler_machine_pipeline.zi cmd/compiler_native_cache.zi
|
||||
ASSEMBLY_SOURCES := std/math.zi cmd/compiler_bundle.zi cmd/compiler_lowered_ir.zi cmd/compiler_lowered_verify.zi cmd/compiler_lowered_proven.zi cmd/compiler_zir_lower.zi cmd/compiler_zx_run.zi cmd/compiler_exec_serial.zi cmd/compiler_exec_debug.zi cmd/compiler_exec_link.zi cmd/compiler_exec.zi cmd/compiler_opt.zi cmd/compiler_opt_ssa.zi cmd/compiler_opt_rotate.zi cmd/compiler_opt_loop.zi cmd/compiler_opt_licm.zi cmd/compiler_opt_induction.zi cmd/compiler_opt_layout.zi cmd/compiler_opt_inline.zi cmd/compiler_opt_specialize.zi cmd/compiler_opt_thread.zi cmd/compiler_opt_accumulate.zi cmd/compiler_opt_dom.zi cmd/compiler_learning.zi cmd/compiler_learning_policy.zi cmd/compiler_learning_table.zi $(ASSEMBLY_MACHINE_SOURCES)
|
||||
ASSEMBLY_SOURCES += std/finite.zi
|
||||
|
||||
ifneq ($(BOOTSTRAP),1)
|
||||
ifeq ($(NATIVE_HOST_ENABLED),1)
|
||||
# Only these objects read the generated assembly headers. A target-specific
|
||||
# CFLAGS would also reach the prerequisites make builds for it, zi2c among
|
||||
# them, where the set's own math.h and vec.h would shadow the real ones;
|
||||
# `private` prevents that but needs GNU Make 3.82, and macOS ships 3.81.
|
||||
$(foreach source,bootstrap/runtime/zir_host_native.c bootstrap/runtime/zir_host_native_armv7.c,\
|
||||
$(eval $(call obj,$(source))_CFLAGS += -I$(ASSEMBLY_C)))
|
||||
$(call obj,bootstrap/runtime/zir_host_native.c bootstrap/runtime/zir_host_native_armv7.c): $(ASSEMBLY_C)/.generated
|
||||
endif
|
||||
endif
|
||||
|
||||
.PHONY: zx-tools
|
||||
zx-tools: $(BIN_DIR)/zi2zx $(BIN_DIR)/zx2wasm $(BIN_DIR)/zx2native
|
||||
|
||||
check: zx-tools
|
||||
|
||||
# The generator runs whenever its sources or zi2c change, but only files
|
||||
# whose text changed are replaced, and .generated moves only then: a zi2c
|
||||
# relinked for a new checkout path (a prebuilt tree) recompiles nothing.
|
||||
$(ASSEMBLY_C)/.ran: assembly.mk $(ASSEMBLY_SOURCES) $(GEN_ZI2C)
|
||||
rm -rf $(BUILD_DIR)/compiler-assembly.next
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY $(GEN_ZI2C) --no-main --root cmd -o $(BUILD_DIR)/compiler-assembly.next \
|
||||
cmd/compiler_lowered_verify.zi cmd/compiler_zir_lower.zi cmd/compiler_exec_serial.zi cmd/compiler_exec_link.zi cmd/compiler_exec.zi cmd/compiler_opt.zi \
|
||||
cmd/compiler_machine_pipeline.zi cmd/compiler_native_cache.zi cmd/compiler_zx_run.zi
|
||||
@mkdir -p $(ASSEMBLY_C); changed=; \
|
||||
for f in $(BUILD_DIR)/compiler-assembly.next/*; do \
|
||||
cmp -s "$$f" "$(ASSEMBLY_C)/$${f##*/}" || { cp "$$f" $(ASSEMBLY_C)/; changed=1; }; done; \
|
||||
for f in $(ASSEMBLY_C)/*; do \
|
||||
[ -e "$(BUILD_DIR)/compiler-assembly.next/$${f##*/}" ] || { rm -f "$$f"; changed=1; }; done; \
|
||||
if [ -n "$$changed" ] || [ ! -e $(ASSEMBLY_C)/.generated ]; then touch $(ASSEMBLY_C)/.generated; fi
|
||||
rm -rf $(BUILD_DIR)/compiler-assembly.next
|
||||
touch $@
|
||||
|
||||
$(ASSEMBLY_C)/.generated: $(ASSEMBLY_C)/.ran
|
||||
@test -f $@ || touch $@
|
||||
|
||||
$(BUILD_DIR)/obj/assembly-core.o: assembly.mk $(ASSEMBLY_C)/.generated $(BUILD_DIR)/.compiler-flags
|
||||
@mkdir -p $(BUILD_DIR)/obj/assembly
|
||||
@set -eu; objects=; for source in $(ASSEMBLY_C)/*.c; do \
|
||||
object=$(BUILD_DIR)/obj/assembly/$$(basename "$$source" .c).o; \
|
||||
$(CC) $(CFLAGS) $(FRAMEFLAGS) -I$(ASSEMBLY_C) -c -o "$$object" "$$source"; \
|
||||
objects="$$objects $$object"; \
|
||||
done; $(CC) -r -nostdlib -o $@ $$objects
|
||||
|
||||
# The embedding library already carries the source compiler and the verified-ZX
|
||||
# engine, including its own compiler_bundle symbols. Keep the native machine
|
||||
# pipeline in a separate relocatable object so linking libziran cannot pull in a
|
||||
# second copy of those public symbols from assembly-core.o.
|
||||
ASSEMBLY_NATIVE_MODULES := compiler_vector_form compiler_vectorize compiler_vector_x86 compiler_opt_ssa \
|
||||
compiler_abi compiler_machine_image \
|
||||
compiler_machine_ir compiler_machine_verify \
|
||||
compiler_machine_aggregate compiler_machine_fields compiler_machine_select compiler_machine_lower compiler_machine_verify_allocated compiler_regalloc \
|
||||
compiler_target compiler_learning compiler_learning_policy compiler_x86_bytes compiler_x86_64 compiler_x86_runtime compiler_encode compiler_aarch64 compiler_aarch64_runtime compiler_aarch64_elf compiler_armv7 compiler_armv7_runtime compiler_armv7_elf \
|
||||
compiler_x86_win64 compiler_x86_host compiler_x86_image \
|
||||
compiler_x86_archive \
|
||||
compiler_arm_bytes \
|
||||
compiler_machine_elf compiler_machine_pe \
|
||||
compiler_machine_pipeline \
|
||||
compiler_native_cache
|
||||
|
||||
$(BUILD_DIR)/obj/native-core.o: assembly.mk $(ASSEMBLY_C)/.generated $(ENGINE_NAMES) $(BUILD_DIR)/.compiler-flags
|
||||
@mkdir -p $(BUILD_DIR)/obj/native-assembly
|
||||
@set -eu; objects=; for module in $(ASSEMBLY_NATIVE_MODULES); do \
|
||||
source=$(ASSEMBLY_C)/$$module.c; \
|
||||
object=$(BUILD_DIR)/obj/native-assembly/$$module.o; \
|
||||
test -f "$$source"; \
|
||||
$(CC) $(CFLAGS) $(FRAMEFLAGS) -fvisibility=hidden -I$(ASSEMBLY_C) \
|
||||
-include $(ENGINE_NAMES) -c -o "$$object" "$$source"; \
|
||||
objects="$$objects $$object"; \
|
||||
done; $(CC) -r -nostdlib -o $@ $$objects
|
||||
|
||||
# zx2native's driver is Ziran (cmd/zx2native.zi); the generated copy uses the
|
||||
# assembly set's own headers and links its unprefixed entry points.
|
||||
ZX2NATIVE_C := $(BUILD_DIR)/zx2native-c
|
||||
$(ZX2NATIVE_C)/.generated: cmd/zx2native.zi cmd/compiler_cli.zi cmd/compiler_ir.zi \
|
||||
$(BUILD_DIR)/compiler-assembly/.generated $(BIN_DIR)/zi2c
|
||||
$(BIN_DIR)/zi2c --entry zx2native:main --root cmd --module-path std -o $(ZX2NATIVE_C) cmd/zx2native.zi
|
||||
touch $@
|
||||
$(ZX2NATIVE_C)/%.c: $(ZX2NATIVE_C)/.generated
|
||||
@test -f $@
|
||||
|
||||
$(BIN_DIR)/zx2native: $(ZX2NATIVE_C)/zx2native.c \
|
||||
$(BUILD_DIR)/obj/assembly-core.o $(BUILD_DIR)/libziran.a | $(BIN_DIR)
|
||||
$(NICE) $(CC) $(CFLAGS) -I$(ZX2NATIVE_C) -I$(BUILD_DIR)/compiler-assembly -o $@ \
|
||||
$(ZX2NATIVE_C)/zx2native.c $(BUILD_DIR)/obj/assembly-core.o $(BUILD_DIR)/libziran.a $(RUNTIME_LIBS)
|
||||
chmod 755 $@
|
||||
+177
-32
@@ -1,9 +1,162 @@
|
||||
# Runtime and compiler benchmarks
|
||||
|
||||
Every benchmark runs through one entry point, from the repository root:
|
||||
|
||||
```sh
|
||||
build/bin/ziran run --target=c bench/bench.zi -- list
|
||||
build/bin/ziran run --target=c bench/bench.zi -- NAME [DRIVER ARGUMENTS]
|
||||
build/bin/ziran run --target=c bench/bench.zi -- --local NAME --validate ...
|
||||
```
|
||||
|
||||
`bench/bench.zi` names every driver, gives each the same environment (no
|
||||
display or desktop-session variables, no `ZIRAN_PROFILE`, and `ZIRAN_LEARN=off`
|
||||
so the learning corpus never records during a benchmark) and refuses to measure
|
||||
a host benchmark anywhere but the physical host named by `ZIRAN_BENCH_HOST`,
|
||||
`alpha` by default. `--local` is for measurement-free modes. A new driver is
|
||||
registered in `bench/bench.zi`; `tests/bench_entry.sh` fails while one is not.
|
||||
The per-benchmark commands below are the driver arguments; prefix each with
|
||||
the entry point instead of running the driver directly.
|
||||
|
||||
Run benchmark builds and measurements on Alpha's physical host, as requested
|
||||
by the owner on 2026-11-11, from the canonical Ziran repository there.
|
||||
Reject virtualized execution. If Alpha is unavailable, wait rather than running the
|
||||
benchmark on the current desktop. Record the host in every report and collect
|
||||
both sides of a comparison on the same host; retained desktop results keep
|
||||
their original provenance.
|
||||
|
||||
## Standard benchmarks and the host gate
|
||||
|
||||
`bench/standard/README.md` describes the standard language benchmarks
|
||||
(`wasm-tier --standard`, `--standard-full` for the Benchmarks Game sizes) and
|
||||
`standard-compile`. Anything the site's kernel or standard tables publish is
|
||||
measured with `--host-gate`: each measured job runs on one logical CPU of the
|
||||
quietest core, inherited by the child so no wrapper process adds time, with Go
|
||||
at `GOMAXPROCS=1`. A poller on the other cores reads that CPU's
|
||||
`scaling_cur_freq` every 10 ms and the sibling's busy time. A job is kept only
|
||||
if its 10th to 90th percentile clock is within 3% of its median, the median
|
||||
reaches 95% of the clock calibrated at start, and the hyperthread sibling is
|
||||
busy at most 15% of the job; otherwise it runs again (up to eight attempts),
|
||||
and rejected attempts stay in the receipt with their observations. The site
|
||||
generators refuse receipts without it. Alpha's powersave/HWP clock otherwise
|
||||
moves between 0.8 and 4.3 GHz and run time follows it
|
||||
(`results/records-native-frequency-alpha-2026-11-16.json`). Compile-time builds
|
||||
are not pinned.
|
||||
|
||||
Timed compiler/codec kernels are an explicit benchmark command, outside
|
||||
`make check`: `build/bin/ziran run --target=c bench/bench.zi -- compiler-kernels` on Alpha.
|
||||
Routine tests still validate benchmark statistics and command interfaces.
|
||||
|
||||
## JSON and UTF-8 workloads
|
||||
|
||||
On Alpha, run `build/bin/ziran run --target=c bench/bench.zi -- json-text --samples 11` to build and measure
|
||||
the six Ziran programs in `bench/json_text/`. Each timed batch verifies its
|
||||
result. The website retains generated artifacts, raw samples and compiler
|
||||
diagnostics for unsupported targets in `site/generated/json-text/`.
|
||||
The qualified Alpha snapshot is retained in `bench/results/json-text/alpha-matrix.json`.
|
||||
Use `build/bin/ziran run --target=c bench/bench.zi -- --local json-text --check` to validate that snapshot without timing it.
|
||||
|
||||
## Portable ZX execution
|
||||
|
||||
```sh
|
||||
build/bin/ziran run --target=c bench/bench.zi -- zx-execution
|
||||
```
|
||||
|
||||
This Ziran script measures every unchanged portable bundle in the published
|
||||
target matrix, verifies output and checksums, and records three repetitions of
|
||||
nine warm batches. Symmetric 1.5×IQR filtering excludes anomalies from each median while retaining the raw samples and excluded indices. Source, library and bundle hashes detect drift. Retained
|
||||
before/after measurements and the bottleneck analysis are in
|
||||
[`results/zx-loops/README.md`](results/zx-loops/README.md).
|
||||
|
||||
Library workloads live upstream. The website's generic library harness accepts
|
||||
Kryon's manifest without adding widget behavior to Ziran:
|
||||
|
||||
```sh
|
||||
build/bin/ziran run --target=c bench/bench.zi -- library-targets \
|
||||
--project ../../kryonlabs/kryon \
|
||||
--manifest ../../kryonlabs/kryon/tests/widget_benchmarks.json --samples 9
|
||||
```
|
||||
|
||||
Use the actual Kryon checkout path. The published archive contains all checked modules;
|
||||
the source fixtures, generated C/Go/ZX and raw samples are downloadable.
|
||||
These desktop cases measure public widget behavior and recorded paint commands,
|
||||
excluding pixel rasterization and OS I/O.
|
||||
|
||||
## ZX assembly comparison receipts
|
||||
|
||||
`assembly_collect.zi` validates an exact campaign plan and, only after fresh
|
||||
Alpha physical-host attestation, executes explicitly selected modes into the
|
||||
strict raw schema consumed by `assembly_compare.zi`. Local plan validation is
|
||||
measurement-free:
|
||||
|
||||
```sh
|
||||
build/bin/ziran run --target=c bench/bench.zi -- --local assembly-collect --validate PLAN.json
|
||||
```
|
||||
|
||||
Run `PLAN.json OUTPUT.json` instead only in the canonical checkout on Alpha's
|
||||
physical host. The collector hashes the workload and complete declared runtime
|
||||
closure before and after collection, enforces private cache/process boundaries,
|
||||
checks every sample's stdout oracle, and atomically emits raw samples. It
|
||||
supports explicit old VM, lowered portable, direct-AOT and control selectors.
|
||||
The current default ZX runtime is not native-only proof, so
|
||||
`old-c-tinycc-native` remains missing; no `new-native` ZX selector exists.
|
||||
Direct AOT is never relabeled as that engine. The exact plan schema, phase
|
||||
units, invocation, and remaining gates are in
|
||||
[`../ASSEMBLY/performance-report.md`](../ASSEMBLY/performance-report.md).
|
||||
|
||||
## ZX runtime comparison 2 driver
|
||||
|
||||
`zx_compare.zi` measures the portable engine, cold native ZX, warm native ZX,
|
||||
the `zx2native` AOT ELF control and the C control over identical workloads in
|
||||
one receipt. Every trial verifies the oracle checksum, the reported backend
|
||||
and, for native cohorts, the native evidence flag. The receipt records the
|
||||
machine, virtualization and load averages before and after the run, hashes of
|
||||
the driver, helper, control and library sources, the fixture artifact hashes,
|
||||
and the copied M0 TinyCC summary:
|
||||
|
||||
```sh
|
||||
build/bin/ziran run --target=c bench/bench.zi -- zx-compare --engine --native-cold --native-warm --aot \
|
||||
--c-control --m0-receipts bench/results --samples 9
|
||||
```
|
||||
|
||||
Every prepare step (fixture `zi2zx`, the `zx-host` helper build, the C control
|
||||
build, the per-kind AOT source generation and builds) runs through the queue
|
||||
and is recorded with its command line, exit code and wall time. The receipt is
|
||||
written atomically after every trial, and the integrity block re-hashes every
|
||||
input before the driver reports success. Without `--out`, the receipt is
|
||||
`bench/results/zx-compare-<host>-<date>.json`. `--alpha` additionally enforces
|
||||
the Alpha physical-host attestation gate for receipts that claim it.
|
||||
|
||||
## Fresh compiler rebuild
|
||||
|
||||
```sh
|
||||
build/bin/ziran run --target=c bench/bench.zi -- compiler-build
|
||||
```
|
||||
|
||||
This times `make -B -jN all` at the normal `build/` paths: all native Ziran
|
||||
compiler tools and `libziran.a` rebuild, including generated compiler modules.
|
||||
`--jobs N` selects concurrency; the default uses the queue's allocation when
|
||||
available, otherwise the Makefile's usual half-CPU limit of 2–16 jobs.
|
||||
|
||||
Results, raw build output and sample history are retained under the tracked
|
||||
`bench/results/compiler-build/` path. The wall time excludes queue waiting,
|
||||
tests, installation and website builds. The report records CPU time, source
|
||||
diff fingerprint, revision, dirty state and compilation count. Filesystem caches
|
||||
remain warm; `make -B` forces all build targets to rebuild without deleting
|
||||
other build outputs.
|
||||
|
||||
Add `--profile` to record every make shell recipe's monotonic start, finish
|
||||
and elapsed time in `recipes.json`, with the 20 slowest in
|
||||
`slowest-recipes.json`. Profiling keeps compiler optimization flags
|
||||
unchanged, but adds process instrumentation; use ordinary runs for timing claims.
|
||||
|
||||
The temporary bootstrap seed defaults to `-O0`: it only emits the compiler
|
||||
modules' C before the final tools are built with the normal `CFLAGS=-O2`.
|
||||
`BOOTSTRAP_CFLAGS=-O2` restores the former seed settings for a comparison.
|
||||
|
||||
## Complete native builds
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/native_builds.py \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- native-builds \
|
||||
--out build/benchmarks/native-builds
|
||||
```
|
||||
|
||||
@@ -66,7 +219,7 @@ while retaining separate translation units and the existing worker limit.
|
||||
For a complete build of the formatter application itself:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/formatter_builds.py \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- formatter-builds \
|
||||
--before-bin-dir PATH/TO/PRESERVED/bin \
|
||||
--out build/benchmarks/native-programs/formatter
|
||||
```
|
||||
@@ -91,14 +244,6 @@ Dependency metadata must contain at least 512 inputs per consumer. Fresh and
|
||||
unchanged samples share warm machine caches and identical source inputs.
|
||||
This compares two compiler versions, without a Go or C language baseline.
|
||||
|
||||
`bench/native_cache_names.py --before-ref REVISION
|
||||
--out build/benchmarks/native-cache-names` isolates ordered-name collection at
|
||||
16, 256, 2,048 and 8,192 names. It compiles the earlier cache source from Git
|
||||
through compiler standard input and compares it with the current source.
|
||||
Each sample inserts unique names, repeats duplicates, checks order and an
|
||||
independent checksum, then frees the collection. Input preparation and process
|
||||
startup are outside the internal timer. Report this container timing
|
||||
separately from whole builds; process RSS also includes benchmark inputs.
|
||||
Both harnesses save raw samples, tool/source hashes and actual CPU affinity.
|
||||
For a before/after comparison that reaches late record types within the former
|
||||
512-module limit, add `--groups 4 --read-last` to the header-graph benchmark.
|
||||
@@ -155,7 +300,7 @@ Preserve `ziran`, `zi2zir`, `zi2c` and `zi2zx` together before changing the
|
||||
compiler, then run:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/body_eligibility.py \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- body-eligibility \
|
||||
--before-bin-dir build/body-eligibility/before \
|
||||
--out build/benchmarks/body-eligibility
|
||||
```
|
||||
@@ -183,7 +328,7 @@ Before changing the runtime, preserve `zi2zir`, `zi2zx` and `libziran.a` togethe
|
||||
in a stable baseline directory. Then run:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/vm_execution.py \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- vm-execution \
|
||||
--before-dir build/vm-execution/before --out build/benchmarks/vm-execution
|
||||
```
|
||||
|
||||
@@ -212,7 +357,7 @@ hashes and expected results alongside the existing raw timing receipts.
|
||||
To calibrate these same workloads against generated native C and Go:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/vm_native.py \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- vm-native \
|
||||
--vm-results build/benchmarks/vm-execution \
|
||||
--out build/benchmarks/vm-native
|
||||
```
|
||||
@@ -237,10 +382,10 @@ the measured workloads; they do not establish whole-application C/Go parity.
|
||||
## Android device execution
|
||||
|
||||
Prepare matched Ziran source/saved-IR C and Go programs, handwritten C/Go
|
||||
controls, and a portable VM fixture for one Android ABI:
|
||||
controls, and a portable engine fixture for one Android ABI:
|
||||
|
||||
```sh
|
||||
python3 bench/android_execution.py prepare \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- android-execution prepare \
|
||||
--out build/benchmarks/android-device/execution \
|
||||
--ndk "$ANDROID_NDK_HOME" --abi armeabi-v7a
|
||||
```
|
||||
@@ -249,7 +394,7 @@ Run the measurement stage on the host that owns the device's ADB connection,
|
||||
passing its exact serial:
|
||||
|
||||
```sh
|
||||
python3 bench/android_execution.py run \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- android-execution run \
|
||||
--out build/benchmarks/android-device/execution --serial DEVICE_SERIAL
|
||||
```
|
||||
|
||||
@@ -270,13 +415,13 @@ not establish Go-like compilation speed on Android.
|
||||
To compare the same seven portable workloads across saved VM libraries:
|
||||
|
||||
```sh
|
||||
python3 bench/vm_android.py prepare \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- vm-android prepare \
|
||||
--vm-results build/benchmarks/vm-execution \
|
||||
--out build/benchmarks/vm-json/android \
|
||||
--ndk "$ANDROID_NDK_HOME" --abi armeabi-v7a \
|
||||
--library before PATH/TO/BASELINE/libziran.a \
|
||||
--library after build/bundle-runtime/android-armeabi-v7a/libziran.a
|
||||
python3 bench/vm_android.py run \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- vm-android run \
|
||||
--out build/benchmarks/vm-json/android --serial DEVICE_SERIAL --cpu 0
|
||||
```
|
||||
|
||||
@@ -297,7 +442,7 @@ establish gains on another.
|
||||
## CPU-selected assembly
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/cpu_features.py \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- cpu-features \
|
||||
--out build/benchmarks/cpu-features
|
||||
```
|
||||
|
||||
@@ -330,7 +475,7 @@ and removing inactive outputs.
|
||||
## Native Go assembly bridges
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/go_assembly.py \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- go-assembly \
|
||||
--before-bin-dir build/go-assembly/before/bin \
|
||||
--out build/go-assembly/benchmark
|
||||
```
|
||||
@@ -360,7 +505,7 @@ that its binaries and build outputs are inactive.
|
||||
Host embedding has a separate capability-scaling benchmark:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/host_capabilities.py \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- host-capabilities \
|
||||
--before-dir build/host-capabilities/before --out build/benchmarks/host-capabilities
|
||||
```
|
||||
|
||||
@@ -378,7 +523,7 @@ For the public embedding API, compare one checked `BundleOpen` followed by
|
||||
independent `BundleInstantiate`/run/close operations:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/bundle_instances.py \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- bundle-instances \
|
||||
--before-dir build/bundle-runtime/before --out build/benchmarks/bundle-instances
|
||||
```
|
||||
|
||||
@@ -397,7 +542,7 @@ sum oracles, verifies source/saved bundle identity, and runs the comparison
|
||||
below. For example:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/enum_values.py \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- enum-values \
|
||||
--before-dir build/compiler-check/before --out build/benchmarks/enum-values
|
||||
```
|
||||
|
||||
@@ -419,7 +564,7 @@ For example, using fixtures generated by `compiler_scaling.py` with its default
|
||||
16 fields:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/vm_startup.py \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- vm-startup \
|
||||
--before-dir build/vm-performance/before \
|
||||
--out build/vm-performance/comparison \
|
||||
--case modules128 \
|
||||
@@ -456,7 +601,7 @@ receipts and remove inactive outputs before reusing the stable output path.
|
||||
## Assembly and portable fallback
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/assembly.py \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- assembly \
|
||||
--out build/benchmarks/assembly
|
||||
```
|
||||
|
||||
@@ -481,7 +626,7 @@ For compiler scaling, module graphs, generic specialization, and source/saved
|
||||
IR validation, run:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/compiler_scaling.py \
|
||||
build/bin/ziran run --target=c bench/bench.zi -- compiler-scaling \
|
||||
--out build/benchmarks/compiler-scaling --sizes 8 32 128
|
||||
```
|
||||
|
||||
@@ -527,7 +672,7 @@ From the repository root, build the current toolchain and run:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY make -j4 all
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/smoke.py
|
||||
build/bin/ziran run --target=c bench/bench.zi -- smoke
|
||||
```
|
||||
|
||||
The script creates a new directory under `build/benchmarks/` with `metadata.json`,
|
||||
@@ -542,7 +687,7 @@ portable `.zx`. The harness checks that generated source and bundles match,
|
||||
and validates every runtime result against an independent modular-series
|
||||
oracle before reporting times. It separately measures Ziran check/emission,
|
||||
downstream native compilation, and whole-process execution. Runtime cases are
|
||||
shuffled with a fixed seed between sample rounds. The portable VM runs only
|
||||
shuffled with a fixed seed between sample rounds. The portable engine runs only
|
||||
the small input because its instruction budget excludes the large one.
|
||||
|
||||
These numbers are a smoke baseline, not a language ranking. They include
|
||||
@@ -557,7 +702,7 @@ real applications.
|
||||
For a second workload that grows a `Vec(s32)` and then scans it, run:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/vector_growth.py
|
||||
build/bin/ziran run --target=c bench/bench.zi -- vector-growth
|
||||
```
|
||||
|
||||
This measures source and saved-IR checks and emissions to C, Go, and
|
||||
@@ -565,7 +710,7 @@ portable `.zx`, downstream native builds, and whole-process execution.
|
||||
Handwritten C, C++, Go, Rust, Java, JavaScript, and Python versions provide
|
||||
algorithm-level comparisons when their toolchains are installed; unavailable
|
||||
tools are recorded explicitly. The checksum uses a closed-form arithmetic
|
||||
oracle, and every runtime sample must match it. The portable VM runs the small
|
||||
oracle, and every runtime sample must match it. The portable engine runs the small
|
||||
input only. Raw commands, samples,
|
||||
source and tool hashes, and caveats are written alongside the report. These
|
||||
workloads remain a smoke and collection baseline; they do not cover text,
|
||||
@@ -574,7 +719,7 @@ records, generics, larger module graphs, or real applications.
|
||||
For a record-value and call workload over a fixed `[32]Point` table, run:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/record_calls.py
|
||||
build/bin/ziran run --target=c bench/bench.zi -- record-calls
|
||||
```
|
||||
|
||||
Each round updates all records through a checked `Mix(Point, Point, s32, s32)`
|
||||
@@ -594,7 +739,7 @@ binary hashes.
|
||||
For a UTF-8 scanning workload over `aé中🙂`, run:
|
||||
|
||||
```sh
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/text_scan.py
|
||||
build/bin/ziran run --target=c bench/bench.zi -- text-scan
|
||||
```
|
||||
|
||||
The text has 10 bytes and 4 Unicode scalar values; every runtime sample must
|
||||
|
||||
@@ -140,7 +140,7 @@ func benchKernel(n int64, seed uint64) uint64 {
|
||||
'Go uses GOMAXPROCS=1 for the single-threaded kernel; no device settings are changed.',
|
||||
'C/Go use the same SWAR population-count formula; Python bit_count supplies the independent oracle.'])
|
||||
(out/'manifest.json').write_text(json.dumps(data,indent=2)+'\n')
|
||||
print('Prepared Android native/Go controls and portable VM fixture')
|
||||
print('Prepared Android native/Go controls and portable engine fixture')
|
||||
|
||||
|
||||
def run(args):
|
||||
|
||||
+1
-1
@@ -155,7 +155,7 @@ Answer :: () -> s64 { return cast(s64)(Kernel(SMALL, SEED) & 9223372036854775807
|
||||
for form, root, entry in [('source', output, source), ('saved', output/'ir', output/'ir/swap.zir')]:
|
||||
directory = output / form
|
||||
repeated([binaries/'zi2c', '--root', root, '-o', directory, entry], 'compile', f'Ziran {form} emit C')
|
||||
repeated([binaries/'zi2zx', 'bundle', '--root', root, '--entry', 'swap:Answer', '-o', output/f'{form}.zx', entry],
|
||||
repeated([binaries/'zi2zx', '--root', root, '--entry', 'swap:Answer', '-o', output/f'{form}.zx', entry],
|
||||
'compile', f'Ziran {form} bundle')
|
||||
host = directory/'host.c'
|
||||
host.write_text('#include "swap.h"\n#include <stdio.h>\n#include <stdlib.h>\n'
|
||||
|
||||
@@ -0,0 +1,757 @@
|
||||
#!/usr/bin/env ziran
|
||||
// Collect strict assembly comparison receipts on Alpha's physical host.
|
||||
// Validation is measurement-free; collection never substitutes the unavailable
|
||||
// new-native ZX engine.
|
||||
#import "benchmark_statistics"
|
||||
#import "std/byte_text_linux"
|
||||
#import "std/file"
|
||||
#import "std/file_tree_linux"
|
||||
#import "std/float_text"
|
||||
#import "std/json_document"
|
||||
#import "std/math"
|
||||
#import "std/number_text"
|
||||
#import "std/process_run_linux"
|
||||
#import "std/text_tools"
|
||||
#import "std/timer_linux"
|
||||
using Vectors :: #import "std/vec"
|
||||
|
||||
#scope_file
|
||||
MAX_PLAN_BYTES :: 4194304;
|
||||
MAX_JOBS :: 2048;
|
||||
MAX_REQUIRED_CELLS :: 512;
|
||||
MAX_REPEATS :: 4096;
|
||||
MAX_TOTAL_SAMPLES :: 65536;
|
||||
MAX_TEXT :: 1024;
|
||||
|
||||
RequiredCell :: struct {
|
||||
case_id: string
|
||||
phase: string
|
||||
metric: string
|
||||
unit: string
|
||||
}
|
||||
|
||||
ClosureItem :: struct {
|
||||
path: string
|
||||
digest: string
|
||||
}
|
||||
|
||||
CollectJob :: struct {
|
||||
receipt_id: string
|
||||
case_id: string
|
||||
engine: string
|
||||
selector: string
|
||||
phase: string
|
||||
metric: string
|
||||
unit: string
|
||||
command: Vec(string)
|
||||
verification: Vec(string)
|
||||
closure: Vec(ClosureItem)
|
||||
workload: string
|
||||
input_path: string
|
||||
input_checksum: string
|
||||
semantic_settings: string
|
||||
correctness_expected: string
|
||||
iterations: s64
|
||||
repeats: s64
|
||||
warmups: s64
|
||||
timeout_ms: s64
|
||||
cache_policy: string
|
||||
cache_directory: string
|
||||
environment: Vec(string)
|
||||
artifact: string
|
||||
rss_tool: string
|
||||
}
|
||||
|
||||
CollectPlan :: struct {
|
||||
campaign: string
|
||||
physical_host: string
|
||||
hostname: string
|
||||
cpu: string
|
||||
os: string
|
||||
working_directory: string
|
||||
collector_work: string
|
||||
required: Vec(RequiredCell)
|
||||
jobs: Vec(CollectJob)
|
||||
}
|
||||
|
||||
Observation :: struct {
|
||||
sample: float64
|
||||
correctness: string
|
||||
valid: bool
|
||||
}
|
||||
|
||||
Cat :: (left: string, right: string) -> string {
|
||||
parts: [2]string = .[left, right]
|
||||
return TextDetach(TextJoin(parts[:], ""))
|
||||
}
|
||||
|
||||
SafeText :: (value: string, limit: s64 = MAX_TEXT) -> bool {
|
||||
if value.count == 0 || value.count > limit { return false }
|
||||
for byte: value { if byte < 32 || byte == 127 { return false } }
|
||||
return true
|
||||
}
|
||||
|
||||
SafeName :: (value: string) -> bool {
|
||||
if !SafeText(value, 256) { return false }
|
||||
for byte: value {
|
||||
if !(byte >= #char "a" && byte <= #char "z") &&
|
||||
!(byte >= #char "A" && byte <= #char "Z") &&
|
||||
!(byte >= #char "0" && byte <= #char "9") &&
|
||||
byte != #char "-" && byte != #char "_" && byte != #char "." { return false }
|
||||
}
|
||||
return value != "." && value != ".."
|
||||
}
|
||||
|
||||
CleanAbsolutePath :: (value: string) -> bool {
|
||||
if value.count < 2 || value[0] != #char "/" || value[value.count - 1] == #char "/" ||
|
||||
TextContains(value, "//") || TextContains(value, "/../") ||
|
||||
TextContains(value, "/./") || TextHasSuffix(value, "/..") ||
|
||||
TextHasSuffix(value, "/.") { return false }
|
||||
return true
|
||||
}
|
||||
|
||||
FieldInto :: (document: *JsonDocument, object: s32, name: string,
|
||||
output: *string, limit: s64 = MAX_TEXT) -> bool {
|
||||
node := JsonMember(document, object, name)
|
||||
if JsonKindOf(document, node) != .String { return false }
|
||||
value := TextDetach(JsonString(document, node))
|
||||
if !SafeText(value, limit) { return false }
|
||||
<<output = value
|
||||
return true
|
||||
}
|
||||
|
||||
IntegerField :: (document: *JsonDocument, object: s32, name: string,
|
||||
minimum: s64, maximum: s64, output: *s64) -> bool {
|
||||
value, valid := JsonInteger(document, JsonMember(document, object, name))
|
||||
if !valid || value < minimum || value > maximum { return false }
|
||||
<<output = value
|
||||
return true
|
||||
}
|
||||
|
||||
StringArray :: (document: *JsonDocument, object: s32, name: string,
|
||||
output: *Vec(string), maximum: s32, empty_ok: bool = true) -> bool {
|
||||
node := JsonMember(document, object, name)
|
||||
if JsonKindOf(document, node) != .Array || JsonCount(document, node) > maximum ||
|
||||
(!empty_ok && JsonCount(document, node) == 0) { return false }
|
||||
for index: cast(s32)0..JsonCount(document, node) - 1 {
|
||||
item := JsonElement(document, node, index)
|
||||
if JsonKindOf(document, item) != .String { return false }
|
||||
value := TextDetach(JsonString(document, item))
|
||||
if !SafeText(value, 4095) { return false }
|
||||
VecPush(<<output, value)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
ValidDigest :: (value: string) -> bool {
|
||||
if value.count != 71 || value[0:7] != "sha256:" { return false }
|
||||
for byte: value[7:] {
|
||||
if !(byte >= #char "0" && byte <= #char "9") &&
|
||||
!(byte >= #char "a" && byte <= #char "f") { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
ParseRequired :: (document: *JsonDocument, node: s32, output: *RequiredCell) -> bool {
|
||||
return JsonKindOf(document, node) == .Object && JsonCount(document, node) == 4 &&
|
||||
FieldInto(document, node, "case", *output.case_id, 256) &&
|
||||
FieldInto(document, node, "phase", *output.phase, 128) &&
|
||||
FieldInto(document, node, "metric", *output.metric, 128) &&
|
||||
FieldInto(document, node, "unit", *output.unit, 128)
|
||||
}
|
||||
|
||||
ParseClosure :: (document: *JsonDocument, object: s32, output: *Vec(ClosureItem)) -> bool {
|
||||
node := JsonMember(document, object, "runtime_closure")
|
||||
if JsonKindOf(document, node) != .Array || JsonCount(document, node) == 0 ||
|
||||
JsonCount(document, node) > 32 { return false }
|
||||
for index: cast(s32)0..JsonCount(document, node) - 1 {
|
||||
item_node := JsonElement(document, node, index)
|
||||
item: ClosureItem
|
||||
if JsonKindOf(document, item_node) != .Object || JsonCount(document, item_node) != 2 ||
|
||||
!FieldInto(document, item_node, "path", *item.path, 4095) ||
|
||||
!FieldInto(document, item_node, "sha256", *item.digest, 71) ||
|
||||
!ValidDigest(item.digest) || !CleanAbsolutePath(item.path) { return false }
|
||||
for other_index: cast(s64)0..(<<output).count - 1 {
|
||||
if (<<output)[other_index].path == item.path { return false }
|
||||
}
|
||||
VecPush(<<output, item)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
Contains :: (values: []string, wanted: string) -> bool {
|
||||
for value: values { if value == wanted { return true } }
|
||||
return false
|
||||
}
|
||||
|
||||
ContainsPair :: (values: []string, first: string, second: string) -> bool {
|
||||
for index: cast(s64)0..values.count - 2 {
|
||||
if values[index] == first && values[index + 1] == second { return true }
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
EnvironmentValue :: (values: []string, name: string) -> string {
|
||||
prefix := Cat(name, "=")
|
||||
for value: values {
|
||||
if TextHasPrefix(value, prefix) { return value[prefix.count:] }
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
ClosureContains :: (job: *CollectJob, path: string) -> bool {
|
||||
for item: job.closure { if item.path == path { return true } }
|
||||
return false
|
||||
}
|
||||
|
||||
ValidCellShape :: (phase: string, metric: string, unit: string) -> bool {
|
||||
if phase == "coldcompile" || phase == "coldstartup" || phase == "warmstartup" {
|
||||
return metric == "duration" && unit == "ns"
|
||||
}
|
||||
if phase == "warmthroughput" { return metric == "throughput" && unit == "ops/s" }
|
||||
if phase == "memory" { return metric == "memory" && unit == "KiB" }
|
||||
if phase == "code-size" { return metric == "code-size" && unit == "bytes" }
|
||||
if phase == "bundle-size" { return metric == "bundle-size" && unit == "bytes" }
|
||||
return false
|
||||
}
|
||||
|
||||
ValidSelector :: (job: *CollectJob) -> bool {
|
||||
if job.engine == "new-native" {
|
||||
print("assembly collector: new-native ZX is unavailable; keep that required cell missing\n")
|
||||
return false
|
||||
}
|
||||
expected := ""
|
||||
if job.engine == "old-portable-vm" { expected = "zx-vm" }
|
||||
else if job.engine == "new-portable" { expected = "lowered-portable" }
|
||||
else if job.engine == "old-c-tinycc-native" {
|
||||
print("assembly collector: old C/TinyCC native has no native-only CLI proof; keep that cell missing\n")
|
||||
return false
|
||||
}
|
||||
else if job.engine == "direct-aot" { expected = "direct-aot" }
|
||||
else if job.engine == "control-c" || job.engine == "control-go" ||
|
||||
job.engine == "control-wasm" { expected = job.engine }
|
||||
else {
|
||||
print("assembly collector: unsupported engine %\n", job.engine)
|
||||
return false
|
||||
}
|
||||
if job.selector != expected {
|
||||
print("assembly collector: engine % requires selector %, not %\n",
|
||||
job.engine, expected, job.selector)
|
||||
return false
|
||||
}
|
||||
if job.command.count == 0 || job.command[0].count == 0 ||
|
||||
job.command[0][0] != #char "/" || !ClosureContains(job, job.command[0]) { return false }
|
||||
if job.verification.count > 0 &&
|
||||
(job.verification[0][0] != #char "/" || !ClosureContains(job, job.verification[0])) {
|
||||
return false
|
||||
}
|
||||
if job.rss_tool != "-" &&
|
||||
(job.rss_tool[0] != #char "/" || !ClosureContains(job, job.rss_tool)) { return false }
|
||||
selection := job.command[:]
|
||||
if (job.phase == "coldcompile" || job.phase == "code-size" ||
|
||||
job.phase == "bundle-size") && job.verification.count > 0 {
|
||||
selection = job.verification[:]
|
||||
}
|
||||
flags := selection[1:]
|
||||
if job.selector == "zx-vm" {
|
||||
return flags.count == 3 && flags[0] == "run" && flags[1] == "--vm" &&
|
||||
flags[2] == job.input_path
|
||||
}
|
||||
if job.selector == "lowered-portable" {
|
||||
expected_input := ifx job.phase == "coldcompile" ||
|
||||
job.phase == "bundle-size" then job.artifact else job.input_path
|
||||
return PathName(selection[0]) == "zi2zx" && flags.count == 2 && flags[0] == "run" &&
|
||||
flags[1] == expected_input
|
||||
}
|
||||
if job.selector == "direct-aot" {
|
||||
return job.artifact != "-" && selection[0] == job.artifact
|
||||
}
|
||||
if job.selector == "control-c" || job.selector == "control-go" {
|
||||
return job.artifact != "-" && selection[0] == job.artifact
|
||||
}
|
||||
if job.selector == "control-wasm" {
|
||||
return job.artifact != "-" && Contains(flags, job.artifact)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
PathInside :: (parent: string, child: string) -> bool {
|
||||
if !CleanAbsolutePath(parent) || !CleanAbsolutePath(child) { return false }
|
||||
prefix := Cat(parent, "/")
|
||||
return child != parent && TextHasPrefix(child, prefix)
|
||||
}
|
||||
|
||||
ValidateJob :: (plan: *CollectPlan, job: *CollectJob) -> bool {
|
||||
if !SafeName(job.receipt_id) || !ValidCellShape(job.phase, job.metric, job.unit) ||
|
||||
!ValidDigest(job.input_checksum) || !ValidDigest(job.correctness_expected) ||
|
||||
!TextContains(job.semantic_settings, "process=fresh-child-per-sample") ||
|
||||
job.command.count == 0 || job.repeats < 3 || job.repeats > MAX_REPEATS ||
|
||||
job.iterations < 1 || job.timeout_ms < 1 ||
|
||||
!CleanAbsolutePath(job.input_path) { return false }
|
||||
if job.phase == "warmstartup" || job.phase == "warmthroughput" {
|
||||
if job.warmups < 1 { return false }
|
||||
} else if job.warmups != 0 { return false }
|
||||
if job.phase == "warmthroughput" &&
|
||||
(job.verification.count == 0 ||
|
||||
!TextContains(job.semantic_settings, "timing=internal-kernel-ns")) { return false }
|
||||
private_cache := job.cache_policy == "private-cold-each-sample" ||
|
||||
job.cache_policy == "private-warm-across-samples"
|
||||
if private_cache {
|
||||
if job.cache_directory == "-" || !PathInside(plan.collector_work, job.cache_directory) {
|
||||
return false
|
||||
}
|
||||
} else if job.cache_policy != "immutable-artifact-no-engine-cache" ||
|
||||
job.cache_directory != "-" { return false }
|
||||
if job.phase == "coldcompile" || job.phase == "code-size" ||
|
||||
job.phase == "bundle-size" {
|
||||
if job.verification.count == 0 || job.artifact == "-" ||
|
||||
!PathInside(plan.collector_work, job.artifact) { return false }
|
||||
}
|
||||
if job.phase == "memory" && job.rss_tool == "-" { return false }
|
||||
if job.phase != "memory" && job.rss_tool != "-" { return false }
|
||||
return ValidSelector(job) && ToolchainIdentity(job) != ""
|
||||
}
|
||||
|
||||
ParseJob :: (document: *JsonDocument, node: s32, output: *CollectJob) -> bool {
|
||||
if JsonKindOf(document, node) != .Object || JsonCount(document, node) != 24 ||
|
||||
!FieldInto(document, node, "receipt_id", *output.receipt_id, 256) ||
|
||||
!FieldInto(document, node, "case", *output.case_id, 256) ||
|
||||
!FieldInto(document, node, "engine", *output.engine, 128) ||
|
||||
!FieldInto(document, node, "selector", *output.selector, 128) ||
|
||||
!FieldInto(document, node, "phase", *output.phase, 128) ||
|
||||
!FieldInto(document, node, "metric", *output.metric, 128) ||
|
||||
!FieldInto(document, node, "unit", *output.unit, 128) ||
|
||||
!StringArray(document, node, "command", *output.command, 64, false) ||
|
||||
!StringArray(document, node, "verification", *output.verification, 64) ||
|
||||
!ParseClosure(document, node, *output.closure) ||
|
||||
!FieldInto(document, node, "workload", *output.workload) ||
|
||||
!FieldInto(document, node, "input_path", *output.input_path, 4095) ||
|
||||
!FieldInto(document, node, "input_checksum", *output.input_checksum, 71) ||
|
||||
!FieldInto(document, node, "semantic_settings", *output.semantic_settings) ||
|
||||
!FieldInto(document, node, "correctness_expected", *output.correctness_expected, 71) ||
|
||||
!IntegerField(document, node, "iterations", 1, 9223372036854775807, *output.iterations) ||
|
||||
!IntegerField(document, node, "repeats", 3, MAX_REPEATS, *output.repeats) ||
|
||||
!IntegerField(document, node, "warmups", 0, MAX_REPEATS, *output.warmups) ||
|
||||
!IntegerField(document, node, "timeout_ms", 1, 86400000, *output.timeout_ms) ||
|
||||
!FieldInto(document, node, "cache_policy", *output.cache_policy, 128) ||
|
||||
!FieldInto(document, node, "cache_directory", *output.cache_directory, 4095) ||
|
||||
!StringArray(document, node, "environment", *output.environment, 64) ||
|
||||
!FieldInto(document, node, "artifact", *output.artifact, 4095) ||
|
||||
!FieldInto(document, node, "rss_tool", *output.rss_tool, 4095) { return false }
|
||||
return true
|
||||
}
|
||||
|
||||
ParsePlan :: (text: string, plan: *CollectPlan) -> bool {
|
||||
document: JsonDocument
|
||||
if !JsonRead(*document, text) || JsonKindOf(*document, document.root) != .Object ||
|
||||
JsonCount(*document, document.root) != 10 { return false }
|
||||
schema, schema_valid := JsonInteger(*document,
|
||||
JsonMember(*document, document.root, "schema_version"))
|
||||
if !schema_valid || schema != 1 ||
|
||||
!FieldInto(*document, document.root, "campaign", *plan.campaign, 256) ||
|
||||
!FieldInto(*document, document.root, "physical_host", *plan.physical_host, 256) ||
|
||||
!FieldInto(*document, document.root, "hostname", *plan.hostname, 256) ||
|
||||
!FieldInto(*document, document.root, "cpu", *plan.cpu) ||
|
||||
!FieldInto(*document, document.root, "os", *plan.os) ||
|
||||
!FieldInto(*document, document.root, "working_directory", *plan.working_directory, 4095) ||
|
||||
!FieldInto(*document, document.root, "collector_work", *plan.collector_work, 4095) {
|
||||
return false
|
||||
}
|
||||
required := JsonMember(*document, document.root, "required_cells")
|
||||
jobs := JsonMember(*document, document.root, "jobs")
|
||||
if JsonKindOf(*document, required) != .Array || JsonCount(*document, required) == 0 ||
|
||||
JsonCount(*document, required) > MAX_REQUIRED_CELLS ||
|
||||
JsonKindOf(*document, jobs) != .Array || JsonCount(*document, jobs) == 0 ||
|
||||
JsonCount(*document, jobs) > MAX_JOBS { return false }
|
||||
for index: cast(s32)0..JsonCount(*document, required) - 1 {
|
||||
cell: RequiredCell
|
||||
if !ParseRequired(*document, JsonElement(*document, required, index), *cell) {
|
||||
return false
|
||||
}
|
||||
VecPush(plan.required, cell)
|
||||
}
|
||||
total_samples: s64
|
||||
for index: cast(s32)0..JsonCount(*document, jobs) - 1 {
|
||||
job: CollectJob
|
||||
if !ParseJob(*document, JsonElement(*document, jobs, index), *job) { return false }
|
||||
total_samples += job.repeats
|
||||
if total_samples > MAX_TOTAL_SAMPLES { return false }
|
||||
VecPush(plan.jobs, job)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
ValidatePlan :: (plan: *CollectPlan) -> bool {
|
||||
if plan.physical_host != "alpha" || !TextHasPrefix(plan.hostname, "alpha") ||
|
||||
!CleanAbsolutePath(plan.working_directory) ||
|
||||
!CleanAbsolutePath(plan.collector_work) ||
|
||||
!PathInside(plan.working_directory, plan.collector_work) { return false }
|
||||
for index: cast(s64)0..plan.required.count - 1 {
|
||||
if !ValidCellShape(plan.required[index].phase, plan.required[index].metric,
|
||||
plan.required[index].unit) { return false }
|
||||
for other: index + 1..plan.required.count - 1 {
|
||||
if plan.required[index].case_id == plan.required[other].case_id &&
|
||||
plan.required[index].phase == plan.required[other].phase &&
|
||||
plan.required[index].metric == plan.required[other].metric &&
|
||||
plan.required[index].unit == plan.required[other].unit { return false }
|
||||
}
|
||||
}
|
||||
for index: cast(s64)0..plan.jobs.count - 1 {
|
||||
if !ValidateJob(plan, *plan.jobs[index]) { return false }
|
||||
for other: index + 1..plan.jobs.count - 1 {
|
||||
if plan.jobs[index].receipt_id == plan.jobs[other].receipt_id { return false }
|
||||
if plan.jobs[index].case_id == plan.jobs[other].case_id &&
|
||||
plan.jobs[index].phase == plan.jobs[other].phase &&
|
||||
plan.jobs[index].metric == plan.jobs[other].metric &&
|
||||
plan.jobs[index].engine == plan.jobs[other].engine { return false }
|
||||
if plan.jobs[index].case_id == plan.jobs[other].case_id &&
|
||||
plan.jobs[index].phase == plan.jobs[other].phase &&
|
||||
plan.jobs[index].metric == plan.jobs[other].metric &&
|
||||
(plan.jobs[index].workload != plan.jobs[other].workload ||
|
||||
plan.jobs[index].input_checksum != plan.jobs[other].input_checksum ||
|
||||
plan.jobs[index].iterations != plan.jobs[other].iterations ||
|
||||
plan.jobs[index].unit != plan.jobs[other].unit ||
|
||||
plan.jobs[index].semantic_settings != plan.jobs[other].semantic_settings ||
|
||||
plan.jobs[index].correctness_expected != plan.jobs[other].correctness_expected) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
#scope_export
|
||||
ValidatePlanText :: (text: string) -> bool {
|
||||
plan: CollectPlan
|
||||
return ParsePlan(text, *plan) && ValidatePlan(*plan)
|
||||
}
|
||||
|
||||
#scope_file
|
||||
Capture :: (arguments: []string) -> (text: string, code: s32) {
|
||||
options: ProcessOptions = .{.arguments = arguments, .capture_output = true}
|
||||
run: ProcessRun
|
||||
if !RunProcess(options, *run) { return "", 127 }
|
||||
return TextDetach(BuilderFinish(run.output)), run.code
|
||||
}
|
||||
|
||||
HashFile :: (path: string) -> string {
|
||||
arguments := string.["sha256sum", "--", path]
|
||||
output, code := Capture(arguments[:])
|
||||
if code != 0 || output.count < 64 { return "" }
|
||||
result := Cat("sha256:", output[0:64])
|
||||
return ifx ValidDigest(result) then result else ""
|
||||
}
|
||||
|
||||
CpuIdentity :: () -> string {
|
||||
arguments := string.["/usr/bin/lscpu"]
|
||||
output, code := Capture(arguments[:])
|
||||
if code != 0 { return "" }
|
||||
lines := TextLines(output)
|
||||
for line: lines {
|
||||
if TextHasPrefix(line, "Model name:") {
|
||||
return TextDetach(TextCopy(TextTrim(line[11:])))
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
VerifyPhysicalHost :: (plan: *CollectPlan) -> bool {
|
||||
host_command := string.["/usr/bin/hostname"]
|
||||
os_command := string.["/usr/bin/uname", "-srmo"]
|
||||
virt_command := string.["/usr/bin/systemd-detect-virt"]
|
||||
hostname, host_code := Capture(host_command[:])
|
||||
os, os_code := Capture(os_command[:])
|
||||
virtualization, virt_code := Capture(virt_command[:])
|
||||
actual_host := TextTrim(hostname)
|
||||
actual_os := TextTrim(os)
|
||||
actual_virt := TextTrim(virtualization)
|
||||
actual_cpu := CpuIdentity()
|
||||
if host_code != 0 || os_code != 0 || virt_code != 1 || actual_virt != "none" ||
|
||||
actual_host != plan.hostname || actual_cpu != plan.cpu || actual_os != plan.os {
|
||||
print("assembly collector: Alpha physical-host attestation failed; no commands were run\n")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
VerifyInputs :: (job: *CollectJob) -> bool {
|
||||
if HashFile(job.input_path) != job.input_checksum { return false }
|
||||
for item: job.closure {
|
||||
if HashFile(item.path) != item.digest { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
ResetPrivateCache :: (plan: *CollectPlan, job: *CollectJob) -> bool {
|
||||
if job.cache_directory == "-" { return true }
|
||||
if !PathInside(plan.collector_work, job.cache_directory) { return false }
|
||||
if PathStatus(job.cache_directory, false).kind != .Missing &&
|
||||
!RemoveTree(job.cache_directory) { return false }
|
||||
return CreateDirectories(job.cache_directory)
|
||||
}
|
||||
|
||||
CommandOutputPath :: (plan: *CollectPlan, job: *CollectJob, label: string) -> string {
|
||||
prefix := Cat(plan.collector_work, Cat("/", Cat(job.receipt_id, Cat("-", label))))
|
||||
return Cat(prefix, ".stdout")
|
||||
}
|
||||
|
||||
RunCommand :: (plan: *CollectPlan, job: *CollectJob, arguments: []string,
|
||||
label: string, measured: bool) -> (elapsed: s64, output_digest: string, valid: bool) {
|
||||
stdout_path := CommandOutputPath(plan, job, label)
|
||||
prefix := stdout_path[0:stdout_path.count - 7]
|
||||
stderr_path := Cat(prefix, ".stderr")
|
||||
environment: Vec(string)
|
||||
for value: job.environment { VecPush(environment, value) }
|
||||
removals := string.["DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY",
|
||||
"DBUS_SESSION_BUS_ADDRESS", "GDK_DISPLAY"]
|
||||
for value: removals { VecPush(environment, value) }
|
||||
VecPush(environment, "HARMONY_DESKTOP_RECOVERY=0")
|
||||
options: ProcessOptions = .{.arguments = arguments, .directory = plan.working_directory,
|
||||
.environment = environment[:], .output_path = stdout_path,
|
||||
.error_path = stderr_path, .new_session = true}
|
||||
run: ProcessRun
|
||||
started := MonotonicNanoseconds()
|
||||
if started < 0 || !StartProcess(options, *run) { return 0, "", false }
|
||||
deadline := MonotonicMilliseconds() + job.timeout_ms
|
||||
while !PollProcess(*run) {
|
||||
if MonotonicMilliseconds() >= deadline {
|
||||
unused SignalProcess(*run, 15, true)
|
||||
unused SleepMilliseconds(100)
|
||||
if !PollProcess(*run) { unused SignalProcess(*run, 9, true) }
|
||||
unused WaitProcess(*run)
|
||||
print("assembly collector: command timed out for %\n", job.receipt_id)
|
||||
return 0, "", false
|
||||
}
|
||||
unused SleepMilliseconds(2)
|
||||
}
|
||||
finished := MonotonicNanoseconds()
|
||||
if run.code != 0 || finished <= started { return 0, "", false }
|
||||
digest := HashFile(stdout_path)
|
||||
return ifx measured then finished - started else cast(s64)1, digest, digest != ""
|
||||
}
|
||||
|
||||
RunVerification :: (plan: *CollectPlan, job: *CollectJob, fallback: string,
|
||||
label: string) -> (identity: string, valid: bool) {
|
||||
if job.verification.count == 0 { return fallback, fallback == job.correctness_expected }
|
||||
unused_elapsed, identity, ok := RunCommand(plan, job, job.verification[:], label, false)
|
||||
return identity, ok && identity == job.correctness_expected
|
||||
}
|
||||
|
||||
MeasureOnce :: (plan: *CollectPlan, job: *CollectJob, index: s64,
|
||||
warmup: bool = false) -> Observation {
|
||||
result: Observation
|
||||
suffix_buffer: [32]u8
|
||||
suffix := TextDetach(TextCopy(FormatInteger(index, suffix_buffer[:])))
|
||||
label := Cat(ifx warmup then "warmup-" else "sample-", suffix)
|
||||
if !warmup && (job.phase == "coldcompile" || job.phase == "code-size" ||
|
||||
job.phase == "bundle-size") {
|
||||
info := PathStatus(job.artifact, false)
|
||||
if info.kind != .Missing && (info.kind != .File || !RemoveFile(job.artifact)) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
command: Vec(string)
|
||||
rss_path := ""
|
||||
if job.phase == "memory" {
|
||||
rss_path = Cat(plan.collector_work, Cat("/", Cat(job.receipt_id, Cat("-rss-", suffix))))
|
||||
VecPush(command, job.rss_tool)
|
||||
VecPush(command, "-f")
|
||||
VecPush(command, "%M")
|
||||
VecPush(command, "-o")
|
||||
VecPush(command, rss_path)
|
||||
VecPush(command, "--")
|
||||
for value: job.command { VecPush(command, value) }
|
||||
} else {
|
||||
for value: job.command { VecPush(command, value) }
|
||||
}
|
||||
elapsed, command_identity, ok := RunCommand(plan, job, command[:], label, true)
|
||||
if !ok { return result }
|
||||
identity, correct := RunVerification(plan, job, command_identity, Cat(label, "-verify"))
|
||||
if !correct { return result }
|
||||
result.correctness = identity
|
||||
if warmup { result.sample = 1.0; result.valid = true; return result }
|
||||
if job.metric == "duration" { result.sample = cast(float64)elapsed }
|
||||
else if job.metric == "throughput" {
|
||||
text, readable := ReadEntireFile(CommandOutputPath(plan, job, label))
|
||||
timing := ifx readable then TextTrim(text) else ""
|
||||
kernel_ns, count := IntegerPrefix(timing)
|
||||
if count != timing.count || kernel_ns <= 0 { return .{} }
|
||||
result.sample = cast(float64)job.iterations * 1000000000.0 /
|
||||
cast(float64)kernel_ns
|
||||
} else if job.metric == "memory" {
|
||||
text, readable := ReadEntireFile(rss_path)
|
||||
value, count := IntegerPrefix(ifx readable then TextTrim(text) else "")
|
||||
if count == 0 || value <= 0 { return .{} }
|
||||
result.sample = cast(float64)value
|
||||
} else {
|
||||
info := PathStatus(job.artifact)
|
||||
if info.kind != .File || info.size <= 0 { return .{} }
|
||||
result.sample = cast(float64)info.size
|
||||
}
|
||||
result.valid = result.sample > 0.0 && Finite64(result.sample)
|
||||
return result
|
||||
}
|
||||
|
||||
ToolchainIdentity :: (job: *CollectJob) -> string {
|
||||
output: Vec(u8)
|
||||
unused BuilderAppend(output, "selector=")
|
||||
unused BuilderAppend(output, job.selector)
|
||||
unused BuilderAppend(output, ";command=")
|
||||
unused BuilderAppend(output, job.command[0])
|
||||
unused BuilderAppend(output, ";cache=")
|
||||
unused BuilderAppend(output, job.cache_policy)
|
||||
unused BuilderAppend(output, "@")
|
||||
unused BuilderAppend(output, job.cache_directory)
|
||||
unused BuilderAppend(output, ";process=fresh-child-per-sample")
|
||||
if job.verification.count > 0 {
|
||||
unused BuilderAppend(output, ";verify=")
|
||||
for index: cast(s64)0..job.verification.count - 1 {
|
||||
if index > 0 { unused BuilderAppend(output, ",") }
|
||||
unused BuilderAppend(output, job.verification[index])
|
||||
}
|
||||
}
|
||||
if job.environment.count > 0 {
|
||||
unused BuilderAppend(output, ";environment=")
|
||||
for index: cast(s64)0..job.environment.count - 1 {
|
||||
if index > 0 { unused BuilderAppend(output, ",") }
|
||||
unused BuilderAppend(output, job.environment[index])
|
||||
}
|
||||
}
|
||||
unused BuilderAppend(output,
|
||||
";collector-environment=DISPLAY-,WAYLAND_DISPLAY-,XAUTHORITY-,DBUS_SESSION_BUS_ADDRESS-,GDK_DISPLAY-,HARMONY_DESKTOP_RECOVERY=0")
|
||||
unused BuilderAppend(output, ";closure=")
|
||||
for index: cast(s64)0..job.closure.count - 1 {
|
||||
if index > 0 { unused BuilderAppend(output, ",") }
|
||||
unused BuilderAppend(output, job.closure[index].path)
|
||||
unused BuilderAppend(output, "@")
|
||||
unused BuilderAppend(output, job.closure[index].digest)
|
||||
}
|
||||
result := TextDetach(BuilderFinish(output))
|
||||
return ifx SafeText(result) then result else ""
|
||||
}
|
||||
|
||||
PutText :: (document: *JsonDocument, object: s32, name: string, value: string) {
|
||||
JsonSet(document, object, name, JsonNewStringCopy(document, value))
|
||||
}
|
||||
|
||||
AppendRequired :: (document: *JsonDocument, array: s32, cell: *RequiredCell) {
|
||||
object := JsonNewObject(document)
|
||||
PutText(document, object, "case", cell.case_id)
|
||||
PutText(document, object, "phase", cell.phase)
|
||||
PutText(document, object, "metric", cell.metric)
|
||||
PutText(document, object, "unit", cell.unit)
|
||||
JsonAppend(document, array, object)
|
||||
}
|
||||
|
||||
AppendReceipt :: (document: *JsonDocument, array: s32, plan: *CollectPlan,
|
||||
job: *CollectJob, samples: []float64, correctness: string) -> bool {
|
||||
toolchain := ToolchainIdentity(job)
|
||||
if toolchain == "" { return false }
|
||||
object := JsonNewObject(document)
|
||||
PutText(document, object, "receipt_id", job.receipt_id)
|
||||
PutText(document, object, "case", job.case_id)
|
||||
PutText(document, object, "physical_host", plan.physical_host)
|
||||
PutText(document, object, "host_mode", "physical")
|
||||
PutText(document, object, "vm", "none")
|
||||
PutText(document, object, "cpu", plan.cpu)
|
||||
PutText(document, object, "os", plan.os)
|
||||
PutText(document, object, "toolchain", toolchain)
|
||||
flags := JsonNewArray(document)
|
||||
for index: cast(s64)1..job.command.count - 1 {
|
||||
JsonAppend(document, flags, JsonNewStringCopy(document, job.command[index]))
|
||||
}
|
||||
JsonSet(document, object, "flags", flags)
|
||||
PutText(document, object, "workload", job.workload)
|
||||
PutText(document, object, "input_checksum", job.input_checksum)
|
||||
PutText(document, object, "engine", job.engine)
|
||||
PutText(document, object, "phase", job.phase)
|
||||
PutText(document, object, "metric", job.metric)
|
||||
PutText(document, object, "unit", job.unit)
|
||||
PutText(document, object, "semantic_settings", job.semantic_settings)
|
||||
PutText(document, object, "correctness_expected", job.correctness_expected)
|
||||
PutText(document, object, "correctness_actual", correctness)
|
||||
JsonSet(document, object, "iterations", JsonNewInteger(document, job.iterations))
|
||||
JsonSet(document, object, "repeats", JsonNewInteger(document, job.repeats))
|
||||
values := JsonNewArray(document)
|
||||
for sample: samples {
|
||||
JsonAppend(document, values, JsonNewNumber(document, Float64Repr(sample)))
|
||||
}
|
||||
JsonSet(document, object, "samples", values)
|
||||
JsonAppend(document, array, object)
|
||||
return true
|
||||
}
|
||||
|
||||
#scope_export
|
||||
ProcessCollection :: (input: string, output: string) -> bool {
|
||||
if input == output { return false }
|
||||
query := PathQuery(input)
|
||||
if !query.valid || query.info.kind != .File || query.info.size < 2 ||
|
||||
query.info.size > MAX_PLAN_BYTES { return false }
|
||||
text, readable := ReadEntireFile(input)
|
||||
if !readable || text.count != query.info.size { return false }
|
||||
plan: CollectPlan
|
||||
if !ParsePlan(text, *plan) || !ValidatePlan(*plan) {
|
||||
print("assembly collector: invalid collection plan\n")
|
||||
return false
|
||||
}
|
||||
// This guard precedes filesystem verification, cache reset, and every job.
|
||||
if !VerifyPhysicalHost(*plan) { return false }
|
||||
if !CreateDirectories(plan.collector_work) { return false }
|
||||
document: JsonDocument
|
||||
root := JsonNewObject(*document)
|
||||
JsonSet(*document, root, "schema_version", JsonNewInteger(*document, 1))
|
||||
PutText(*document, root, "campaign", plan.campaign)
|
||||
required := JsonNewArray(*document)
|
||||
for * cell: plan.required { AppendRequired(*document, required, cell) }
|
||||
JsonSet(*document, root, "required_cells", required)
|
||||
receipts := JsonNewArray(*document)
|
||||
for * job: plan.jobs {
|
||||
if !VerifyInputs(job) { return false }
|
||||
if job.cache_policy == "private-warm-across-samples" &&
|
||||
!ResetPrivateCache(*plan, job) { return false }
|
||||
for warmup: cast(s64)0..job.warmups - 1 {
|
||||
observation := MeasureOnce(*plan, job, warmup, true)
|
||||
if !observation.valid { return false }
|
||||
}
|
||||
samples: Vec(float64)
|
||||
correctness := ""
|
||||
for index: cast(s64)0..job.repeats - 1 {
|
||||
if job.cache_policy == "private-cold-each-sample" &&
|
||||
!ResetPrivateCache(*plan, job) { return false }
|
||||
observation := MeasureOnce(*plan, job, index)
|
||||
if !observation.valid || observation.correctness != job.correctness_expected {
|
||||
return false
|
||||
}
|
||||
correctness = observation.correctness
|
||||
VecPush(samples, observation.sample)
|
||||
}
|
||||
statistics := BenchmarkAnalyze(samples[:])
|
||||
if !statistics.valid || !VerifyInputs(job) ||
|
||||
!AppendReceipt(*document, receipts, *plan, job,
|
||||
samples[:], correctness) { return false }
|
||||
}
|
||||
JsonSet(*document, root, "receipts", receipts)
|
||||
result := JsonWrite(*document, root, JsonPythonStyle(2))
|
||||
return CreateDirectories(PathParent(output)) && ReplaceFile(output, result)
|
||||
}
|
||||
|
||||
#program_export
|
||||
main :: (argc: s32, argv: **u8) -> s32 {
|
||||
if argc == 3 && TextFromCString(argv[1]) == "--validate" {
|
||||
input := TextDetach(TextCopy(TextFromCString(argv[2])))
|
||||
query := PathQuery(input)
|
||||
text, readable := ReadEntireFile(input)
|
||||
if !query.valid || query.info.kind != .File || query.info.size < 2 ||
|
||||
query.info.size > MAX_PLAN_BYTES || !readable || text.count != query.info.size ||
|
||||
!ValidatePlanText(text) { return 1 }
|
||||
print("assembly collector: plan is valid; no commands were run\n")
|
||||
return 0
|
||||
}
|
||||
if argc != 3 {
|
||||
print("usage: assembly_collect.zi [--validate] PLAN.json [OUTPUT.json]\n")
|
||||
return 2
|
||||
}
|
||||
input := TextDetach(TextCopy(TextFromCString(argv[1])))
|
||||
output := TextDetach(TextCopy(TextFromCString(argv[2])))
|
||||
return ifx ProcessCollection(input, output) then 0 else 1
|
||||
}
|
||||
@@ -0,0 +1,590 @@
|
||||
#!/usr/bin/env ziran
|
||||
#import "benchmark_statistics"
|
||||
#import "std/byte_text_linux"
|
||||
#import "std/file"
|
||||
#import "std/file_tree_linux"
|
||||
#import "std/float_text"
|
||||
#import "std/json_document"
|
||||
#import "std/math"
|
||||
#import "std/number_text"
|
||||
#import "std/text_tools"
|
||||
using Vectors :: #import "std/vec"
|
||||
|
||||
#scope_file
|
||||
MAX_INPUT_BYTES :: 4194304;
|
||||
MAX_REQUIRED_CELLS :: 512;
|
||||
MAX_RECEIPTS :: 2048;
|
||||
MAX_SAMPLES_PER_RECEIPT :: 4096;
|
||||
MAX_TOTAL_SAMPLES :: 65536;
|
||||
MAX_TEXT :: 1024;
|
||||
|
||||
core_engines: [5]string = .[
|
||||
"old-portable-vm",
|
||||
"new-portable",
|
||||
"old-c-tinycc-native",
|
||||
"new-native",
|
||||
"direct-aot",
|
||||
];
|
||||
|
||||
RequiredCell :: struct {
|
||||
case_id: string
|
||||
phase: string
|
||||
metric: string
|
||||
unit: string
|
||||
}
|
||||
|
||||
Receipt :: struct {
|
||||
receipt_id: string
|
||||
case_id: string
|
||||
physical_host: string
|
||||
host_mode: string
|
||||
vm: string
|
||||
cpu: string
|
||||
os: string
|
||||
toolchain: string
|
||||
flags: Vec(string)
|
||||
workload: string
|
||||
input_checksum: string
|
||||
engine: string
|
||||
phase: string
|
||||
metric: string
|
||||
unit: string
|
||||
semantic_settings: string
|
||||
correctness_expected: string
|
||||
correctness_actual: string
|
||||
iterations: s64
|
||||
repeats: s64
|
||||
samples: Vec(float64)
|
||||
statistics: BenchmarkSampleStatistics
|
||||
}
|
||||
|
||||
Markdown :: struct {
|
||||
bytes: Vec(u8)
|
||||
valid: bool
|
||||
}
|
||||
|
||||
Cat :: (left: string, right: string) -> string {
|
||||
parts: [2]string = .[left, right]
|
||||
return TextDetach(TextJoin(parts[:], ""))
|
||||
}
|
||||
|
||||
Put :: (output: *Markdown, text: string) {
|
||||
if output.valid { output.valid = BuilderAppend(output.bytes, text) }
|
||||
}
|
||||
|
||||
SafeText :: (text: string, limit: s64 = MAX_TEXT) -> bool {
|
||||
if text.count == 0 || text.count > limit { return false }
|
||||
for byte: text { if byte < 32 || byte == 127 { return false } }
|
||||
return true
|
||||
}
|
||||
|
||||
FieldInto :: (document: *JsonDocument, object: s32, name: string,
|
||||
output: *string, limit: s64 = MAX_TEXT) -> bool {
|
||||
node := JsonMember(document, object, name)
|
||||
if JsonKindOf(document, node) != .String { return false }
|
||||
value := TextDetach(JsonString(document, node))
|
||||
if !SafeText(value, limit) { return false }
|
||||
<<output = value
|
||||
return true
|
||||
}
|
||||
|
||||
IntegerField :: (document: *JsonDocument, object: s32, name: string,
|
||||
minimum: s64, maximum: s64, output: *s64) -> bool {
|
||||
value, valid := JsonInteger(document, JsonMember(document, object, name))
|
||||
if !valid || value < minimum || value > maximum { return false }
|
||||
<<output = value
|
||||
return true
|
||||
}
|
||||
|
||||
ParseRequiredCell :: (document: *JsonDocument, node: s32,
|
||||
result: *RequiredCell) -> bool {
|
||||
return JsonKindOf(document, node) == .Object && JsonCount(document, node) == 4 &&
|
||||
FieldInto(document, node, "case", *result.case_id, 256) &&
|
||||
FieldInto(document, node, "phase", *result.phase, 128) &&
|
||||
FieldInto(document, node, "metric", *result.metric, 128) &&
|
||||
FieldInto(document, node, "unit", *result.unit, 128)
|
||||
}
|
||||
|
||||
ParseReceipt :: (document: *JsonDocument, node: s32, result: *Receipt) -> bool {
|
||||
if JsonKindOf(document, node) != .Object || JsonCount(document, node) != 21 {
|
||||
return false
|
||||
}
|
||||
if !FieldInto(document, node, "receipt_id", *result.receipt_id, 256) ||
|
||||
!FieldInto(document, node, "case", *result.case_id, 256) ||
|
||||
!FieldInto(document, node, "physical_host", *result.physical_host, 256) ||
|
||||
!FieldInto(document, node, "host_mode", *result.host_mode, 64) ||
|
||||
!FieldInto(document, node, "vm", *result.vm, 256) ||
|
||||
!FieldInto(document, node, "cpu", *result.cpu) ||
|
||||
!FieldInto(document, node, "os", *result.os) ||
|
||||
!FieldInto(document, node, "toolchain", *result.toolchain) ||
|
||||
!FieldInto(document, node, "workload", *result.workload) ||
|
||||
!FieldInto(document, node, "input_checksum", *result.input_checksum, 256) ||
|
||||
!FieldInto(document, node, "engine", *result.engine, 128) ||
|
||||
!FieldInto(document, node, "phase", *result.phase, 128) ||
|
||||
!FieldInto(document, node, "metric", *result.metric, 128) ||
|
||||
!FieldInto(document, node, "unit", *result.unit, 128) ||
|
||||
!FieldInto(document, node, "semantic_settings", *result.semantic_settings) ||
|
||||
!FieldInto(document, node, "correctness_expected", *result.correctness_expected) ||
|
||||
!FieldInto(document, node, "correctness_actual", *result.correctness_actual) ||
|
||||
!IntegerField(document, node, "iterations", 1, 9223372036854775807, *result.iterations) ||
|
||||
!IntegerField(document, node, "repeats", 3, MAX_SAMPLES_PER_RECEIPT, *result.repeats) {
|
||||
return false
|
||||
}
|
||||
flags := JsonMember(document, node, "flags")
|
||||
if JsonKindOf(document, flags) != .Array || JsonCount(document, flags) > 64 {
|
||||
return false
|
||||
}
|
||||
for index: cast(s32)0..JsonCount(document, flags) - 1 {
|
||||
flag_node := JsonElement(document, flags, index)
|
||||
if JsonKindOf(document, flag_node) != .String { return false }
|
||||
flag := TextDetach(JsonString(document, flag_node))
|
||||
if !SafeText(flag, 256) { return false }
|
||||
VecPush(result.flags, flag)
|
||||
}
|
||||
samples := JsonMember(document, node, "samples")
|
||||
if JsonKindOf(document, samples) != .Array ||
|
||||
JsonCount(document, samples) != result.repeats { return false }
|
||||
for index: cast(s32)0..JsonCount(document, samples) - 1 {
|
||||
sample_node := JsonElement(document, samples, index)
|
||||
if JsonKindOf(document, sample_node) != .Number { return false }
|
||||
value, valid := ParseFloat64(JsonNumberText(document, sample_node))
|
||||
if !valid || value <= 0.0 || !Finite64(value) { return false }
|
||||
VecPush(result.samples, value)
|
||||
}
|
||||
statistics := BenchmarkAnalyze(result.samples[:])
|
||||
result.statistics.valid = statistics.valid
|
||||
result.statistics.lower = statistics.lower
|
||||
result.statistics.upper = statistics.upper
|
||||
result.statistics.median = statistics.median
|
||||
VecSwap(result.statistics.excluded, statistics.excluded)
|
||||
VecSwap(result.statistics.included, statistics.included)
|
||||
return result.statistics.valid
|
||||
}
|
||||
|
||||
SameCell :: (left: *Receipt, right: *Receipt) -> bool {
|
||||
return left.case_id == right.case_id && left.phase == right.phase &&
|
||||
left.metric == right.metric
|
||||
}
|
||||
|
||||
CompatibilityProblem :: (left: *Receipt, right: *Receipt) -> string {
|
||||
if left.physical_host != right.physical_host { return "physical_host changed" }
|
||||
if left.host_mode != right.host_mode { return "host_mode changed" }
|
||||
if left.vm != right.vm { return "VM identity changed" }
|
||||
if left.cpu != right.cpu { return "CPU identity changed" }
|
||||
if left.os != right.os { return "OS identity changed" }
|
||||
if left.workload != right.workload { return "workload changed" }
|
||||
if left.input_checksum != right.input_checksum { return "workload input checksum changed" }
|
||||
if left.iterations != right.iterations { return "iteration count changed" }
|
||||
if left.unit != right.unit { return "measurement unit changed" }
|
||||
if left.semantic_settings != right.semantic_settings { return "semantic settings changed" }
|
||||
if left.correctness_expected != right.correctness_expected {
|
||||
return "expected correctness identity changed"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
ValidateCampaign :: (required: []RequiredCell, receipts: []Receipt) -> bool {
|
||||
for index: cast(s64)0..required.count - 1 {
|
||||
for other: index + 1..required.count - 1 {
|
||||
if required[index].case_id == required[other].case_id &&
|
||||
required[index].phase == required[other].phase &&
|
||||
required[index].metric == required[other].metric &&
|
||||
required[index].unit == required[other].unit {
|
||||
print("assembly comparison: duplicate required cell %/%/%\n",
|
||||
required[index].case_id, required[index].phase, required[index].metric)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
if receipts.count == 0 {
|
||||
print("assembly comparison: receipts must not be empty\n")
|
||||
return false
|
||||
}
|
||||
first := *receipts[0]
|
||||
for index: cast(s64)0..receipts.count - 1 {
|
||||
receipt := *receipts[index]
|
||||
if receipt.host_mode != "physical" || receipt.vm != "none" {
|
||||
print("assembly comparison: receipt % is not a direct physical-host measurement\n",
|
||||
receipt.receipt_id)
|
||||
return false
|
||||
}
|
||||
if receipt.correctness_expected != receipt.correctness_actual {
|
||||
print("assembly comparison: receipt % failed its correctness identity\n",
|
||||
receipt.receipt_id)
|
||||
return false
|
||||
}
|
||||
global_problem := CompatibilityProblem(first, receipt)
|
||||
if global_problem == "physical_host changed" || global_problem == "host_mode changed" ||
|
||||
global_problem == "VM identity changed" || global_problem == "CPU identity changed" ||
|
||||
global_problem == "OS identity changed" {
|
||||
print("assembly comparison: incompatible campaign receipt %: %\n",
|
||||
receipt.receipt_id, global_problem)
|
||||
return false
|
||||
}
|
||||
for other: index + 1..receipts.count - 1 {
|
||||
candidate := *receipts[other]
|
||||
if receipt.receipt_id == candidate.receipt_id {
|
||||
print("assembly comparison: duplicate receipt_id %\n", receipt.receipt_id)
|
||||
return false
|
||||
}
|
||||
if SameCell(receipt, candidate) && receipt.engine == candidate.engine {
|
||||
print("assembly comparison: duplicate engine cell %/%/%/%\n",
|
||||
receipt.case_id, receipt.phase, receipt.metric, receipt.engine)
|
||||
return false
|
||||
}
|
||||
if SameCell(receipt, candidate) {
|
||||
problem := CompatibilityProblem(receipt, candidate)
|
||||
if problem != "" {
|
||||
print("assembly comparison: incompatible receipts % and %: %\n",
|
||||
receipt.receipt_id, candidate.receipt_id, problem)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
MetricDirection :: (metric: string) -> s32 {
|
||||
if metric == "throughput" { return 1 }
|
||||
if metric == "duration" || metric == "memory" ||
|
||||
metric == "code-size" || metric == "bundle-size" { return -1 }
|
||||
return 0
|
||||
}
|
||||
|
||||
FindReceipt :: (receipts: []Receipt, cell: *RequiredCell, engine: string) -> s64 {
|
||||
for index: cast(s64)0..receipts.count - 1 {
|
||||
receipt := *receipts[index]
|
||||
if receipt.case_id == cell.case_id && receipt.phase == cell.phase &&
|
||||
receipt.metric == cell.metric && receipt.unit == cell.unit &&
|
||||
receipt.engine == engine { return index }
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
ContainsCell :: (cells: []RequiredCell, candidate: *RequiredCell) -> bool {
|
||||
for cell: cells {
|
||||
if cell.case_id == candidate.case_id && cell.phase == candidate.phase &&
|
||||
cell.metric == candidate.metric && cell.unit == candidate.unit { return true }
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
AllCells :: (required: []RequiredCell, receipts: []Receipt) -> Vec(RequiredCell) {
|
||||
cells: Vec(RequiredCell)
|
||||
for cell: required { VecPush(cells, cell) }
|
||||
for index: cast(s64)0..receipts.count - 1 {
|
||||
receipt := *receipts[index]
|
||||
cell: RequiredCell = .{.case_id = receipt.case_id, .phase = receipt.phase,
|
||||
.metric = receipt.metric, .unit = receipt.unit}
|
||||
if !ContainsCell(cells[:], *cell) { VecPush(cells, cell) }
|
||||
}
|
||||
return cells
|
||||
}
|
||||
|
||||
EscapeMarkdown :: (value: string) -> string {
|
||||
escaped: Vec(u8)
|
||||
for byte: value {
|
||||
entity := ""
|
||||
if byte == #char "&" { entity = "&" }
|
||||
else if byte == #char "<" { entity = "<" }
|
||||
else if byte == #char ">" { entity = ">" }
|
||||
else if byte == #char "|" { entity = "|" }
|
||||
else if byte == #char "`" { entity = "`" }
|
||||
else if byte == #char "\\" { entity = "\" }
|
||||
else if byte == #char "*" { entity = "*" }
|
||||
else if byte == #char "_" { entity = "_" }
|
||||
else if byte == #char "[" { entity = "[" }
|
||||
else if byte == #char "]" { entity = "]" }
|
||||
else if byte == #char "#" { entity = "#" }
|
||||
if entity != "" {
|
||||
if !BuilderAppend(escaped, entity) { return "" }
|
||||
} else if !VecPush(escaped, byte) { return "" }
|
||||
}
|
||||
return TextDetach(BuilderFinish(escaped))
|
||||
}
|
||||
|
||||
Decimal :: (value: float64, places: s32) -> string {
|
||||
buffer: [64]u8
|
||||
return TextDetach(TextCopy(FormatDecimal(value, places, buffer[:])))
|
||||
}
|
||||
|
||||
MedianText :: (receipt: *Receipt) -> string {
|
||||
return Cat(TextDetach(Float64Repr(receipt.statistics.median)),
|
||||
Cat(" ", EscapeMarkdown(receipt.unit)))
|
||||
}
|
||||
|
||||
IndicesText :: (indices: []s64) -> string {
|
||||
output: Vec(u8)
|
||||
unused BuilderAppend(output, "[")
|
||||
for index: cast(s64)0..indices.count - 1 {
|
||||
if index > 0 { unused BuilderAppend(output, ", ") }
|
||||
buffer: [32]u8
|
||||
unused BuilderAppend(output, FormatInteger(indices[index], buffer[:]))
|
||||
}
|
||||
unused BuilderAppend(output, "]")
|
||||
return TextDetach(BuilderFinish(output))
|
||||
}
|
||||
|
||||
SamplesText :: (samples: []float64) -> string {
|
||||
output: Vec(u8)
|
||||
unused BuilderAppend(output, "[")
|
||||
for index: cast(s64)0..samples.count - 1 {
|
||||
if index > 0 { unused BuilderAppend(output, ", ") }
|
||||
unused BuilderAppend(output, Float64Repr(samples[index]))
|
||||
}
|
||||
unused BuilderAppend(output, "]")
|
||||
return TextDetach(BuilderFinish(output))
|
||||
}
|
||||
|
||||
CellValue :: (receipts: []Receipt, cell: *RequiredCell, engine: string) -> string {
|
||||
index := FindReceipt(receipts, cell, engine)
|
||||
if index < 0 { return "missing" }
|
||||
return MedianText(*receipts[index])
|
||||
}
|
||||
|
||||
CountMissing :: (required: []RequiredCell, receipts: []Receipt) -> s64 {
|
||||
count: s64
|
||||
for cell: required {
|
||||
for engine: core_engines {
|
||||
if FindReceipt(receipts, *cell, engine) < 0 { count += 1 }
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
PairRow :: (output: *Markdown, receipts: []Receipt, cell: *RequiredCell,
|
||||
baseline: string, candidate: string, optional: bool = false) {
|
||||
base := FindReceipt(receipts, cell, baseline)
|
||||
next := FindReceipt(receipts, cell, candidate)
|
||||
if optional && next < 0 { return }
|
||||
Put(output, "| "); Put(output, EscapeMarkdown(cell.case_id)); Put(output, " | ")
|
||||
Put(output, EscapeMarkdown(cell.phase)); Put(output, " / ")
|
||||
Put(output, EscapeMarkdown(cell.metric)); Put(output, " | ")
|
||||
Put(output, baseline); Put(output, " → "); Put(output, candidate); Put(output, " | ")
|
||||
Put(output, ifx base >= 0 then MedianText(*receipts[base]) else "missing")
|
||||
Put(output, " | ")
|
||||
Put(output, ifx next >= 0 then MedianText(*receipts[next]) else "missing")
|
||||
Put(output, " | ")
|
||||
if base < 0 || next < 0 {
|
||||
Put(output, "not compared: missing receipt")
|
||||
} else {
|
||||
direction := MetricDirection(cell.metric)
|
||||
if direction == 0 {
|
||||
Put(output, "noncomparable: unknown metric direction")
|
||||
} else {
|
||||
baseline_value := receipts[base].statistics.median
|
||||
candidate_value := receipts[next].statistics.median
|
||||
ratio := ifx direction > 0 then candidate_value / baseline_value else baseline_value / candidate_value
|
||||
metric_ratio := candidate_value / baseline_value
|
||||
metric_change := (metric_ratio - 1.0) * 100.0
|
||||
if ratio <= 0.0 || metric_ratio <= 0.0 || !Finite64(ratio) ||
|
||||
!Finite64(metric_ratio) || !Finite64(metric_change) {
|
||||
Put(output, "noncomparable: derived ratio outside finite range")
|
||||
} else {
|
||||
Put(output, Decimal(ratio, 3)); Put(output, "x favorable factor; ")
|
||||
if ratio > 1.0 { Put(output, "improvement") }
|
||||
else if ratio < 1.0 { Put(output, "regression") }
|
||||
else { Put(output, "unchanged") }
|
||||
Put(output, "; candidate metric change ")
|
||||
if metric_change > 0.0 { Put(output, "+") }
|
||||
Put(output, Decimal(metric_change, 2)); Put(output, "%")
|
||||
}
|
||||
}
|
||||
}
|
||||
Put(output, " |\n")
|
||||
}
|
||||
|
||||
BuildReport :: (campaign: string, required: []RequiredCell,
|
||||
receipts: []Receipt) -> (text: string, valid: bool) {
|
||||
output: Markdown
|
||||
output.valid = true
|
||||
missing := CountMissing(required, receipts)
|
||||
Put(*output, "# ZX Assembly Performance Comparison\n\n")
|
||||
Put(*output, "Campaign: `"); Put(*output, EscapeMarkdown(campaign)); Put(*output, "`\n\n")
|
||||
Put(*output, "Status: ")
|
||||
if missing == 0 { Put(*output, "complete required comparison matrix") }
|
||||
else {
|
||||
Put(*output, "incomplete — ")
|
||||
buffer: [32]u8
|
||||
Put(*output, FormatInteger(missing, buffer[:]))
|
||||
Put(*output, " required engine/phase cells missing")
|
||||
}
|
||||
Put(*output, ".\n\n")
|
||||
Put(*output, "This report contains no aggregate or geometric mean. Each row keeps its absolute median, normalized favorable factor, candidate metric change, raw samples, and audited outlier indices. Favorable factors are candidate/baseline for throughput and baseline/candidate for duration, memory, code size, and bundle size; candidate metric change is always (candidate - baseline) / baseline.\n\n")
|
||||
Put(*output, "## Environment\n\n")
|
||||
first := *receipts[0]
|
||||
Put(*output, "- Physical host: `"); Put(*output, EscapeMarkdown(first.physical_host)); Put(*output, "` (`")
|
||||
Put(*output, EscapeMarkdown(first.host_mode)); Put(*output, "`, VM `")
|
||||
Put(*output, EscapeMarkdown(first.vm)); Put(*output, "`)\n")
|
||||
Put(*output, "- CPU: `"); Put(*output, EscapeMarkdown(first.cpu)); Put(*output, "`\n")
|
||||
Put(*output, "- OS: `"); Put(*output, EscapeMarkdown(first.os)); Put(*output, "`\n\n")
|
||||
|
||||
cells := AllCells(required, receipts)
|
||||
Put(*output, "## Absolute medians and required matrix\n\n")
|
||||
Put(*output, "| Case | Phase / metric | Unit | old portable VM | new portable | old C/TinyCC native | new native | direct AOT | C control | Go control | Wasm control |\n")
|
||||
Put(*output, "| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |\n")
|
||||
for cell: cells {
|
||||
Put(*output, "| "); Put(*output, EscapeMarkdown(cell.case_id)); Put(*output, " | ")
|
||||
Put(*output, EscapeMarkdown(cell.phase)); Put(*output, " / ")
|
||||
Put(*output, EscapeMarkdown(cell.metric)); Put(*output, " | ")
|
||||
Put(*output, EscapeMarkdown(cell.unit)); Put(*output, " | ")
|
||||
Put(*output, CellValue(receipts, *cell, "old-portable-vm")); Put(*output, " | ")
|
||||
Put(*output, CellValue(receipts, *cell, "new-portable")); Put(*output, " | ")
|
||||
Put(*output, CellValue(receipts, *cell, "old-c-tinycc-native")); Put(*output, " | ")
|
||||
Put(*output, CellValue(receipts, *cell, "new-native")); Put(*output, " | ")
|
||||
Put(*output, CellValue(receipts, *cell, "direct-aot")); Put(*output, " | ")
|
||||
Put(*output, CellValue(receipts, *cell, "control-c")); Put(*output, " | ")
|
||||
Put(*output, CellValue(receipts, *cell, "control-go")); Put(*output, " | ")
|
||||
Put(*output, CellValue(receipts, *cell, "control-wasm")); Put(*output, " |\n")
|
||||
}
|
||||
|
||||
Put(*output, "\n## Per-case comparisons\n\n")
|
||||
Put(*output, "| Case | Phase / metric | Comparison | Baseline median | Candidate median | Result |\n")
|
||||
Put(*output, "| --- | --- | --- | ---: | ---: | --- |\n")
|
||||
for cell: cells {
|
||||
PairRow(*output, receipts, *cell, "old-portable-vm", "new-portable")
|
||||
PairRow(*output, receipts, *cell, "old-c-tinycc-native", "new-native")
|
||||
PairRow(*output, receipts, *cell, "old-c-tinycc-native", "direct-aot")
|
||||
PairRow(*output, receipts, *cell, "old-portable-vm", "control-c", true)
|
||||
PairRow(*output, receipts, *cell, "old-portable-vm", "control-go", true)
|
||||
PairRow(*output, receipts, *cell, "old-portable-vm", "control-wasm", true)
|
||||
}
|
||||
|
||||
Put(*output, "\n## Missing required cells\n\n")
|
||||
if missing == 0 { Put(*output, "None.\n") }
|
||||
else {
|
||||
for cell: required {
|
||||
for engine: core_engines {
|
||||
if FindReceipt(receipts, *cell, engine) < 0 {
|
||||
Put(*output, "- `"); Put(*output, EscapeMarkdown(cell.case_id)); Put(*output, "` / `")
|
||||
Put(*output, EscapeMarkdown(cell.phase)); Put(*output, "` / `")
|
||||
Put(*output, EscapeMarkdown(cell.metric)); Put(*output, "` / `")
|
||||
Put(*output, EscapeMarkdown(cell.unit)); Put(*output, "`: missing `")
|
||||
Put(*output, engine); Put(*output, "`\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Put(*output, "\n## Raw receipt audit\n\n")
|
||||
Put(*output, "Outliers use the canonical symmetric 1.5×IQR fences with linearly interpolated inclusive quartiles. Indices below are zero-based positions in the unchanged raw sample array.\n\n")
|
||||
for receipt_index: cast(s64)0..receipts.count - 1 {
|
||||
receipt := *receipts[receipt_index]
|
||||
Put(*output, "### "); Put(*output, EscapeMarkdown(receipt.receipt_id)); Put(*output, "\n\n")
|
||||
Put(*output, "- Cell: `"); Put(*output, EscapeMarkdown(receipt.case_id)); Put(*output, "` / `")
|
||||
Put(*output, EscapeMarkdown(receipt.phase)); Put(*output, "` / `")
|
||||
Put(*output, EscapeMarkdown(receipt.metric)); Put(*output, "`; engine `")
|
||||
Put(*output, EscapeMarkdown(receipt.engine)); Put(*output, "`\n")
|
||||
Put(*output, "- Workload: `"); Put(*output, EscapeMarkdown(receipt.workload)); Put(*output, "`; input checksum `")
|
||||
Put(*output, EscapeMarkdown(receipt.input_checksum)); Put(*output, "`; iterations `")
|
||||
buffer: [32]u8
|
||||
Put(*output, FormatInteger(receipt.iterations, buffer[:]))
|
||||
Put(*output, "`; semantics `"); Put(*output, EscapeMarkdown(receipt.semantic_settings)); Put(*output, "`\n")
|
||||
Put(*output, "- Toolchain: `"); Put(*output, EscapeMarkdown(receipt.toolchain)); Put(*output, "`; flags: ")
|
||||
if receipt.flags.count == 0 { Put(*output, "(none)") }
|
||||
else {
|
||||
for index: cast(s64)0..receipt.flags.count - 1 {
|
||||
if index > 0 { Put(*output, ", ") }
|
||||
Put(*output, "`"); Put(*output, EscapeMarkdown(receipt.flags[index])); Put(*output, "`")
|
||||
}
|
||||
}
|
||||
Put(*output, "\n- Correctness identity: `"); Put(*output, EscapeMarkdown(receipt.correctness_expected))
|
||||
Put(*output, "` = `"); Put(*output, EscapeMarkdown(receipt.correctness_actual)); Put(*output, "`\n")
|
||||
Put(*output, "- Sample count: `"); Put(*output, FormatInteger(receipt.repeats, buffer[:]))
|
||||
Put(*output, "`; raw samples ("); Put(*output, EscapeMarkdown(receipt.unit)); Put(*output, "): `")
|
||||
Put(*output, SamplesText(receipt.samples[:])); Put(*output, "`\n")
|
||||
Put(*output, "- Excluded indices: `"); Put(*output, IndicesText(receipt.statistics.excluded[:]))
|
||||
Put(*output, "`; retained median: `"); Put(*output, MedianText(receipt)); Put(*output, "`\n\n")
|
||||
}
|
||||
if !output.valid { return "", false }
|
||||
return TextDetach(BuilderFinish(output.bytes)), true
|
||||
}
|
||||
|
||||
#scope_export
|
||||
ProcessComparison :: (input: string, output: string) -> bool {
|
||||
if input == output {
|
||||
print("assembly comparison: input and output paths must differ\n")
|
||||
return false
|
||||
}
|
||||
query := PathQuery(input)
|
||||
if !query.valid || query.info.kind != .File || query.info.size < 2 ||
|
||||
query.info.size > MAX_INPUT_BYTES {
|
||||
print("assembly comparison: input must be a 2-byte..4-MiB regular file\n")
|
||||
return false
|
||||
}
|
||||
text, readable := ReadEntireFile(input)
|
||||
if !readable || text.count != query.info.size {
|
||||
print("assembly comparison: input could not be read completely\n")
|
||||
return false
|
||||
}
|
||||
document: JsonDocument
|
||||
if !JsonRead(*document, text) || JsonKindOf(*document, document.root) != .Object ||
|
||||
JsonCount(*document, document.root) != 4 {
|
||||
print("assembly comparison: malformed root receipt document\n")
|
||||
return false
|
||||
}
|
||||
schema, schema_valid := JsonInteger(*document, JsonMember(*document, document.root, "schema_version"))
|
||||
campaign := ""
|
||||
if !schema_valid || schema != 1 ||
|
||||
!FieldInto(*document, document.root, "campaign", *campaign, 256) {
|
||||
print("assembly comparison: unsupported schema or invalid campaign\n")
|
||||
return false
|
||||
}
|
||||
required_node := JsonMember(*document, document.root, "required_cells")
|
||||
receipts_node := JsonMember(*document, document.root, "receipts")
|
||||
if JsonKindOf(*document, required_node) != .Array ||
|
||||
JsonCount(*document, required_node) == 0 ||
|
||||
JsonCount(*document, required_node) > MAX_REQUIRED_CELLS ||
|
||||
JsonKindOf(*document, receipts_node) != .Array ||
|
||||
JsonCount(*document, receipts_node) > MAX_RECEIPTS {
|
||||
print("assembly comparison: required_cells or receipts exceeds its bound\n")
|
||||
return false
|
||||
}
|
||||
required: Vec(RequiredCell)
|
||||
for index: cast(s32)0..JsonCount(*document, required_node) - 1 {
|
||||
cell: RequiredCell
|
||||
if !ParseRequiredCell(*document, JsonElement(*document, required_node, index), *cell) {
|
||||
print("assembly comparison: malformed required cell at index %\n", index)
|
||||
return false
|
||||
}
|
||||
VecPush(required, cell)
|
||||
}
|
||||
receipts: Vec(Receipt)
|
||||
total_samples: s64
|
||||
for index: cast(s32)0..JsonCount(*document, receipts_node) - 1 {
|
||||
receipt: Receipt
|
||||
if !ParseReceipt(*document, JsonElement(*document, receipts_node, index), *receipt) {
|
||||
print("assembly comparison: malformed receipt or invalid samples at index %\n", index)
|
||||
return false
|
||||
}
|
||||
total_samples += receipt.samples.count
|
||||
if total_samples > MAX_TOTAL_SAMPLES {
|
||||
print("assembly comparison: total raw sample bound exceeded\n")
|
||||
return false
|
||||
}
|
||||
VecPush(receipts, receipt)
|
||||
}
|
||||
if !ValidateCampaign(required[:], receipts[:]) { return false }
|
||||
report, valid := BuildReport(campaign, required[:], receipts[:])
|
||||
if !valid {
|
||||
print("assembly comparison: report construction failed\n")
|
||||
return false
|
||||
}
|
||||
if !CreateDirectories(PathParent(output)) || !ReplaceFile(output, report) {
|
||||
print("assembly comparison: atomic report replacement failed\n")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
#program_export
|
||||
main :: (argc: s32, argv: **u8) -> s32 {
|
||||
if argc != 3 {
|
||||
print("usage: assembly_compare.zi INPUT.json OUTPUT.md\n")
|
||||
return 2
|
||||
}
|
||||
input := TextDetach(TextCopy(TextFromCString(argv[1])))
|
||||
output := TextDetach(TextCopy(TextFromCString(argv[2])))
|
||||
return ifx ProcessComparison(input, output) then 0 else 1
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
// Read a valid executable with a synthetic binary asset, at the small and
|
||||
// 75 MB package sizes. Compile and run only on Alpha's physical host:
|
||||
// LDLIBS="$PWD/build/libziran.a" build-queue -- ziran build --target=c --exe --entry asset_digest:main --root bench --module-path cmd \
|
||||
// -o build/asset-digest bench/asset_digest.zi
|
||||
// build-queue -- build/asset-digest/asset_digest
|
||||
// Each JSON line retains all 11 read samples, with one untimed warmup.
|
||||
#import "std/timer_linux"
|
||||
using Bundle :: #import "compiler_bundle"
|
||||
using Link :: #import "compiler_exec_link"
|
||||
using Lir :: #import "compiler_lowered_ir"
|
||||
using Vectors :: #import "std/vec"
|
||||
|
||||
Measure :: (program: Lir.LirProgram, count: s64) -> bool {
|
||||
payload: Vec(u8)
|
||||
if !VecResize(payload, count) { return false }
|
||||
defer VecFree(payload)
|
||||
for index: 0..count - 1 { payload[index] = cast(u8)(index * 37 + 11) }
|
||||
assets: [1]Bundle.Asset = .{.{name = "data/payload.bin", data = TextView(payload[:])}}
|
||||
empty: []u8
|
||||
measured := Link.ZxExecWrite(program, assets[:], empty)
|
||||
encoded: Vec(u8)
|
||||
if measured.problem != .None || !VecResize(encoded, measured.size) ||
|
||||
Link.ZxExecWrite(program, assets[:], encoded[:]).problem != .None { return false }
|
||||
defer VecFree(encoded)
|
||||
decoded_assets: [1]Bundle.Asset
|
||||
layout := Bundle.ExecutableDecode(TextView(encoded[:]), decoded_assets[:])
|
||||
if layout.problem != .None { return false }
|
||||
identity: [32]u8
|
||||
samples: [11]s64
|
||||
for round: 0..11 {
|
||||
owner: Link.ZxExecOwner
|
||||
began := MonotonicNanoseconds()
|
||||
read := Link.ZxExecRead(*owner, TextView(encoded[:]), Lir.LirDefaultLimits())
|
||||
elapsed := MonotonicNanoseconds() - began
|
||||
if read.problem != .None || !owner.valid || owner.assets != 1 {
|
||||
Link.ZxExecReadFree(*owner)
|
||||
return false
|
||||
}
|
||||
if round == 0 { identity = owner.identity }
|
||||
else {
|
||||
for index: 0..31 {
|
||||
if identity[index] != owner.identity[index] { Link.ZxExecReadFree(*owner); return false }
|
||||
}
|
||||
samples[round - 1] = elapsed
|
||||
}
|
||||
Link.ZxExecReadFree(*owner)
|
||||
}
|
||||
print("{\"asset_bytes\":%,\"bundle_bytes\":%,\"identity\":[", count, measured.size)
|
||||
for index: 0..31 {
|
||||
if index > 0 { print(",") }
|
||||
print("%", identity[index])
|
||||
}
|
||||
print("],\"assets_identity\":[")
|
||||
for index: 0..31 {
|
||||
if index > 0 { print(",") }
|
||||
print("%", layout.assets_identity[index])
|
||||
}
|
||||
print("],\"content_identity\":[")
|
||||
for index: 0..31 {
|
||||
if index > 0 { print(",") }
|
||||
print("%", layout.content_identity[index])
|
||||
}
|
||||
print("],\"samples_ns\":[")
|
||||
for index: 0..10 {
|
||||
if index > 0 { print(",") }
|
||||
print("%", samples[index])
|
||||
}
|
||||
print("]}\n")
|
||||
return true
|
||||
}
|
||||
|
||||
main :: () -> s32 {
|
||||
types: [2]Lir.LirType = .{.{kind = .Void}, .{kind = .Integer, bits = 32, is_signed = true}}
|
||||
modules: [1]string = .{"asset-digest"}
|
||||
constants: [1]Lir.LirConstant = .{.{type = 1, bits = 42}}
|
||||
values: [1]s32 = .{1}
|
||||
returned: [1]s32 = .{0}
|
||||
instructions: [2]Lir.LirInstruction
|
||||
instructions[0] = .{op = .Constant, result = 0, symbol = 0, origin = -1}
|
||||
instructions[1] = .{op = .Return, result = -1, operands = returned[:], symbol = -1, origin = -1}
|
||||
blocks: [1]Lir.LirBlock = .{.{instructions = instructions[:]}}
|
||||
functions: [1]Lir.LirFunction = .{.{module = 0, name = "main", result = 1,
|
||||
values = values[:], blocks = blocks[:], entry = 0, origin = -1}}
|
||||
program := Lir.LirProgram.{version = Lir.LirVersion, modules = modules[:],
|
||||
types = types[:], constants = constants[:], functions = functions[:], entry = 0}
|
||||
if !Measure(program, 1000000) || !Measure(program, 75000000) { return 1 }
|
||||
return 0
|
||||
}
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
#!/usr/bin/env -S ziran run --target=c
|
||||
// The one entry point for Ziran's benchmarks. From the repository root:
|
||||
//
|
||||
// build/bin/ziran run --target=c bench/bench.zi -- list
|
||||
// build/bin/ziran run --target=c bench/bench.zi -- NAME [DRIVER ARGUMENTS]
|
||||
// build/bin/ziran run --target=c bench/bench.zi -- --local NAME [DRIVER ARGUMENTS]
|
||||
// build/bin/ziran run --target=c bench/bench.zi -- check
|
||||
//
|
||||
// Every benchmark gets the same environment: no display or desktop-session
|
||||
// variables, no ZIRAN_PROFILE, and ZIRAN_LEARN=off, so the learning corpus
|
||||
// never records while something is measured. A host benchmark measures only
|
||||
// on a physical host named by ZIRAN_BENCH_HOST (`alpha` by default); `--local`
|
||||
// skips that check for measurement-free modes such as `--validate` or
|
||||
// `--check`. A device benchmark measures on a phone, and a report reads saved
|
||||
// receipts, so neither checks the host. `check` verifies that every driver in
|
||||
// bench/ is registered here and that the shared environment applies.
|
||||
#import "std/byte_text_linux"
|
||||
#import "std/environment_linux"
|
||||
#import "std/file"
|
||||
#import "std/file_tree_linux"
|
||||
#import "std/process_run_linux"
|
||||
#import "std/text_tools"
|
||||
using Vectors :: #import "std/vec"
|
||||
|
||||
#scope_file
|
||||
libc_bench :: #system_library "libc";
|
||||
FlushAll :: (stream: *void) -> s32 #foreign libc_bench "fflush";
|
||||
|
||||
Runner :: enum u8 { Ziran :: 0; Python :: 1; Shell :: 2; }
|
||||
Place :: enum u8 { Host :: 0; Device :: 1; Report :: 2; }
|
||||
|
||||
Benchmark :: struct {
|
||||
name: string
|
||||
file: string
|
||||
runner: Runner
|
||||
place: Place
|
||||
summary: string
|
||||
module_path: string
|
||||
compiler_library: bool
|
||||
}
|
||||
|
||||
// A bare name removes the variable from the driver's environment.
|
||||
BENCH_ENVIRONMENT: [9]string = .["DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS",
|
||||
"SESSION_MANAGER", "XDG_SESSION_ID", "XDG_SESSION_TYPE", "ZIRAN_PROFILE", "ZIRAN_LEARN=off"];
|
||||
|
||||
// Files in bench/ that a registered benchmark builds or imports.
|
||||
SUPPORT_FILES: [15]string = .["bench.zi", "benchmark_statistics.zi", "standard_compile_entry.zi", "standard_cases.zi", "codec_kernels.py", "json_document.zi",
|
||||
"math_sqrt.zi", "native_cache_fixture.zi", "wasm_tier.zi", "c_teacher_assembly.zi", "c_teacher_profile.zi", "c_teacher_rules.zi", "rill_row.zi", "zx_i386_blocks.zi", "zx_aggregate_load.zi"];
|
||||
|
||||
Add :: (list: *Vec(Benchmark), name: string, file: string, runner: Runner, place: Place, summary: string,
|
||||
module_path: string = "", compiler_library: bool = false) {
|
||||
unused VecPush(list.*, Benchmark.{.name = name, .file = file, .runner = runner, .place = place, .summary = summary,
|
||||
.module_path = module_path, .compiler_library = compiler_library})
|
||||
}
|
||||
|
||||
Registry :: () -> Vec(Benchmark) {
|
||||
list: Vec(Benchmark)
|
||||
Add(*list, "android-execution", "bench/android_execution.py", .Python, .Device, "cross-built kernels on one Android device")
|
||||
Add(*list, "asset-digest", "bench/asset_digest.zi", .Ziran, .Host, "checked executable asset digest throughput", "cmd", true)
|
||||
Add(*list, "assembly", "bench/assembly.py", .Python, .Host, "assembly, portable fallback, C, Go and the ZX engine")
|
||||
Add(*list, "assembly-collect", "bench/assembly_collect.zi", .Ziran, .Host, "strict assembly comparison receipts")
|
||||
Add(*list, "assembly-compare", "bench/assembly_compare.zi", .Ziran, .Report, "compare collected assembly receipts")
|
||||
Add(*list, "body-eligibility", "bench/body_eligibility.py", .Python, .Host, "paired checking with output identity")
|
||||
Add(*list, "bundle-assets", "bench/bundle_assets.py", .Python, .Host, "checked resource loading with real bundles")
|
||||
Add(*list, "bundle-instances", "bench/bundle_instances.py", .Python, .Host, "bundle loading and fresh-instance costs")
|
||||
Add(*list, "compiler-build", "bench/compiler_build.zi", .Ziran, .Host, "full native compiler rebuild")
|
||||
Add(*list, "standard-compile", "bench/standard_compile.zi", .Ziran, .Host, "complete standard suite builds in C, Go, generated C, native ZX and Wasm")
|
||||
Add(*list, "standard-ab", "bench/standard_ab.zi", .Ziran, .Host, "shuffled C and in-process ZX native runners on the standard suite")
|
||||
Add(*list, "standard-profile", "bench/standard_profile.zi", .Ziran, .Host, "SIGPROF samples of an in-process standard runner by function")
|
||||
Add(*list, "c-teacher", "bench/c_teacher.zi", .Ziran, .Host, "generated C versus native assembly and SIGPROF")
|
||||
Add(*list, "c-teacher-tune", "bench/c_teacher_tuning.zi", .Ziran, .Host, "offline leaf policies against generated C")
|
||||
Add(*list, "compiler-kernels", "bench/compiler_kernel_benchmarks.sh", .Shell, .Host, "timed compiler and codec kernels")
|
||||
Add(*list, "compiler-scaling", "bench/compiler_scaling.py", .Python, .Host, "module graphs and generic specialization")
|
||||
Add(*list, "cpu-features", "bench/cpu_features.py", .Python, .Host, "CPU-selected assembly against fallbacks")
|
||||
Add(*list, "enum-values", "bench/enum_values.py", .Python, .Host, "enum-heavy checks and portable loading")
|
||||
Add(*list, "formatter-builds", "bench/formatter_builds.py", .Python, .Host, "complete builds of the formatter")
|
||||
Add(*list, "go-assembly", "bench/go_assembly.py", .Python, .Host, "Go assembly bridges against pure Go and C")
|
||||
Add(*list, "host-capabilities", "bench/host_capabilities.py", .Python, .Host, "host-capability enumeration and calls")
|
||||
Add(*list, "json-document", "bench/json_document.sh", .Shell, .Host, "direct JSON parser")
|
||||
Add(*list, "json-string-scan", "bench/json_string_scan.zi", .Ziran, .Host, "JSON string scanning")
|
||||
Add(*list, "json-text", "bench/json_text.py", .Python, .Host, "JSON and UTF-8 workloads on every target")
|
||||
Add(*list, "library-targets", "scripts/site_library_targets.py", .Python, .Host, "a library's workloads on the site targets")
|
||||
Add(*list, "math-sqrt", "bench/math_sqrt.sh", .Shell, .Host, "std/math square root")
|
||||
Add(*list, "native-builds", "bench/native_builds.py", .Python, .Host, "complete native builds against C and Go")
|
||||
Add(*list, "native-header-graphs", "bench/native_header_graphs.py", .Python, .Host, "native builds with a dense record ABI")
|
||||
Add(*list, "native-probe", "bench/native_probe.py", .Python, .Host, "native builds with interleaved probes")
|
||||
Add(*list, "native-resize-ab", "bench/native_resize_ab.py", .Python, .Host, "matched frozen native runtimes on scalar and vector kernels")
|
||||
Add(*list, "reachable-types", "bench/reachable_types.py", .Python, .Host, "qualified type-graph lookup")
|
||||
Add(*list, "rill-compact", "bench/rill_compact.zi", .Ziran, .Host, "checked row memory operations in compact and full-plan engines", "cmd")
|
||||
Add(*list, "record-calls", "bench/record_calls.py", .Python, .Host, "record values and calls across backends")
|
||||
Add(*list, "smoke", "bench/smoke.py", .Python, .Host, "cross-target smoke, startup included")
|
||||
Add(*list, "text-scan", "bench/text_scan.py", .Python, .Host, "UTF-8 scanning across backends")
|
||||
Add(*list, "type-exports", "bench/type_exports.py", .Python, .Host, "local and re-exported types")
|
||||
Add(*list, "vector-growth", "bench/vector_growth.py", .Python, .Host, "vector growth across backends")
|
||||
Add(*list, "vector-growth-ab", "bench/vector_growth_ab.py", .Python, .Host, "two vector-growth binaries, shuffled")
|
||||
Add(*list, "vm-android", "bench/vm_android.py", .Python, .Device, "saved engine libraries on one Android device")
|
||||
Add(*list, "vm-execution", "bench/vm_execution.py", .Python, .Host, "verified engine execution")
|
||||
Add(*list, "vm-native", "bench/vm_native.py", .Python, .Host, "engine workloads against generated C and Go")
|
||||
Add(*list, "vm-startup", "bench/vm_startup.py", .Python, .Host, "checked loading and engine preparation")
|
||||
Add(*list, "wasm-tier", "bench/wasm_tier.py", .Python, .Host, "native/Wasm kernels; --standard adds independent C/Go references")
|
||||
Add(*list, "widget-native", "bench/widget_native.py", .Python, .Host, "matched frozen public Kryon Text, Input and Button scenarios")
|
||||
Add(*list, "widget-profile", "bench/widget_profile.zi", .Ziran, .Host, "SIGPROF of warmed public widget scenarios")
|
||||
Add(*list, "zx-compare", "bench/zx_compare.zi", .Ziran, .Host, "ZX runtime comparison cohorts")
|
||||
Add(*list, "zx-compare-devices", "bench/zx_compare.py", .Python, .Device, "ZX comparison on Alpha or a USB phone")
|
||||
Add(*list, "zx-engine", "bench/zx_engine.zi", .Ziran, .Host, "instruction engine against the C target")
|
||||
Add(*list, "zx-execution", "bench/zx_execution.zi", .Ziran, .Host, "warm execution of the matrix's bundles")
|
||||
Add(*list, "zx-host-slice", "bench/benchmark_zx_host_slice.py", .Python, .Host, "matched i386 host slices, integer blocks and aggregate loads")
|
||||
return list
|
||||
}
|
||||
|
||||
Concat :: (left: string, right: string) -> string {
|
||||
parts: [2]string = .[left, right]
|
||||
return TextDetach(TextJoin(parts[:], ""))
|
||||
}
|
||||
|
||||
Pad :: (text: string, width: s64) -> string {
|
||||
spaces := " "
|
||||
if text.count >= width || width > spaces.count { return text }
|
||||
return Concat(text, spaces[0:width - text.count])
|
||||
}
|
||||
|
||||
PlaceName :: (place: Place) -> string {
|
||||
if place == .Device { return "device" }
|
||||
if place == .Report { return "report" }
|
||||
return "host"
|
||||
}
|
||||
|
||||
Find :: (list: []Benchmark, name: string) -> s64 {
|
||||
for index: cast(s64)0..list.count - 1 { if list[index].name == name { return index } }
|
||||
return -1
|
||||
}
|
||||
|
||||
Capture :: (arguments: []string, directory: string) -> (output: string, code: s32) {
|
||||
options: ProcessOptions = .{arguments = arguments, directory = directory, environment = BENCH_ENVIRONMENT[:],
|
||||
capture_output = true, merge_error = true}
|
||||
run: ProcessRun
|
||||
if !RunProcess(options, *run) { return "", 127 }
|
||||
return TextDetach(TextCopy(TextTrim(BuilderFinish(run.output)))), run.code
|
||||
}
|
||||
|
||||
HostName :: () -> string {
|
||||
text, found := ReadEntireFile("/proc/sys/kernel/hostname")
|
||||
return ifx found then TextDetach(TextCopy(TextTrim(text))) else "unknown"
|
||||
}
|
||||
|
||||
Virtualization :: () -> string {
|
||||
command: [1]string = .["systemd-detect-virt"]
|
||||
output, code := Capture(command[:], "")
|
||||
if code == 127 { return "unavailable" }
|
||||
return ifx output != "" then output else "none"
|
||||
}
|
||||
|
||||
List :: (list: []Benchmark) -> s32 {
|
||||
print("benchmarks (run with: build/bin/ziran run --target=c bench/bench.zi -- NAME [ARGS])\n")
|
||||
for item: list { print(" % % %\n", Pad(item.name, 21), Pad(PlaceName(item.place), 6), item.summary) }
|
||||
return 0
|
||||
}
|
||||
|
||||
Registered :: (list: []Benchmark, file: string) -> bool {
|
||||
for item: list { if item.file == file { return true } }
|
||||
for support: SUPPORT_FILES { if Concat("bench/", support) == file { return true } }
|
||||
return false
|
||||
}
|
||||
|
||||
IsDriver :: (repo: string, name: string) -> bool {
|
||||
if TextHasSuffix(name, ".py") || TextHasSuffix(name, ".sh") { return true }
|
||||
if !TextHasSuffix(name, ".zi") { return false }
|
||||
text, found := ReadEntireFile(TextDetach(JoinPath(JoinPath(repo, "bench"), name)))
|
||||
return found && (TextHasPrefix(text, "main ::") || TextContains(text, "\nmain ::"))
|
||||
}
|
||||
|
||||
Check :: (repo: string, list: []Benchmark) -> s32 {
|
||||
failures: s64 = 0
|
||||
for item: list {
|
||||
if !IsFile(TextDetach(JoinPath(repo, item.file))) { print("missing driver for %: %\n", item.name, item.file); failures += 1 }
|
||||
}
|
||||
names: Vec(string)
|
||||
if !ListDirectory(TextDetach(JoinPath(repo, "bench")), *names) { print("cannot list bench/\n"); return 1 }
|
||||
for name: names {
|
||||
if IsDriver(repo, name) && !Registered(list, Concat("bench/", name)) {
|
||||
print("bench/% is a driver that bench/bench.zi does not register\n", name)
|
||||
failures += 1
|
||||
}
|
||||
}
|
||||
probe: [3]string = .["sh", "-c",
|
||||
"test \"$ZIRAN_LEARN\" = off && test -z \"${DISPLAY+set}${WAYLAND_DISPLAY+set}${ZIRAN_PROFILE+set}\""]
|
||||
probe_output, code := Capture(probe[:], repo)
|
||||
if code != 0 { print("the shared benchmark environment did not apply: %\n", probe_output); failures += 1 }
|
||||
if failures > 0 { return 1 }
|
||||
print("bench entry: % benchmarks registered, every driver covered, shared environment applied\n", list.count)
|
||||
return 0
|
||||
}
|
||||
|
||||
Run :: (repo: string, item: Benchmark, extra: []string, local: bool) -> s32 {
|
||||
host := HostName()
|
||||
virtualization := Virtualization()
|
||||
required := EnvironmentText("ZIRAN_BENCH_HOST")
|
||||
if required == "" { required = "alpha" }
|
||||
if item.place == .Host && !local {
|
||||
physical := virtualization == "none" || virtualization == "container-other"
|
||||
if host != required || !physical {
|
||||
print("% measures only on the physical host %; this is % (virtualization %).\n", item.name, required, host, virtualization)
|
||||
print("Run it there, or pass --local before the name for a measurement-free mode.\n")
|
||||
return 2
|
||||
}
|
||||
}
|
||||
command: Vec(string)
|
||||
if item.runner == .Ziran {
|
||||
ziran := TextDetach(JoinPath(repo, "build/bin/ziran"))
|
||||
if !IsFile(ziran) { print("build the toolchain first: make\n"); return 2 }
|
||||
modules := ifx item.module_path == "" then repo else TextDetach(JoinPath(repo, item.module_path))
|
||||
prefix := string.[ziran, "run", "--target=c", "--root", TextDetach(JoinPath(repo, "bench")), "--module-path", modules,
|
||||
TextDetach(JoinPath(repo, item.file)), "--"]
|
||||
for part: prefix { unused VecPush(command, part) }
|
||||
} else {
|
||||
interpreter := ifx item.runner == .Python then "python3" else "sh"
|
||||
unused VecPush(command, interpreter)
|
||||
unused VecPush(command, TextDetach(JoinPath(repo, item.file)))
|
||||
}
|
||||
for part: extra { unused VecPush(command, part) }
|
||||
mode := ifx local then "local, not a measurement" else PlaceName(item.place)
|
||||
print("benchmark % on % (virtualization %, %)\n", item.name, host, virtualization, mode)
|
||||
environment: Vec(string)
|
||||
for variable: BENCH_ENVIRONMENT { unused VecPush(environment, variable) }
|
||||
if item.compiler_library {
|
||||
libraries := Concat(Concat(EnvironmentText("LDLIBS"), " "), TextDetach(JoinPath(repo, "build/libziran.a")))
|
||||
unused VecPush(environment, Concat("LDLIBS=", libraries))
|
||||
}
|
||||
options: ProcessOptions = .{arguments = VecSlice(command, 0, command.count), directory = repo,
|
||||
environment = environment[:]}
|
||||
// The header reaches the terminal before anything the driver prints.
|
||||
unused FlushAll(null)
|
||||
run: ProcessRun
|
||||
if !RunProcess(options, *run) { print("cannot start %\n", item.file); return 2 }
|
||||
return run.code
|
||||
}
|
||||
|
||||
#scope_export
|
||||
#program_export
|
||||
main :: (argc: s32, argv: **u8) -> s32 {
|
||||
repo := PathParent(PathParent(EnvironmentText("ZIRAN_SCRIPT_FILE")))
|
||||
if repo == "" || !IsFile(TextDetach(JoinPath(repo, "bench/bench.zi"))) { repo = ResolvePath(".") }
|
||||
if !IsFile(TextDetach(JoinPath(repo, "bench/bench.zi"))) { print("run from the Ziran repository\n"); return 2 }
|
||||
registry := Registry()
|
||||
list := VecSlice(registry, 0, registry.count)
|
||||
index: s32 = 1
|
||||
local := false
|
||||
if index < argc && TextFromCString(argv[index]) == "--local" { local = true; index += 1 }
|
||||
if index >= argc { return List(list) }
|
||||
name := TextFromCString(argv[index])
|
||||
if name == "list" || name == "--help" || name == "-h" { return List(list) }
|
||||
if name == "check" { return Check(repo, list) }
|
||||
found := Find(list, name)
|
||||
if found < 0 {
|
||||
print("unknown benchmark: % (bench/bench.zi -- list shows them)\n", name)
|
||||
return 2
|
||||
}
|
||||
extra: Vec(string)
|
||||
index += 1
|
||||
while index < argc { unused VecPush(extra, TextFromCString(argv[index])); index += 1 }
|
||||
return Run(repo, list[found], VecSlice(extra, 0, extra.count), local)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Shared native benchmark statistics. Keep raw samples in their original order;
|
||||
// symmetric inclusive-quartile Tukey fences determine the displayed median.
|
||||
#import "std/math"
|
||||
#import "std/sort"
|
||||
using Vectors :: #import "std/vec"
|
||||
|
||||
BenchmarkSampleStatistics :: struct {
|
||||
valid: bool
|
||||
lower: float64
|
||||
upper: float64
|
||||
median: float64
|
||||
excluded: Vec(s64)
|
||||
included: Vec(float64)
|
||||
}
|
||||
|
||||
BenchmarkQuantile :: (sorted: []float64, fraction: float64) -> float64 {
|
||||
if sorted.count == 0 { return 0.0 }
|
||||
position := cast(float64)(sorted.count - 1) * fraction
|
||||
lower := cast(s64)position
|
||||
upper := ifx lower + 1 < sorted.count then lower + 1 else lower
|
||||
return sorted[lower] + (sorted[upper] - sorted[lower]) * (position - cast(float64)lower)
|
||||
}
|
||||
|
||||
BenchmarkAnalyze :: (samples: []float64) -> BenchmarkSampleStatistics {
|
||||
if samples.count < 3 { return .{} }
|
||||
sorted: Vec(float64)
|
||||
for sample: samples {
|
||||
if sample <= 0.0 || !Finite64(sample) { return .{} }
|
||||
VecPush(sorted, sample)
|
||||
}
|
||||
Sort(sorted[:])
|
||||
q1 := BenchmarkQuantile(sorted[:], 0.25)
|
||||
q3 := BenchmarkQuantile(sorted[:], 0.75)
|
||||
result: BenchmarkSampleStatistics
|
||||
result.lower = q1 - 1.5 * (q3 - q1)
|
||||
result.upper = q3 + 1.5 * (q3 - q1)
|
||||
for index: cast(s64)0..samples.count - 1 {
|
||||
if samples[index] < result.lower || samples[index] > result.upper { VecPush(result.excluded, index) }
|
||||
else { VecPush(result.included, samples[index]) }
|
||||
}
|
||||
if result.included.count < 3 { return .{} }
|
||||
kept: Vec(float64)
|
||||
for value: result.included { VecPush(kept, value) }
|
||||
Sort(kept[:])
|
||||
result.median = BenchmarkQuantile(kept[:], 0.5)
|
||||
result.valid = true
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Measure ZX execution with matched Linux/i386 archives on physical Alpha."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
from benchmark_samples import HostGate, summarize_samples
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('loader', type=Path)
|
||||
parser.add_argument('libraries', type=Path)
|
||||
parser.add_argument('inputs', type=Path)
|
||||
parser.add_argument('output', type=Path)
|
||||
parser.add_argument('--hot-blocks', action='store_true', help='Use the integer fixture in place of host slices')
|
||||
parser.add_argument('--aggregate-loads', action='store_true', help='Also measure 32 KiB aggregate snapshots')
|
||||
args = parser.parse_args()
|
||||
host = socket.gethostname()
|
||||
virtualization = subprocess.run(['systemd-detect-virt'], text=True, capture_output=True).stdout.strip()
|
||||
if host.split('.')[0] != 'alpha' or virtualization != 'none':
|
||||
parser.error('A physical Alpha host is required')
|
||||
|
||||
inputs = args.inputs.resolve()
|
||||
gate = HostGate()
|
||||
workloads = [('integer-blocks', 113475636, 'engine', False)] if args.hot_blocks else [
|
||||
('small', 0x235689BC, 'slice', True), ('large', 0x235689BC, 'slice', True),
|
||||
]
|
||||
if args.aggregate_loads:
|
||||
workloads.append(('aggregate-load', 499008, 'engine', False))
|
||||
workloads.extend([
|
||||
('rill-row', 1622073797, 'engine', False),
|
||||
('sieve', 2262, 'engine', False),
|
||||
('records', 68788, 'engine', False),
|
||||
])
|
||||
order = ('baseline', 'candidate', 'candidate', 'baseline',
|
||||
'candidate', 'baseline', 'baseline', 'candidate')
|
||||
receipt = {'host': host, 'virtualization': virtualization, 'kernel': platform.release(),
|
||||
'gate': gate.describe(), 'order': order, 'sha256': {}, 'workloads': {}}
|
||||
for artifact in sorted(inputs.iterdir()):
|
||||
if artifact.is_file():
|
||||
with artifact.open('rb') as stream:
|
||||
receipt['sha256'][artifact.name] = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
def save():
|
||||
temp = args.output.with_suffix('.tmp')
|
||||
temp.write_text(json.dumps(receipt, indent=2) + '\n')
|
||||
temp.replace(args.output)
|
||||
|
||||
for workload, expected, driver, borrow in workloads:
|
||||
attempts = []
|
||||
samples = {'baseline': [], 'candidate': []}
|
||||
receipt['workloads'][workload] = {'attempts': attempts, 'summaries': {}}
|
||||
for variant in order:
|
||||
env = dict(os.environ)
|
||||
env.pop('MATRIX_BORROW_SLICE', None)
|
||||
if borrow and variant == 'candidate':
|
||||
env['MATRIX_BORROW_SLICE'] = '1'
|
||||
command = [args.loader, '--library-path', args.libraries,
|
||||
inputs / f'{variant}-{driver}', inputs / f'{workload}.zx', str(expected), '15']
|
||||
for _ in range(gate.ATTEMPTS):
|
||||
measurement, observation = gate.observe(lambda: json.loads(
|
||||
subprocess.check_output(command, env=env, text=True)))
|
||||
rejection = gate.rejection(observation)
|
||||
attempts.append(dict(variant=variant, borrowed=borrow and variant == 'candidate',
|
||||
measurement=measurement, host_gate=observation, rejection=rejection))
|
||||
save()
|
||||
print(f'{workload} {variant} cpu{gate.cpu}: {rejection or "accepted"}', flush=True)
|
||||
if rejection is None:
|
||||
samples[variant].extend(ms / measurement['batches'] for ms in measurement['batch_samples_ms'])
|
||||
break
|
||||
gate.choose_core()
|
||||
else:
|
||||
raise SystemExit('Host gate rejected every attempt')
|
||||
result = receipt['workloads'][workload]
|
||||
result['summaries'] = {variant: summarize_samples(values) for variant, values in samples.items()}
|
||||
result['speedup'] = result['summaries']['baseline']['median_ms'] / result['summaries']['candidate']['median_ms']
|
||||
save()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -94,7 +94,7 @@ def main():
|
||||
emitted = output/'c'; bundle = output/'program.zx'
|
||||
check = [binaries/'zi2zir', '--check-only', '--root', root, input_path]
|
||||
emit = [binaries/'zi2c', '--root', root, '-o', emitted, input_path]
|
||||
pack = [binaries/'zi2zx', 'bundle', '--root', root, '--entry', 'program:Answer', '-o', bundle, input_path]
|
||||
pack = [binaries/'zi2zx', '--root', root, '--entry', 'program:Answer', '-o', bundle, input_path]
|
||||
for phase, command in [('check', check), ('emit:c', emit), ('bundle', pack)]:
|
||||
invoke(command); register(case, form, version, phase, command)
|
||||
invoke([binaries/'zi2zx', 'run', bundle], expected=expected)
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
// Compare generated C with the native pipeline using identical checked input.
|
||||
// Run only through bench/bench.zi; all compilation and sampling shares its
|
||||
// learning-off environment and the caller's build-queue reservation.
|
||||
#import "c_teacher_assembly"
|
||||
#import "c_teacher_profile"
|
||||
#import "c_teacher_rules"
|
||||
#import "std/byte_text_linux"
|
||||
#import "std/environment_linux"
|
||||
#import "std/file"
|
||||
#import "std/file_tree_linux"
|
||||
#import "std/json_document"
|
||||
#import "std/number_text"
|
||||
#import "std/process_run_linux"
|
||||
#import "std/text_tools"
|
||||
using Vectors :: #import "std/vec"
|
||||
|
||||
#scope_file
|
||||
Case :: struct { name: string; bundle: string; cdir: string; symbol: string; header: string; expected: s32; printing: bool; checksum: string }
|
||||
Finding :: struct { workload: string; compiler: string; name: string; native: TeacherMetrics; teacher: TeacherMetrics; samples: s64; total: s64; score: s64 }
|
||||
|
||||
Join :: (a: string, b: string) -> string { parts := string.[a, b]; return TextDetach(TextJoin(parts[:], "")) }
|
||||
Number :: (n: s64) -> string { bytes: [32]u8; return Join("", FormatInteger(n, bytes[:])) }
|
||||
Field :: (d: *JsonDocument, node: s32, key: string) -> string { return TextDetach(JsonString(d, JsonMember(d, node, key))) }
|
||||
Integer :: (d: *JsonDocument, node: s32, key: string) -> s64 { n, ok := JsonInteger(d, JsonMember(d, node, key)); return ifx ok then n else -1 }
|
||||
Capture :: (args: []string) -> (text: string, code: s32) {
|
||||
run: ProcessRun
|
||||
options: ProcessOptions = .{arguments = args, capture_output = true, merge_error = true}
|
||||
if !RunProcess(options, *run) { return "could not start child", 127 }
|
||||
return TextDetach(BuilderFinish(run.output)), run.code
|
||||
}
|
||||
Require :: (args: []string) -> bool {
|
||||
text, code := Capture(args)
|
||||
if code != 0 { print("command failed (%): %\n%\n", code, TextJoin(args, " "), text); return false }
|
||||
return true
|
||||
}
|
||||
Sources :: (directory: string, suffix: string, files: *Vec(string)) {
|
||||
names: Vec(string)
|
||||
if !ListDirectory(directory, *names) { return }
|
||||
for name: names {
|
||||
path := TextDetach(JoinPath(directory, name))
|
||||
if IsDirectory(path) { Sources(path, suffix, files) }
|
||||
else if TextHasSuffix(path, suffix) { unused VecPush(files.*, path) }
|
||||
}
|
||||
}
|
||||
Hash :: (path: string) -> string {
|
||||
command := string.["sha256sum", path]
|
||||
text, code := Capture(command[:])
|
||||
return ifx code == 0 && text.count >= 64 then text[:64] else "unavailable"
|
||||
}
|
||||
Clang :: () -> string {
|
||||
candidates := string.["clang", "clang-22", "clang-21", "clang-20", "clang-19", "clang-18", "clang-17"]
|
||||
for candidate: candidates {
|
||||
command := string.[candidate, "--version"]
|
||||
version, code := Capture(command[:])
|
||||
if code == 0 { return candidate }
|
||||
}
|
||||
return ""
|
||||
}
|
||||
Metrics :: (m: TeacherMetrics) -> string {
|
||||
values := s64.[m.instructions, m.loop_instructions, m.back_edges, m.stack_reads, m.stack_writes,
|
||||
m.memory, m.indexed, m.branches, m.forward_branches, m.calls, m.vectors, m.multiplies, m.divides, m.shifts, m.loop_constants]
|
||||
parts: Vec(string)
|
||||
for value: values { unused VecPush(parts, Number(value)) }
|
||||
return TextDetach(TextJoin(VecSlice(parts, 0, parts.count), "/"))
|
||||
}
|
||||
Patterns :: (n: TeacherMetrics, c: TeacherMetrics) -> string {
|
||||
patterns: Vec(string)
|
||||
if n.stack_reads + n.stack_writes > c.stack_reads + c.stack_writes { unused VecPush(patterns, "stack traffic (regalloc/aggregate lane)") }
|
||||
if n.branches > c.branches { unused VecPush(patterns, "branch layout/loop rotation (SSA lane)") }
|
||||
if n.calls > c.calls { unused VecPush(patterns, "calls/inlining candidates") }
|
||||
if n.multiplies + n.divides > c.multiplies + c.divides { unused VecPush(patterns, "strength reduction candidates") }
|
||||
if n.loop_constants > c.loop_constants { unused VecPush(patterns, "loop constants/LICM candidates") }
|
||||
if c.vectors > n.vectors { unused VecPush(patterns, "vector idioms (inspect scalar SSE uses)") }
|
||||
if n.memory > c.memory { unused VecPush(patterns, "memory/address folding candidates") }
|
||||
return TextDetach(TextJoin(VecSlice(patterns, 0, patterns.count), "; "))
|
||||
}
|
||||
|
||||
SaveProfile :: (path: string, profile: *TeacherProfile, digest: string) -> bool {
|
||||
document: JsonDocument
|
||||
defer JsonReset(*document)
|
||||
root := JsonNewObject(*document)
|
||||
JsonSet(*document, root, "artifact_sha256", JsonNewStringCopy(*document, digest))
|
||||
JsonSet(*document, root, "samples", JsonNewInteger(*document, profile.total))
|
||||
JsonSet(*document, root, "runs", JsonNewInteger(*document, profile.runs))
|
||||
ips := JsonNewArray(*document)
|
||||
JsonSet(*document, root, "ips", ips)
|
||||
for sample: profile.samples {
|
||||
ip := JsonNewObject(*document)
|
||||
JsonSet(*document, ip, "address", JsonNewInteger(*document, cast(s64)sample.address))
|
||||
JsonSet(*document, ip, "count", JsonNewInteger(*document, sample.count))
|
||||
unused JsonAppend(*document, ips, ip)
|
||||
}
|
||||
return WriteEntireFile(path, TextDetach(JsonWrite(*document, root, JsonPythonStyle(2))))
|
||||
}
|
||||
Append :: (text: *Vec(u8), value: string) { BuilderAppend(text.*, value) }
|
||||
Line :: (text: *Vec(u8), value: string) { Append(text, value); Append(text, "\n") }
|
||||
Row :: (text: *Vec(u8), cells: []string) {
|
||||
Append(text, "| "); Append(text, TextDetach(TextJoin(cells, " | "))); Line(text, " |")
|
||||
}
|
||||
LoopSummary :: (code: []TeacherInstruction, begin: s64, end: s64, base: s64, profile: *TeacherProfile) -> string {
|
||||
loops := TeacherLoops(code, begin, end)
|
||||
best: TeacherLoop
|
||||
best_samples: s64 = -1
|
||||
for loop: loops {
|
||||
samples: s64
|
||||
for sample: profile.samples {
|
||||
if sample.address >= cast(u64)(base + loop.begin) && sample.address <= cast(u64)(base + loop.end) { samples += sample.count }
|
||||
}
|
||||
if samples > best_samples || samples == best_samples && loop.instructions > best.instructions {
|
||||
best = loop; best_samples = samples
|
||||
}
|
||||
}
|
||||
if best_samples < 0 { return "none" }
|
||||
parts := string.[Number(best.begin), "..", Number(best.end), ": ", Number(best.instructions), " instructions, ", Number(best_samples), " samples"]
|
||||
return TextDetach(TextJoin(parts[:], ""))
|
||||
}
|
||||
Bindings :: (arguments: *Vec(string)) -> bool {
|
||||
text, found := ReadEntireFile("build/site-library-targets/sources/widget_benchmarks.json")
|
||||
document: JsonDocument
|
||||
defer JsonReset(*document)
|
||||
if !found || !JsonRead(*document, text) { return false }
|
||||
bindings := JsonMember(*document, document.root, "bindings")
|
||||
if JsonKindOf(*document, bindings) != .Array { return false }
|
||||
for index: cast(s32)0..JsonCount(*document, bindings) - 1 {
|
||||
binding := TeacherIRBinding(JsonString(*document, JsonElement(*document, bindings, index)))
|
||||
if binding == "" { return false }
|
||||
unused VecPush(arguments.*, "--bind")
|
||||
unused VecPush(arguments.*, binding)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Reuse the scenario harness's checked IR, including its ordinary library
|
||||
// bindings, rather than teaching this tool anything about widget internals.
|
||||
GenerateC :: (item: Case, directory: string) -> bool {
|
||||
if item.name == "Hello" { return true }
|
||||
arguments: Vec(string)
|
||||
root := ifx item.header == "wasm_tier.h" then "bench" else "build/site-library-targets/ir"
|
||||
module := ifx item.header == "wasm_tier.h" then "wasm_tier" else "widget_benchmarks"
|
||||
entry := ifx item.header == "wasm_tier.h" then item.name else Join(item.name, "Case")
|
||||
flags := string.["build/bin/zi2c", "--no-main", "--root", root, "--module-path", "std", "--entry",
|
||||
Join(module, Join(":", entry)), "-o", directory]
|
||||
for flag: flags { unused VecPush(arguments, flag) }
|
||||
if root == "bench" { unused VecPush(arguments, "bench/wasm_tier.zi") }
|
||||
else {
|
||||
if !Bindings(*arguments) { return false }
|
||||
Sources(root, ".zir", *arguments)
|
||||
}
|
||||
return Require(VecSlice(arguments, 0, arguments.count))
|
||||
}
|
||||
|
||||
Compare :: (item: Case, compiler: string, work: string, report: *Vec(u8), findings: *Vec(Finding)) -> bool {
|
||||
directory := TextDetach(JoinPath(work, item.name))
|
||||
if !CreateDirectories(directory) { return false }
|
||||
generated := TextDetach(JoinPath(directory, "c"))
|
||||
if !GenerateC(item, generated) { return false }
|
||||
cdir := ifx item.name == "Hello" then item.cdir else generated
|
||||
native := TextDetach(JoinPath(directory, "native"))
|
||||
mapfile := TextDetach(JoinPath(directory, "native.map.json"))
|
||||
native_command := string.["build/bin/zx2native", "-o", native, item.bundle]
|
||||
map_command := string.["build/bin/zx2native", "--emit", "map", "-o", mapfile, item.bundle]
|
||||
if !Require(native_command[:]) || !Require(map_command[:]) { return false }
|
||||
maptext, read := ReadEntireFile(mapfile)
|
||||
map: JsonDocument
|
||||
defer JsonReset(*map)
|
||||
if !read || !JsonRead(*map, maptext) { return false }
|
||||
identity := JsonMember(*map, map.root, "identity")
|
||||
if Field(*map, identity, "digest") != Hash(native) { print("native map identity mismatch for %\n", item.name); return false }
|
||||
image := JsonMember(*map, map.root, "image")
|
||||
offset := Integer(*map, image, "text_file_offset")
|
||||
size := Integer(*map, image, "text_size")
|
||||
base := Integer(*map, image, "text_virtual_address")
|
||||
raw := TextDetach(JoinPath(directory, "text.bin"))
|
||||
extract_command := string.["dd", Join("if=", native), Join("of=", raw), "bs=65536", "iflag=skip_bytes,count_bytes",
|
||||
Join("skip=", Number(offset)), Join("count=", Number(size)), "status=none"]
|
||||
if offset < 0 || size <= 0 || !Require(extract_command[:]) { return false }
|
||||
native_dump := string.["objdump", "-D", "-b", "binary", "-m", "i386:x86-64", "-M", "intel", "--no-show-raw-insn", raw]
|
||||
ntext, ncode := Capture(native_dump[:])
|
||||
if ncode != 0 { return false }
|
||||
unused WriteEntireFile(JoinPath(directory, "native.asm"), ntext)
|
||||
executable := TextDetach(JoinPath(directory, compiler))
|
||||
arguments: Vec(string)
|
||||
flags := string.[compiler, "-O2", "-std=c11"]
|
||||
for flag: flags { unused VecPush(arguments, flag) }
|
||||
matrix_flags := string.["-DMATRIX_NATIVE", Join("-I", cdir),
|
||||
Join("-DMATRIX_HEADER=\"", Join(item.header, "\"")), Join("-DMATRIX_ENTRY=", item.symbol)]
|
||||
if item.header != "" { for flag: matrix_flags { unused VecPush(arguments, flag) } }
|
||||
if item.header != "" { unused VecPush(arguments, "bench/site_target_host.c") }
|
||||
if item.printing { unused VecPush(arguments, "-DMATRIX_VOID") }
|
||||
Sources(cdir, ".c", *arguments)
|
||||
link_flags := string.["-lm", "-o", executable]
|
||||
for flag: link_flags { unused VecPush(arguments, flag) }
|
||||
if !Require(VecSlice(arguments, 0, arguments.count)) { return false }
|
||||
parity_command := string.[executable, "-", item.checksum, "3"]
|
||||
parity, parity_code := Capture(parity_command[:])
|
||||
if parity_code != 0 { print("C checksum parity failed for %/%: %\n", item.name, compiler, parity); return false }
|
||||
unused WriteEntireFile(JoinPath(directory, Join(compiler, ".parity.json")), parity)
|
||||
c_dump := string.["objdump", "-d", "-M", "intel", "--no-show-raw-insn", executable]
|
||||
ctext, ccode := Capture(c_dump[:])
|
||||
if ccode != 0 { return false }
|
||||
unused WriteEntireFile(JoinPath(directory, Join(compiler, ".asm")), ctext)
|
||||
// Sampling is diagnostic, never a benchmark timing. Short programs may
|
||||
// yield no ticks; report unknown instead of inventing a time share.
|
||||
profile := TeacherSampleProgram(native, item.expected)
|
||||
if !profile.valid { print("sampling failed for %\n", item.name); return false }
|
||||
if !SaveProfile(JoinPath(directory, Join(compiler, ".profile.json")), *profile, Hash(native)) { return false }
|
||||
Line(report, Join("\n## ", Join(item.name, Join(" / ", compiler))))
|
||||
Line(report, Join("Native SHA-256: ", Hash(native)))
|
||||
Line(report, Join("C SHA-256: ", Hash(executable)))
|
||||
Line(report, Join("ZX SHA-256: ", Hash(item.bundle)))
|
||||
version_command := string.[compiler, "--version"]
|
||||
compiler_version, version_code := Capture(version_command[:])
|
||||
version_end := TextFind(compiler_version, "\n")
|
||||
if version_end >= 0 { compiler_version = compiler_version[:version_end] }
|
||||
Line(report, Join("Compiler: ", compiler_version))
|
||||
Line(report, Join("SIGPROF samples/runs: ", Join(Number(profile.total), Join("/", Number(profile.runs)))))
|
||||
Line(report, "\n| Function | Native metrics | C metrics | Samples | Native loop with most samples (text offsets) |\n| --- | --- | --- | ---: | --- |")
|
||||
ninst := TeacherInstructions(ntext)
|
||||
cinst := TeacherInstructions(ctext)
|
||||
symbol_command := string.["nm", "-S", "-n", "--defined-only", executable]
|
||||
symbol_text, symbol_code := Capture(symbol_command[:])
|
||||
if symbol_code != 0 { return false }
|
||||
symbols := TeacherSizedSymbols(symbol_text)
|
||||
proposals: JsonDocument
|
||||
defer JsonReset(*proposals)
|
||||
proposal_root := JsonNewObject(*proposals)
|
||||
JsonSet(*proposals, proposal_root, "schema_version", JsonNewInteger(*proposals, 1))
|
||||
JsonSet(*proposals, proposal_root, "native_sha256", JsonNewStringCopy(*proposals, Hash(native)))
|
||||
JsonSet(*proposals, proposal_root, "zx_sha256", JsonNewStringCopy(*proposals, Hash(item.bundle)))
|
||||
JsonSet(*proposals, proposal_root, "c_sha256", JsonNewStringCopy(*proposals, Hash(executable)))
|
||||
JsonSet(*proposals, proposal_root, "compiler", JsonNewStringCopy(*proposals, compiler_version))
|
||||
proposal_rules := JsonNewArray(*proposals)
|
||||
JsonSet(*proposals, proposal_root, "candidates", proposal_rules)
|
||||
functions := JsonMember(*map, map.root, "functions")
|
||||
for index: cast(s32)0..JsonCount(*map, functions) - 1 {
|
||||
function := JsonElement(*map, functions, index)
|
||||
begin := Integer(*map, function, "begin")
|
||||
end := Integer(*map, function, "end")
|
||||
if begin < 0 || end <= begin { continue }
|
||||
name := Field(*map, function, "name")
|
||||
module := Field(*map, function, "module")
|
||||
mangled := Join(module, Join("_", name))
|
||||
found := false
|
||||
cbegin: s64
|
||||
cend: s64
|
||||
cmetrics: TeacherMetrics
|
||||
for symbol: symbols {
|
||||
if symbol.name == mangled || name != "main" && symbol.name == name {
|
||||
cmetrics = TeacherMeasure(VecSlice(cinst, 0, cinst.count), symbol.begin, symbol.end)
|
||||
cbegin = symbol.begin; cend = symbol.end
|
||||
found = true; break
|
||||
}
|
||||
}
|
||||
native_metrics := TeacherMeasure(VecSlice(ninst, 0, ninst.count), begin, end)
|
||||
samples: s64
|
||||
for sample: profile.samples {
|
||||
if sample.address >= cast(u64)(base + begin) && sample.address < cast(u64)(base + end) { samples += sample.count }
|
||||
}
|
||||
cname := ifx found then Metrics(cmetrics) else "absent (inline/dead/renamed unknown)"
|
||||
cells := string.[mangled, Metrics(native_metrics), cname, Number(samples),
|
||||
LoopSummary(VecSlice(ninst, 0, ninst.count), begin, end, base, *profile)]
|
||||
Row(report, cells[:])
|
||||
if found {
|
||||
rules := TeacherMineRewrites(VecSlice(ninst, 0, ninst.count), begin, end,
|
||||
VecSlice(cinst, 0, cinst.count), cbegin, cend)
|
||||
for rule: rules {
|
||||
proposal := JsonNewObject(*proposals)
|
||||
JsonSet(*proposals, proposal, "rule", JsonNewStringCopy(*proposals, "x86-multiply-constant"))
|
||||
JsonSet(*proposals, proposal, "function", JsonNewStringCopy(*proposals, mangled))
|
||||
JsonSet(*proposals, proposal, "factor", JsonNewInteger(*proposals, rule.factor))
|
||||
JsonSet(*proposals, proposal, "native", JsonNewStringCopy(*proposals, rule.native))
|
||||
JsonSet(*proposals, proposal, "teacher", JsonNewStringCopy(*proposals, rule.teacher))
|
||||
JsonSet(*proposals, proposal, "precondition", JsonNewStringCopy(*proposals, "integer-modulo-width; flags-dead; no-memory"))
|
||||
JsonSet(*proposals, proposal, "verified", JsonNewBool(*proposals, false))
|
||||
unused JsonAppend(*proposals, proposal_rules, proposal)
|
||||
}
|
||||
}
|
||||
if found && native_metrics.instructions > cmetrics.instructions {
|
||||
delta := native_metrics.instructions - cmetrics.instructions
|
||||
// Ranking is a proxy, not estimated cycles. Weight excess code by
|
||||
// observed function samples; unsampled functions rank last.
|
||||
score := ifx profile.total > 0 then samples * 100000 * delta / (native_metrics.instructions * profile.total) else 0
|
||||
unused VecPush(findings.*, Finding.{workload = item.name, compiler = compiler, name = mangled,
|
||||
native = native_metrics, teacher = cmetrics, samples = samples, total = profile.total, score = score})
|
||||
}
|
||||
}
|
||||
return WriteEntireFile(JoinPath(directory, Join(compiler, ".candidates.json")),
|
||||
TextDetach(JsonWrite(*proposals, proposal_root, JsonPythonStyle(2))))
|
||||
}
|
||||
|
||||
#program_export
|
||||
main :: (argc: s32, argv: **u8) -> s32 {
|
||||
output := "bench/results/c-teacher-omega.md"
|
||||
if argc == 3 && TextFromCString(argv[1]) == "--output" { output = TextFromCString(argv[2]) }
|
||||
else if argc != 1 { print("c_teacher.zi [--output REPORT.md]\nPrepare wasm-tier and library-targets through bench/bench.zi first.\n"); return 2 }
|
||||
work := "build/c-teacher"
|
||||
if !CreateDirectories(work) { return 1 }
|
||||
cases: Vec(Case)
|
||||
kernel_names := string.["Sieve", "Records", "Hash", "Vectors", "Calls", "Printing"]
|
||||
for name: kernel_names {
|
||||
wrapper_path := Join("build/wasm-tier/native_", Join(name, ".zi"))
|
||||
wrapper, found := ReadEntireFile(wrapper_path)
|
||||
if !found { print("prepare wasm-tier first: missing %\n", wrapper_path); return 1 }
|
||||
wrapper = TextDetach(TextReplace(wrapper, "0..31", "0..1023"))
|
||||
checksum_at := TextFind(wrapper, "checksum != ")
|
||||
result := "0"
|
||||
if checksum_at >= 0 {
|
||||
at := checksum_at + 12
|
||||
end := TextFind(wrapper, " {", at)
|
||||
checksum, ok := TextInteger(wrapper[at:end])
|
||||
if !ok { return 1 }
|
||||
result = Number(checksum / 32)
|
||||
wrapper = TextDetach(TextReplace(wrapper, Join("checksum != ", Number(checksum)), Join("checksum != ", Number(checksum * 32))))
|
||||
}
|
||||
teacher_source := TextDetach(JoinPath(work, Join("teacher_", Join(name, ".zi"))))
|
||||
bundle := TextDetach(JoinPath(work, Join(name, ".zx")))
|
||||
if !WriteEntireFile(teacher_source, wrapper) { return 1 }
|
||||
build_command := string.["build/bin/zi2zx", "--root", work, "--module-path", "bench", "--module-path", "std",
|
||||
"--entry", Join("teacher_", Join(name, ":main")), "-o", bundle, teacher_source]
|
||||
if !Require(build_command[:]) { return 1 }
|
||||
unused VecPush(cases, Case.{name = name, bundle = bundle,
|
||||
cdir = "build/wasm-tier/c", symbol = Join("wasm_tier_", name), header = "wasm_tier.h", expected = 42, printing = name == "Printing", checksum = result})
|
||||
}
|
||||
widget_cases := string.["Button", "Text", "Input"]
|
||||
widget_ids := string.["button", "text", "input"]
|
||||
for index: 0..2 {
|
||||
folder := Join("build/site-library-targets/", widget_ids[index])
|
||||
module := Join("teacher_", widget_cases[index])
|
||||
source := TextDetach(JoinPath(work, Join(module, ".zi")))
|
||||
bundle := TextDetach(JoinPath(work, Join(module, ".zx")))
|
||||
body := string.["Widget :: #import \"widget_benchmarks\";\n#program_export\nmain :: () -> s32 {\n",
|
||||
" for iteration: 0..2047 { if Widget.", widget_cases[index], "Case() != 0 { return 1 } }\n return 0\n}\n"]
|
||||
if !WriteEntireFile(source, TextDetach(TextJoin(body[:], ""))) { return 1 }
|
||||
command: Vec(string)
|
||||
flags := string.["build/bin/zi2zx", "--root", work, "--module-path", "build/site-library-targets/ir", "--module-path", "std",
|
||||
"--entry", Join(module, ":main"), "-o", bundle]
|
||||
for flag: flags { unused VecPush(command, flag) }
|
||||
if !Bindings(*command) { return 1 }
|
||||
unused VecPush(command, source)
|
||||
Sources("build/site-library-targets/ir", ".zir", *command)
|
||||
if !Require(VecSlice(command, 0, command.count)) { return 1 }
|
||||
unused VecPush(cases, Case.{name = widget_cases[index], bundle = bundle,
|
||||
cdir = Join(folder, "/c"), symbol = Join(widget_cases[index], "Case"), header = "widget_benchmarks.h", checksum = "0"})
|
||||
}
|
||||
hello_bundle := string.["build/bin/zi2zx", "--root", "examples", "--module-path", "std", "--entry", "hello:main", "-o", "build/c-teacher/hello.zx", "examples/hello.zi"]
|
||||
hello_c := string.["build/bin/zi2c", "--root", "examples", "--module-path", "std", "-o", "build/c-teacher/hello-c", "examples/hello.zi"]
|
||||
if !Require(hello_bundle[:]) || !Require(hello_c[:]) { return 1 }
|
||||
unused VecPush(cases, Case.{name = "Hello", bundle = "build/c-teacher/hello.zx", cdir = "build/c-teacher/hello-c",
|
||||
symbol = "hello_main", header = "hello.h", printing = true, checksum = "0"})
|
||||
report: Vec(u8)
|
||||
revision_command := string.["git", "rev-parse", "HEAD"]
|
||||
revision, code := Capture(revision_command[:])
|
||||
Line(*report, "# C teacher: native assembly comparison")
|
||||
Line(*report, Join("\nBase revision: ", TextTrim(revision)))
|
||||
host_command := string.["hostname"]
|
||||
host, host_code := Capture(host_command[:])
|
||||
if host_code != 0 { return 1 }
|
||||
Line(*report, Join("Host: ", TextTrim(host)))
|
||||
tool_names := string.["build/bin/zi2c", "build/bin/zi2zx", "build/bin/zx2native"]
|
||||
tool_hashes: Vec(string)
|
||||
for tool: tool_names {
|
||||
digest := Hash(tool)
|
||||
unused VecPush(tool_hashes, digest)
|
||||
Line(*report, Join(tool, Join(" SHA-256: ", digest)))
|
||||
}
|
||||
Line(*report, "Learning off. Generated C compiled with -O2; native compiled from verified ZX. Function extents come from the native map; C symbols match module_name or exported name exactly. Absent symbols are not evidence of inlining. Metrics: instructions/loop-union/back-edges/stack-reads/stack-writes/memory/indexed/branches/forward-branches/calls/vector-register-uses/mul/div/shifts/loop-immediate-or-PC-relative candidates. Stack traffic includes locals and saves. Vector-register uses include scalar floating point. Loop constants are LICM candidates, not proven invariants. Back edges describe loop bodies, not execution frequency. SIGPROF uses a 1ms CPU timer, at most 30 runs; zero samples means unknown time share. Sampling includes process startup and runtime. Ranking weights relative instruction excess by observed function samples; it predicts neither cycles nor speedup.")
|
||||
findings: Vec(Finding)
|
||||
clang := Clang()
|
||||
failures: s64
|
||||
for item: cases {
|
||||
if !Compare(item, "cc", work, *report, *findings) {
|
||||
Line(*report, Join("\nINCOMPLETE: comparison failed for ", item.name))
|
||||
failures += 1
|
||||
continue
|
||||
}
|
||||
if clang != "" && !Compare(item, clang, work, *report, *findings) {
|
||||
Line(*report, Join("\nINCOMPLETE: clang comparison failed for ", item.name))
|
||||
failures += 1
|
||||
}
|
||||
}
|
||||
ranked: Vec(u8)
|
||||
Line(*ranked, "\n## Ranked C wins\n\n| Workload/compiler/function | Weighted excess | Function samples/total (estimated CPU share) | Patterns to inspect | Native | C |\n| --- | ---: | ---: | --- | --- | --- |")
|
||||
for index: 1..findings.count - 1 {
|
||||
at := index
|
||||
while at > 0 && findings[at].score > findings[at - 1].score {
|
||||
swap := findings[at]; findings[at] = findings[at - 1]; findings[at - 1] = swap; at -= 1
|
||||
}
|
||||
}
|
||||
for finding: findings {
|
||||
identity := string.[finding.workload, finding.compiler, finding.name]
|
||||
share := ifx finding.total > 0 then Join(Number(finding.samples * 100 / finding.total), "%") else "unknown"
|
||||
cells := string.[TextDetach(TextJoin(identity[:], "/")), Number(finding.score),
|
||||
Join(Number(finding.samples), Join("/", Join(Number(finding.total), Join(" ", share)))),
|
||||
Patterns(finding.native, finding.teacher), Metrics(finding.native), Metrics(finding.teacher)]
|
||||
Row(*ranked, cells[:])
|
||||
}
|
||||
Append(*report, TextDetach(BuilderFinish(ranked)))
|
||||
for index: 0..tool_names.count - 1 {
|
||||
if Hash(tool_names[index]) != tool_hashes[index] {
|
||||
Line(*report, Join("INCOMPLETE: compiler changed during comparison: ", tool_names[index]))
|
||||
failures += 1
|
||||
}
|
||||
}
|
||||
if !WriteEntireFile(output, TextDetach(BuilderFinish(report))) { return 1 }
|
||||
print("C teacher: % workloads, % ranked function comparisons, % failed; %\n", cases.count, findings.count, failures, output)
|
||||
return ifx failures == 0 then 0 else 1
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
// Structural observations, never equivalence proofs. Addresses are normalized
|
||||
// by the caller: ELF virtual addresses for C, text-relative addresses for ZX.
|
||||
#import "std/text_tools"
|
||||
#import "std/byte_text_linux"
|
||||
using Vectors :: #import "std/vec"
|
||||
|
||||
TeacherInstruction :: struct {
|
||||
address: s64
|
||||
mnemonic: string
|
||||
operands: string
|
||||
}
|
||||
|
||||
TeacherFunction :: struct {
|
||||
name: string
|
||||
begin: s64
|
||||
end: s64
|
||||
}
|
||||
|
||||
TeacherLoop :: struct { begin: s64; end: s64; instructions: s64 }
|
||||
|
||||
// Checked IR export uses the leaf module name. Apply the same mapping to
|
||||
// each qualified side of a manifest binding; retain the function spelling.
|
||||
TeacherIRBinding :: (binding: string) -> string {
|
||||
sides := TextSplit(binding, "=")
|
||||
flattened: Vec(string)
|
||||
for side: sides {
|
||||
colon := TextFind(side, ":")
|
||||
if colon < 0 { return "" }
|
||||
slash := TextFindLast(side[:colon], "/")
|
||||
unused VecPush(flattened, side[slash + 1:])
|
||||
}
|
||||
if flattened.count != 2 { return "" }
|
||||
return TextDetach(TextJoin(VecSlice(flattened, 0, flattened.count), "="))
|
||||
}
|
||||
|
||||
TeacherMetrics :: struct {
|
||||
instructions: s64
|
||||
loop_instructions: s64
|
||||
back_edges: s64
|
||||
stack_reads: s64
|
||||
stack_writes: s64
|
||||
memory: s64
|
||||
indexed: s64
|
||||
branches: s64
|
||||
forward_branches: s64
|
||||
calls: s64
|
||||
vectors: s64
|
||||
multiplies: s64
|
||||
divides: s64
|
||||
shifts: s64
|
||||
loop_constants: s64
|
||||
}
|
||||
|
||||
TeacherHex :: (text: string) -> (value: s64, valid: bool) {
|
||||
if TextHasPrefix(text, "0x") { text = text[2:] }
|
||||
value: s64
|
||||
digits: s64
|
||||
for byte: text {
|
||||
digit: s64 = -1
|
||||
if byte >= 48 && byte <= 57 { digit = cast(s64)byte - 48 }
|
||||
if byte >= 97 && byte <= 102 { digit = cast(s64)byte - 87 }
|
||||
if byte >= 65 && byte <= 70 { digit = cast(s64)byte - 55 }
|
||||
if digit < 0 || value > 576460752303423487 { return 0, false }
|
||||
value = value * 16 + digit
|
||||
digits += 1
|
||||
}
|
||||
return value, digits > 0
|
||||
}
|
||||
|
||||
// objdump --no-show-raw-insn -M intel. Ignore symbol headings, data and
|
||||
// diagnostic lines; never count a wrapped instruction byte line as code.
|
||||
TeacherInstructions :: (text: string) -> Vec(TeacherInstruction) {
|
||||
result: Vec(TeacherInstruction)
|
||||
lines := TextLines(text)
|
||||
for raw: lines {
|
||||
line := TextTrim(raw)
|
||||
colon := TextFind(line, ":")
|
||||
if colon <= 0 { continue }
|
||||
address, valid := TeacherHex(line[:colon])
|
||||
if !valid { continue }
|
||||
body := TextTrim(line[colon + 1:])
|
||||
at: s64
|
||||
while at < body.count && !TextIsSpace(body[at]) { at += 1 }
|
||||
if at == 0 { continue }
|
||||
mnemonic := body[:at]
|
||||
if mnemonic == "(bad)" || mnemonic[0] == 46 { continue }
|
||||
unused VecPush(result, TeacherInstruction.{address = address, mnemonic = mnemonic,
|
||||
operands = TextTrim(body[at:])})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
TeacherSymbols :: (text: string) -> Vec(TeacherFunction) {
|
||||
result: Vec(TeacherFunction)
|
||||
lines := TextLines(text)
|
||||
for raw: lines {
|
||||
line := TextTrim(raw)
|
||||
left := TextFind(line, " <")
|
||||
right := TextFind(line, ">:")
|
||||
if left <= 0 || right <= left { continue }
|
||||
address, valid := TeacherHex(line[:left])
|
||||
if !valid { continue }
|
||||
if result.count > 0 { result[result.count - 1].end = address }
|
||||
unused VecPush(result, TeacherFunction.{name = line[left + 2:right], begin = address, end = 9223372036854775807})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// nm -S -n --defined-only gives real symbol sizes, excluding alignment
|
||||
// padding and adjacent functions. Zero-sized/untyped symbols stay unmatched.
|
||||
TeacherSizedSymbols :: (text: string) -> Vec(TeacherFunction) {
|
||||
result: Vec(TeacherFunction)
|
||||
lines := TextLines(text)
|
||||
for line: lines {
|
||||
pieces := TextSplit(TextTrim(line), " ")
|
||||
fields: Vec(string)
|
||||
for piece: pieces { if piece != "" { unused VecPush(fields, piece) } }
|
||||
if fields.count != 4 || fields[2] != "T" && fields[2] != "t" { continue }
|
||||
address, address_ok := TeacherHex(fields[0])
|
||||
size, size_ok := TeacherHex(fields[1])
|
||||
if !address_ok || !size_ok || size <= 0 || size > 9223372036854775807 - address { continue }
|
||||
unused VecPush(result, TeacherFunction.{name = fields[3], begin = address, end = address + size})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
TeacherBranch :: (instruction: TeacherInstruction) -> bool {
|
||||
return TextHasPrefix(instruction.mnemonic, "j") || instruction.mnemonic == "loop"
|
||||
}
|
||||
|
||||
TeacherTarget :: (instruction: TeacherInstruction) -> (address: s64, valid: bool) {
|
||||
at: s64
|
||||
while at < instruction.operands.count && !TextIsSpace(instruction.operands[at]) { at += 1 }
|
||||
return TeacherHex(instruction.operands[:at])
|
||||
}
|
||||
|
||||
TeacherLoops :: (code: []TeacherInstruction, begin: s64, end: s64) -> Vec(TeacherLoop) {
|
||||
result: Vec(TeacherLoop)
|
||||
for instruction: code {
|
||||
if instruction.address < begin || instruction.address >= end || !TeacherBranch(instruction) { continue }
|
||||
target, valid := TeacherTarget(instruction)
|
||||
if !valid || target < begin || target > instruction.address { continue }
|
||||
count: s64
|
||||
for member: code { if member.address >= target && member.address <= instruction.address { count += 1 } }
|
||||
unused VecPush(result, TeacherLoop.{begin = target, end = instruction.address, instructions = count})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
TeacherMeasure :: (code: []TeacherInstruction, begin: s64, end: s64) -> TeacherMetrics {
|
||||
result: TeacherMetrics
|
||||
// Count the union of loop intervals; nested loops must not inflate the
|
||||
// static instruction count. Back edges are candidates, not hotness data.
|
||||
loops := TeacherLoops(code, begin, end)
|
||||
result.back_edges = loops.count
|
||||
for instruction: code {
|
||||
if instruction.address < begin || instruction.address >= end { continue }
|
||||
result.instructions += 1
|
||||
loop := false
|
||||
for candidate: loops {
|
||||
if instruction.address >= candidate.begin && instruction.address <= candidate.end { loop = true }
|
||||
}
|
||||
if loop { result.loop_instructions += 1 }
|
||||
operands := instruction.operands
|
||||
memory := TextContains(operands, "[")
|
||||
if memory {
|
||||
result.memory += 1
|
||||
if TextContains(operands, "*") || TextContains(operands, "+r") || TextContains(operands, "+e") { result.indexed += 1 }
|
||||
// Stack references include locals, saved registers and spills.
|
||||
// They cannot be identified as allocator spills from assembly alone.
|
||||
if TextContains(operands, "[rsp") || TextContains(operands, "[rbp") {
|
||||
comma := TextFind(operands, ",")
|
||||
bracket := TextFind(operands, "[")
|
||||
if comma >= 0 && bracket < comma && instruction.mnemonic != "cmp" && instruction.mnemonic != "test" && instruction.mnemonic != "lea" {
|
||||
result.stack_writes += 1
|
||||
} else if instruction.mnemonic != "lea" { result.stack_reads += 1 }
|
||||
}
|
||||
}
|
||||
if TeacherBranch(instruction) {
|
||||
result.branches += 1
|
||||
target, valid := TeacherTarget(instruction)
|
||||
if valid && target > instruction.address { result.forward_branches += 1 }
|
||||
}
|
||||
if instruction.mnemonic == "call" { result.calls += 1 }
|
||||
if TextContains(operands, "xmm") || TextContains(operands, "ymm") || TextContains(operands, "zmm") { result.vectors += 1 }
|
||||
if instruction.mnemonic == "imul" || instruction.mnemonic == "mul" { result.multiplies += 1 }
|
||||
if instruction.mnemonic == "idiv" || instruction.mnemonic == "div" { result.divides += 1 }
|
||||
if instruction.mnemonic == "shl" || instruction.mnemonic == "shr" || instruction.mnemonic == "sar" { result.shifts += 1 }
|
||||
if loop && (TextContains(operands, ",0x") || instruction.mnemonic == "lea" && TextContains(operands, "[rip")) {
|
||||
result.loop_constants += 1
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
// SIGPROF sampling of a private child, Linux x86-64. Install ITIMER_PROF at
|
||||
// exec's first stop, restore its instruction and registers, and then sample
|
||||
// unchanged code. No signal handler or runtime is added to the measured ELF.
|
||||
#import "std/c_string"
|
||||
#import "std/file"
|
||||
#import "std/number_text"
|
||||
#import "std/text_tools"
|
||||
using Vectors :: #import "std/vec"
|
||||
|
||||
#scope_file
|
||||
libc_teacher :: #system_library "libc";
|
||||
Ptrace :: (request: s64, pid: s32, address: u64, data: u64) -> s64 #foreign libc_teacher "ptrace";
|
||||
Fork :: () -> s32 #foreign libc_teacher "fork";
|
||||
Exec :: (path: *u8, arguments: **u8) -> s32 #foreign libc_teacher "execv";
|
||||
Exit :: (code: s32) -> void #foreign libc_teacher "_exit";
|
||||
WaitPid :: (pid: s32, status: *s32, options: s32) -> s32 #foreign libc_teacher "waitpid";
|
||||
Kill :: (pid: s32, number: s32) -> s32 #foreign libc_teacher "kill";
|
||||
Open :: (path: *u8, flags: s32) -> s32 #foreign libc_teacher "open";
|
||||
Dup :: (from: s32, to: s32) -> s32 #foreign libc_teacher "dup2";
|
||||
Close :: (fd: s32) -> s32 #foreign libc_teacher "close";
|
||||
PreadRaw :: (fd: s32, buffer: *u8, count: u64, offset: s64) -> s64 #foreign libc_teacher "pread";
|
||||
Errno :: () -> *s32 #foreign libc_teacher "__errno_location";
|
||||
Registers :: struct { words: [27]u64 }
|
||||
|
||||
Wait :: (pid: s32, status: *s32) -> bool {
|
||||
while true {
|
||||
if WaitPid(pid, status, 0) == pid { return true }
|
||||
if Errno()[0] != 4 { return false }
|
||||
}
|
||||
}
|
||||
|
||||
Hex :: (text: string) -> u64 {
|
||||
value: u64 = 0
|
||||
for byte: text {
|
||||
if byte >= #char "0" && byte <= #char "9" { value = value * 16 + cast(u64)(byte - #char "0") }
|
||||
else if byte >= #char "a" && byte <= #char "f" { value = value * 16 + cast(u64)(byte - #char "a") + 10 }
|
||||
else { break }
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// The first executable mapping without a path in MAPS, read from the
|
||||
// stopped child's memory.
|
||||
CaptureImage :: (pid: s32, maps: string, profile: *TeacherProfile) {
|
||||
lines := TextLines(maps)
|
||||
for line: lines {
|
||||
dash := TextFind(line, "-")
|
||||
space := TextFind(line, " ")
|
||||
if dash <= 0 || space <= dash || space + 4 > line.count || line[space + 3] != #char "x" { continue }
|
||||
// Anonymous mappings end after the inode field: five fields only.
|
||||
fields: s64 = 0
|
||||
at: s64 = 0
|
||||
while at < line.count {
|
||||
while at < line.count && line[at] == #char " " { at += 1 }
|
||||
if at < line.count { fields += 1 }
|
||||
while at < line.count && line[at] != #char " " { at += 1 }
|
||||
}
|
||||
if fields != 5 { continue }
|
||||
begin := Hex(line[0:dash])
|
||||
end := Hex(line[dash + 1:space])
|
||||
if end <= begin || end - begin > 268435456 { return }
|
||||
buffer: [32]u8
|
||||
parts := string.["/proc/", FormatInteger(cast(s64)pid, buffer[:]), "/mem"]
|
||||
path: [64]u8
|
||||
if !CopyCString(TextDetach(TextJoin(parts[:], "")), path[:]) { return }
|
||||
fd := Open(*path[0], 0)
|
||||
if fd < 0 { return }
|
||||
unused VecResize(profile.image, cast(s64)(end - begin))
|
||||
if PreadRaw(fd, *profile.image[0], end - begin, cast(s64)begin) == cast(s64)(end - begin) { profile.image_base = begin }
|
||||
else { unused VecResize(profile.image, 0) }
|
||||
unused Close(fd)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
Trace :: (request: s64, pid: s32, address: u64, data: u64) -> bool {
|
||||
error := Errno()
|
||||
error[0] = 0
|
||||
result := Ptrace(request, pid, address, data)
|
||||
return result != -1 || Errno()[0] == 0
|
||||
}
|
||||
|
||||
#scope_export
|
||||
TeacherSample :: struct { address: u64; count: s64 }
|
||||
TeacherProfile :: struct {
|
||||
samples: Vec(TeacherSample)
|
||||
total: s64
|
||||
runs: s64
|
||||
valid: bool
|
||||
exit_code: s32
|
||||
// With maps requested: the child's first anonymous executable mapping
|
||||
// (an in-process native image) and its address.
|
||||
image_base: u64
|
||||
image: Vec(u8)
|
||||
}
|
||||
|
||||
TeacherSampleRun :: (path: string, profile: *TeacherProfile) -> bool {
|
||||
arguments := string.[path]
|
||||
return TeacherSampleProcess(arguments[:], profile, null)
|
||||
}
|
||||
|
||||
// Samples ARGUMENTS[0] run with ARGUMENTS. MAPS, when not null, receives
|
||||
// the child's /proc maps at its 64th sample, so samples in anonymous code
|
||||
// (an in-process native image) and in shared libraries can be attributed.
|
||||
TeacherSampleProcess :: (arguments: []string, profile: *TeacherProfile, maps: *Vec(u8)) -> bool {
|
||||
if arguments.count < 1 || arguments.count > 15 { return false }
|
||||
text: [8192]u8
|
||||
sink: [16]u8
|
||||
pointers: [16]*u8
|
||||
used: s64 = 0
|
||||
for index: cast(s64)0..arguments.count - 1 {
|
||||
if used + arguments[index].count + 1 > text.count || !CopyCString(arguments[index], text[used:]) { return false }
|
||||
pointers[index] = *text[used]
|
||||
used += arguments[index].count + 1
|
||||
}
|
||||
pointers[arguments.count] = null
|
||||
if !CopyCString("/dev/null", sink[:]) { return false }
|
||||
cpath := pointers[0]
|
||||
pid := Fork()
|
||||
if pid < 0 { return false }
|
||||
if pid == 0 {
|
||||
fd := Open(*sink[0], 1)
|
||||
if fd < 0 { Exit(120); return false }
|
||||
unused Dup(fd, 1); unused Dup(fd, 2); unused Close(fd)
|
||||
if !Trace(0, 0, 0, 0) { Exit(121); return false }
|
||||
unused Exec(cpath, *pointers[0])
|
||||
Exit(122)
|
||||
return false
|
||||
}
|
||||
reaped := false
|
||||
status: s32
|
||||
defer {
|
||||
if !reaped {
|
||||
// Confirm this PID is still our unreaped child before signaling.
|
||||
pending := WaitPid(pid, *status, 1)
|
||||
if pending == 0 || pending == pid && (status & 255) == 127 {
|
||||
unused Kill(pid, 9)
|
||||
unused Wait(pid, *status)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !Wait(pid, *status) { return false }
|
||||
if (status & 255) != 127 { reaped = true; return false }
|
||||
// EXITKILL ensures a stopped child cannot outlive a failed tracer.
|
||||
if !Trace(16896, pid, 0, 1048576) { return false }
|
||||
saved: Registers
|
||||
if !Trace(12, pid, 0, cast(u64)*saved) { return false }
|
||||
ip := saved.words[16]
|
||||
error := Errno()
|
||||
error[0] = 0
|
||||
original := Ptrace(1, pid, ip, 0)
|
||||
if original == -1 && Errno()[0] != 0 { return false }
|
||||
// syscall is two bytes; single-step it with setitimer(ITIMER_PROF).
|
||||
patched := (cast(u64)original & ~cast(u64)65535) | 1295
|
||||
if !Trace(4, pid, ip, patched) { return false }
|
||||
timer := saved.words[19] - 128
|
||||
values: [4]u64 = .[0, 1000, 0, 1000]
|
||||
for index: 0..3 { if !Trace(5, pid, timer + cast(u64)index * 8, values[index]) { return false } }
|
||||
registers := saved
|
||||
registers.words[10] = 38
|
||||
registers.words[14] = 2
|
||||
registers.words[13] = timer
|
||||
registers.words[12] = 0
|
||||
if !Trace(13, pid, 0, cast(u64)*registers) || !Trace(9, pid, 0, 0) || !Wait(pid, *status) { return false }
|
||||
if (status & 255) != 127 || !Trace(12, pid, 0, cast(u64)*registers) || registers.words[10] != 0 { return false }
|
||||
if !Trace(4, pid, ip, cast(u64)original) || !Trace(13, pid, 0, cast(u64)*saved) || !Trace(7, pid, 0, 0) { return false }
|
||||
while Wait(pid, *status) {
|
||||
if (status & 127) == 0 {
|
||||
reaped = true
|
||||
profile.exit_code = (status >> 8) & 255
|
||||
profile.runs += 1
|
||||
return true
|
||||
}
|
||||
if (status & 255) != 127 { reaped = true; return false }
|
||||
signal_number := (status >> 8) & 255
|
||||
if signal_number == 27 {
|
||||
if !Trace(12, pid, 0, cast(u64)*registers) { return false }
|
||||
address := registers.words[16]
|
||||
found := false
|
||||
for index: 0..profile.samples.count - 1 {
|
||||
if profile.samples[index].address == address { profile.samples[index].count += 1; found = true; break }
|
||||
}
|
||||
if !found { unused VecPush(profile.samples, TeacherSample.{address = address, count = 1}) }
|
||||
profile.total += 1
|
||||
if maps != null && profile.total == 64 {
|
||||
buffer: [32]u8
|
||||
parts := string.["/proc/", FormatInteger(cast(s64)pid, buffer[:]), "/maps"]
|
||||
path := TextDetach(TextJoin(parts[:], ""))
|
||||
captured: Vec(u8)
|
||||
if ReadFileInto(path, *captured) {
|
||||
CaptureImage(pid, TextView(captured[:]), profile)
|
||||
unused VecResize(<<maps, 0)
|
||||
for byte: captured { unused VecPush(<<maps, byte) }
|
||||
}
|
||||
VecFree(captured)
|
||||
}
|
||||
signal_number = 0
|
||||
}
|
||||
if !Trace(7, pid, 0, cast(u64)signal_number) { return false }
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
TeacherSampleProgram :: (path: string, expected: s32) -> TeacherProfile {
|
||||
profile: TeacherProfile
|
||||
valid := true
|
||||
for run: 0..29 {
|
||||
if !TeacherSampleRun(path, *profile) || profile.exit_code != expected { valid = false; break }
|
||||
if profile.total >= 150 { break }
|
||||
}
|
||||
profile.valid = valid
|
||||
return profile
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// Mine candidates only. Matching two assembly idioms proves nothing about
|
||||
// program equivalence; the learning verifier must certify their semantics.
|
||||
#import "c_teacher_assembly"
|
||||
#import "std/text_tools"
|
||||
using Vectors :: #import "std/vec"
|
||||
|
||||
TeacherRewrite :: struct { factor: s64; native: string; teacher: string }
|
||||
|
||||
TeacherLeaFactor :: (operands: string) -> s64 {
|
||||
left := TextFind(operands, "[")
|
||||
right := TextFind(operands, "]")
|
||||
if left < 0 || right < left { return 0 }
|
||||
body := operands[left + 1:right]
|
||||
plus := TextFind(body, "+")
|
||||
if plus <= 0 { return 0 }
|
||||
base := body[:plus]
|
||||
index := body[plus + 1:]
|
||||
star := TextFind(index, "*")
|
||||
if star < 0 { return ifx base == index then 2 else 0 }
|
||||
if index[:star] != base { return 0 }
|
||||
scale, valid := TeacherHex(index[star + 1:])
|
||||
if !valid || scale != 1 && scale != 2 && scale != 4 && scale != 8 { return 0 }
|
||||
return 1 + scale
|
||||
}
|
||||
|
||||
TeacherIdiomFactor :: (instruction: TeacherInstruction) -> s64 {
|
||||
if instruction.mnemonic == "lea" { return TeacherLeaFactor(instruction.operands) }
|
||||
parts := TextSplit(instruction.operands, ",")
|
||||
if parts.count != 2 { return 0 }
|
||||
if instruction.mnemonic == "add" && TextTrim(parts[0]) == TextTrim(parts[1]) { return 2 }
|
||||
if instruction.mnemonic != "shl" && instruction.mnemonic != "sal" { return 0 }
|
||||
shift, valid := TeacherHex(TextTrim(parts[1]))
|
||||
if !valid || shift < 1 || shift > 30 { return 0 }
|
||||
return cast(s64)(cast(u64)1 << cast(u64)shift)
|
||||
}
|
||||
|
||||
TeacherMineRewrites :: (native: []TeacherInstruction, begin: s64, end: s64,
|
||||
teacher: []TeacherInstruction, cbegin: s64, cend: s64) -> Vec(TeacherRewrite) {
|
||||
result: Vec(TeacherRewrite)
|
||||
for instruction: native {
|
||||
if instruction.address < begin || instruction.address >= end || instruction.mnemonic != "imul" { continue }
|
||||
operands := TextSplit(instruction.operands, ",")
|
||||
if operands.count != 3 { continue }
|
||||
factor, valid := TeacherHex(TextTrim(operands[2]))
|
||||
if !valid || factor < 2 { continue }
|
||||
duplicate := false
|
||||
for rule: result { if rule.factor == factor { duplicate = true; break } }
|
||||
if duplicate { continue }
|
||||
for candidate: teacher {
|
||||
if candidate.address < cbegin || candidate.address >= cend || TeacherIdiomFactor(candidate) != factor { continue }
|
||||
n := string.[instruction.mnemonic, " ", instruction.operands]
|
||||
c := string.[candidate.mnemonic, " ", candidate.operands]
|
||||
unused VecPush(result, TeacherRewrite.{factor = factor,
|
||||
native = TextDetach(TextJoin(n[:], "")), teacher = TextDetach(TextJoin(c[:], ""))})
|
||||
break
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// Offline calibration of the bounded leaf pass. Run through bench/bench.zi.
|
||||
// Uses the teacher's long, checksum-checking kernel wrappers and generated C.
|
||||
#import, file "../cmd/compiler_exec_link.zi";
|
||||
#import, file "../cmd/compiler_opt.zi";
|
||||
#import, file "../cmd/compiler_lowered_ir.zi";
|
||||
#import, file "../cmd/compiler_bundle.zi";
|
||||
#import, file "../cmd/compiler_learning.zi";
|
||||
#import "std/byte_text_linux"
|
||||
#import "std/environment_linux"
|
||||
#import "std/file"
|
||||
#import "std/file_tree_linux"
|
||||
#import "std/json_document"
|
||||
#import "std/number_text"
|
||||
#import "std/process_run_linux"
|
||||
#import "std/text_tools"
|
||||
#import "std/timer_linux"
|
||||
#import "std/vec"
|
||||
|
||||
#scope_file
|
||||
Join :: (a: string, b: string) -> string { parts := string.[a, b]; return TextDetach(TextJoin(parts[:], "")) }
|
||||
Number :: (n: s64) -> string { digits: [32]u8; return Join("", FormatInteger(n, digits[:])) }
|
||||
Capture :: (arguments: []string) -> (text: string, code: s32) {
|
||||
run: ProcessRun
|
||||
options := ProcessOptions.{arguments = arguments, capture_output = true, merge_error = true}
|
||||
if !RunProcess(options, *run) { return "cannot start child", 127 }
|
||||
return TextDetach(BuilderFinish(run.output)), run.code
|
||||
}
|
||||
Require :: (arguments: []string) -> bool {
|
||||
text, code := Capture(arguments)
|
||||
if code != 0 { print("calibration failed (%): %\n%\n", code, TextJoin(arguments, " "), text); return false }
|
||||
return true
|
||||
}
|
||||
Digest :: (path: string) -> string {
|
||||
command := string.["sha256sum", "--", path]
|
||||
text, code := Capture(command[:])
|
||||
return ifx code == 0 && text.count >= 64 then text[:64] else ""
|
||||
}
|
||||
TextField :: (document: *JsonDocument, root: s32, key: string, value: string) {
|
||||
JsonSet(document, root, key, JsonNewStringCopy(document, value))
|
||||
}
|
||||
Policy :: (document: *JsonDocument, row: s32, leaf: s32) {
|
||||
policy := JsonNewObject(document)
|
||||
JsonSet(document, row, "policy", policy)
|
||||
JsonSet(document, policy, "leaf_operations", JsonNewInteger(document, leaf))
|
||||
JsonSet(document, policy, "unroll_factor", JsonNewInteger(document, 1))
|
||||
JsonSet(document, policy, "block_layout", JsonNewInteger(document, 1))
|
||||
JsonSet(document, policy, "allocation", JsonNewInteger(document, 0))
|
||||
}
|
||||
|
||||
// Clone/verify and vary only the leaf pass. The canonical input has already
|
||||
// passed the ordinary optimizer; running other passes again would confound it.
|
||||
Variant :: (source: string, output: string, leaf: s32) -> bool {
|
||||
bytes, found := ReadEntireFile(source)
|
||||
if !found { return false }
|
||||
decoded: ZxExecOwner
|
||||
defer ZxExecReadFree(*decoded)
|
||||
if ZxExecRead(*decoded, bytes, LirDefaultLimits()).problem != .None || decoded.assets != 0 { return false }
|
||||
if ZxExecReadProgram(*decoded).checks { return false }
|
||||
optimized: LirOptOwner
|
||||
defer LirOptFree(*optimized)
|
||||
options := LirOptOptions.{maximum_rounds = 1, inline_leaf_operations = leaf}
|
||||
result := LirOptBuild(*optimized, ZxExecReadProgram(*decoded), LirDefaultLimits(), options)
|
||||
if result.problem != .None { return false }
|
||||
program := LirOptProgram(*optimized)
|
||||
assets: [0]Asset
|
||||
empty: []u8
|
||||
measured := ZxExecWrite(program, assets[:], empty, TextView(decoded.interface[:]))
|
||||
if measured.problem != .None { return false }
|
||||
encoded: Vec(u8)
|
||||
defer VecFree(encoded)
|
||||
if !VecResize(encoded, measured.size) { return false }
|
||||
written := ZxExecWrite(program, assets[:], encoded[:], TextView(decoded.interface[:]))
|
||||
if written.problem != .None || written.size != measured.size { return false }
|
||||
print("leaf=% inlined_calls=% source=%\n", leaf, result.counters.inline_leaf.instructions, source)
|
||||
return WriteEntireFile(output, TextView(encoded[:]))
|
||||
}
|
||||
Time :: (executable: string) -> s64 {
|
||||
command := string.[executable]
|
||||
options := ProcessOptions.{arguments = command[:], output_path = "/dev/null", error_path = "/dev/null"}
|
||||
run: ProcessRun
|
||||
start := MonotonicNanoseconds()
|
||||
if !RunProcess(options, *run) || run.code != 42 { return -1 }
|
||||
return MonotonicNanoseconds() - start
|
||||
}
|
||||
Record :: (corpus: string, bundle: string, elf: string, original: string, compiler: string) -> string {
|
||||
format := Join("zx", Join(Number(ExecutableVersionNumber()), Join("-lir", Number(LirVersion))))
|
||||
zx_digest := Digest(bundle)
|
||||
native_digest := Digest(elf)
|
||||
relative := Join(format, Join("/", Join(zx_digest, Join("/x86_64-", native_digest))))
|
||||
stem := Join(corpus, Join("/", relative))
|
||||
folder := PathParent(stem)
|
||||
if !CreateDirectories(folder) { return "" }
|
||||
copy_zx := string.["cp", "--", bundle, Join(folder, "/program.zx")]
|
||||
copy_elf := string.["cp", "--", elf, Join(stem, ".elf")]
|
||||
map := string.["build/bin/zx2native", "--emit", "map", "-o", Join(stem, ".map.json"), bundle]
|
||||
if !Require(copy_zx[:]) || !Require(copy_elf[:]) || !Require(map[:]) { return "" }
|
||||
document: JsonDocument
|
||||
defer JsonReset(*document)
|
||||
root := JsonNewObject(*document)
|
||||
TextField(*document, root, "format", format)
|
||||
TextField(*document, root, "target", "x86_64")
|
||||
TextField(*document, root, "platform", "linux")
|
||||
TextField(*document, root, "zx2native_sha256", compiler)
|
||||
TextField(*document, root, "input_sha256", original)
|
||||
TextField(*document, root, "producer", "c-teacher-tune")
|
||||
if !WriteEntireFile(Join(stem, ".record.json"), JsonWrite(*document, root, JsonCompactStyle())) { return "" }
|
||||
return Join(relative, ".record.json")
|
||||
}
|
||||
Epoch :: (work: string) -> string {
|
||||
// Hash the source inventory too: exact tool identities alone cannot detect
|
||||
// edits awaiting a rebuild. Include untracked learning modules explicitly.
|
||||
command := string.["git", "ls-files", "cmd", "std", "Makefile", "assembly.mk", "bench"]
|
||||
inventory, code := Capture(command[:])
|
||||
if code != 0 { return "" }
|
||||
paths := TextLines(inventory)
|
||||
defer VecFree(paths)
|
||||
text: Vec(u8)
|
||||
for path: paths {
|
||||
if path == "" || TextHasPrefix(path, "bench/results/") { continue }
|
||||
hash := Digest(path)
|
||||
if hash.count != 64 { VecFree(text); return "" }
|
||||
BuilderAppend(text, path); BuilderAppend(text, hash)
|
||||
}
|
||||
extra := string.["build/bin/zi2c", "build/bin/zi2zx", "build/bin/zx2native",
|
||||
"cmd/compiler_opt_inline.zi", "cmd/compiler_learning.zi", "cmd/compiler_learning_policy.zi",
|
||||
"cmd/compiler_learning_table.zi", "bench/c_teacher_tuning.zi"]
|
||||
for path: extra {
|
||||
hash := Digest(path)
|
||||
if hash.count != 64 { VecFree(text); return "" }
|
||||
BuilderAppend(text, path); BuilderAppend(text, hash)
|
||||
}
|
||||
receipt := Join(work, "/source-epoch")
|
||||
return ifx WriteEntireFile(receipt, BuilderFinish(text)) then Digest(receipt) else ""
|
||||
}
|
||||
|
||||
#scope_export
|
||||
#program_export
|
||||
main :: (argc: s32, argv: **u8) -> s32 {
|
||||
output: string; corpus: string
|
||||
if argc != 5 { print("usage: c-teacher-tune --output FILE --corpus DIR\n"); return 1 }
|
||||
for index: cast(s32)1..argc - 1 {
|
||||
value := TextFromCString(argv[index])
|
||||
if value == "--output" && index + 1 < argc { output = TextFromCString(argv[index + 1]) }
|
||||
if value == "--corpus" && index + 1 < argc { corpus = TextFromCString(argv[index + 1]) }
|
||||
}
|
||||
if output == "" || corpus == "" || EnvironmentText("ZIRAN_LEARN") != "off" { return 1 }
|
||||
policy := LearningTuningChoice()
|
||||
if policy.leaf_operations != 0 || policy.block_layout != 1 {
|
||||
print("calibration needs the baseline leaf/layout table and freshly prepared teacher inputs\n"); return 1
|
||||
}
|
||||
work := "build/c-teacher/tuning"
|
||||
if !CreateDirectories(work) || !CreateDirectories(corpus) { return 1 }
|
||||
epoch := Epoch(work)
|
||||
compiler := Digest("build/bin/zx2native")
|
||||
host := string.["hostname"]
|
||||
hostname, host_code := Capture(host[:])
|
||||
if epoch.count != 64 || compiler.count != 64 || host_code != 0 { return 1 }
|
||||
document: JsonDocument
|
||||
defer JsonReset(*document)
|
||||
root := JsonNewObject(*document)
|
||||
JsonSet(*document, root, "schema_version", JsonNewInteger(*document, 1))
|
||||
JsonSet(*document, root, "checks", JsonNewBool(*document, false))
|
||||
TextField(*document, root, "target", "x86_64-linux")
|
||||
TextField(*document, root, "learning", "off")
|
||||
TextField(*document, root, "host", TextTrim(hostname))
|
||||
TextField(*document, root, "source_epoch_sha256", epoch)
|
||||
TextField(*document, root, "method", "paired process wall time; 1024 checksum-checked kernel calls; includes startup; 11 samples")
|
||||
rows := JsonNewArray(*document)
|
||||
JsonSet(*document, root, "measurements", rows)
|
||||
names := string.["Sieve", "Records", "Hash", "Vectors", "Calls", "Printing"]
|
||||
for name: names {
|
||||
folder := Join(work, Join("/", name))
|
||||
if !CreateDirectories(folder) { return 1 }
|
||||
original := Join("build/c-teacher/", Join(name, ".zx"))
|
||||
source := Join("build/c-teacher/teacher_", Join(name, ".zi"))
|
||||
reference_folder := Join(folder, "/c")
|
||||
reference := Join(reference_folder, Join("/teacher_", name))
|
||||
c := string.["env", "CFLAGS=-O2", "build/bin/zi2c", "--exe", "--root", "build/c-teacher", "--module-path", "bench", "--module-path", "std",
|
||||
"--entry", Join("teacher_", Join(name, ":main")), "-o", reference_folder, source]
|
||||
if !Require(c[:]) { return 1 }
|
||||
for leaf: cast(s32)0..cast(s32)1 {
|
||||
bundle := Join(folder, Join("/policy-", Join(Number(leaf), ".zx")))
|
||||
native := Join(folder, Join("/policy-", Number(leaf)))
|
||||
if !Variant(original, bundle, leaf) { return 1 }
|
||||
encode := string.["build/bin/zx2native", "-o", native, bundle]
|
||||
if !Require(encode[:]) { return 1 }
|
||||
record := Record(corpus, bundle, native, Digest(original), compiler)
|
||||
if record == "" || Time(native) <= 0 || Time(reference) <= 0 { return 1 }
|
||||
row := JsonNewObject(*document)
|
||||
unused JsonAppend(*document, rows, row)
|
||||
TextField(*document, row, "workload", name)
|
||||
TextField(*document, row, "input_sha256", Digest(original))
|
||||
TextField(*document, row, "zx_sha256", Digest(bundle))
|
||||
TextField(*document, row, "native_sha256", Digest(native))
|
||||
TextField(*document, row, "compiler_sha256", compiler)
|
||||
TextField(*document, row, "corpus_record", record)
|
||||
TextField(*document, row, "checksum", "42"); TextField(*document, row, "c_checksum", "42")
|
||||
file := OpenRead(native)
|
||||
if !file.valid { return 1 }
|
||||
JsonSet(*document, row, "code_bytes", JsonNewInteger(*document, FileSize(file)))
|
||||
CloseFile(file)
|
||||
Policy(*document, row, leaf)
|
||||
ns := JsonNewArray(*document); cs := JsonNewArray(*document)
|
||||
JsonSet(*document, row, "native_ns", ns); JsonSet(*document, row, "c_ns", cs)
|
||||
for sample: 0..10 {
|
||||
// Alternate native/reference order to reduce drift bias.
|
||||
n: s64; ctime: s64
|
||||
if sample % 2 == 0 { n = Time(native); ctime = Time(reference) }
|
||||
else { ctime = Time(reference); n = Time(native) }
|
||||
if n <= 0 || ctime <= 0 { return 1 }
|
||||
unused JsonAppend(*document, ns, JsonNewInteger(*document, n))
|
||||
unused JsonAppend(*document, cs, JsonNewInteger(*document, ctime))
|
||||
}
|
||||
}
|
||||
}
|
||||
if Epoch(work) != epoch || Digest("build/bin/zx2native") != compiler { print("compiler/source changed; calibration rejected\n"); return 1 }
|
||||
if !WriteEntireFile(output, JsonWrite(*document, root, JsonPythonStyle(2))) { return 1 }
|
||||
print("Saved measured leaf policies: %, corpus %\n", output, corpus)
|
||||
return 0
|
||||
}
|
||||
+28
-19
@@ -406,7 +406,7 @@ def main():
|
||||
if not cc or not hasattr(os, 'wait4'):
|
||||
parser.error('a C compiler and POSIX wait4 are required')
|
||||
bins = args.bin_dir.resolve()
|
||||
required = ['ziran', 'zi2zir', 'zi2c', 'zi2go', 'zi2zx']
|
||||
required = ['ziran', 'zi2zir', 'zi2c', 'zi2go', 'zi2zx', 'zx2wasm']
|
||||
for name in required:
|
||||
if not (bins / name).is_file():
|
||||
parser.error(f'missing compiler tool: {bins / name}; build the toolchain first')
|
||||
@@ -477,7 +477,7 @@ def main():
|
||||
'correctness': 'Python oracle, all native vectors, then source/saved IR small bundle outputs; all before timing',
|
||||
'warm_native': 'fresh process, one full untimed call on identical input, then one timed call; both results checked',
|
||||
'cold_process': 'first call in a fresh process, no cache flush; process wall/CPU include startup and kernel initialization',
|
||||
'portable_process': 'fresh portable VM process for each sample; includes bundle load/verification and interpreter startup',
|
||||
'portable_process': 'fresh portable engine process for each sample; includes bundle load/verification and interpreter startup',
|
||||
'kernel_region': 'initialization, scalar algorithm, checksum and call overhead; excludes code generation, build and process startup',
|
||||
'compile': 'single separately recorded build phase, no claim of cold or repeated compile performance'},
|
||||
limitations=[
|
||||
@@ -500,10 +500,10 @@ def main():
|
||||
metadata['toolchain'] = {'cc': invoke([cc, '--version'], 'metadata', 'C compiler version')[0],
|
||||
'cc_target': invoke([cc, '-dumpmachine'], 'metadata', 'C compiler target')[0],
|
||||
'python': sys.version}
|
||||
tool_files = [bins / name for name in required] + [bins / 'zi2wasm', bins.parent / 'libziran.a']
|
||||
tool_files = [bins / name for name in required] + [bins.parent / 'libziran.a']
|
||||
metadata['tools'] = {str(path): dict(sha256=digest(path), size=path.stat().st_size, mtime_ns=path.stat().st_mtime_ns)
|
||||
for path in tool_files if path.is_file()}
|
||||
inputs = [Path(__file__), ROOT / 'tests/compiler_kernel_benchmarks.sh',
|
||||
inputs = [Path(__file__), ROOT / 'bench/compiler_kernel_benchmarks.sh',
|
||||
FIXTURES / 'codec_kernels.zi', FIXTURES / 'codec_kernels_layout.zi']
|
||||
metadata['input_hashes'] = {str(path.relative_to(ROOT)): digest(path) for path in inputs}
|
||||
# Capture compiler/library source identity without loading source contents.
|
||||
@@ -621,7 +621,7 @@ def main():
|
||||
wasm_python = importlib.util.find_spec('wasmtime') is not None
|
||||
browser = shutil.which('firefox') or shutil.which('chromium')
|
||||
wasm_engine = wasm_python or bool(browser)
|
||||
capabilities['wasm'] = dict(generator=str(bins / 'zi2wasm'), execution='available' if wasm_engine else 'unavailable',
|
||||
capabilities['wasm'] = dict(generator=f"{bins / 'zi2zx'} | {bins / 'zx2wasm'}", execution='available' if wasm_engine else 'unavailable',
|
||||
runner='Python Wasmtime' if wasm_python else f'private headless {Path(browser).name}' if browser else None,
|
||||
reason='' if wasm_engine else 'No Python wasmtime binding, Firefox or Chromium executable; Node/npm/npx prohibited. Generated modules do not count as executed validation.')
|
||||
if wasm_python:
|
||||
@@ -634,18 +634,23 @@ def main():
|
||||
for function in ['Validate', *[kind + 'Bench' for kind in KERNELS]]:
|
||||
wanted = validation if function == 'Validate' else oracle(function[:-5], 8, 37)
|
||||
bundle = out / f'{form}-{function}.zx'
|
||||
invoke([ziran, 'bundle', '--root', root, '--entry', f'codec_kernels:{function}', '-o', bundle, entry], 'codegen', f'{form} {function} bundle')
|
||||
# `run --vm` is explicitly the portable interpreter, not native dispatch.
|
||||
command = [bins / 'zi2zx', 'run', '--vm', bundle]
|
||||
invoke([bins / 'zi2zx', '--root', root, '--entry', f'codec_kernels:{function}', '-o', bundle, entry], 'codegen', f'{form} {function} bundle')
|
||||
# A bundle runs on the portable instruction engine.
|
||||
command = [bins / 'zi2zx', 'run', bundle]
|
||||
actual = invoke(command, 'correctness', f'{form} portable {function}')[0]
|
||||
if actual != str(wanted):
|
||||
raise AssertionError(f'{form} portable {function}: {actual} != {wanted}')
|
||||
if function != 'Validate':
|
||||
portable.append((f'{form}-portable-{function[:-5]}', command, wanted))
|
||||
if (bins / 'zi2wasm').is_file():
|
||||
if (bins / 'zx2wasm').is_file():
|
||||
wasm = out / f'{form}-{function}.wasm'
|
||||
_, row, diagnostic = invoke([bins / 'zi2wasm', '--root', root, '--entry', f'codec_kernels:{function}',
|
||||
'-o', wasm, entry], 'codegen', f'{form} {function} Wasm', allow_failure=True)
|
||||
wasm_wire = out / f'{form}-{function}-wasm.zx'
|
||||
_, row, diagnostic = invoke([bins / 'zi2zx', '--target', 'wasm', '--root', root,
|
||||
'--entry', f'codec_kernels:{function}', '-o', wasm_wire, entry],
|
||||
'codegen', f'{form} {function} Wasm ZX', allow_failure=True)
|
||||
if not row['returncode']:
|
||||
_, row, diagnostic = invoke([bins / 'zx2wasm', '-o', wasm, wasm_wire],
|
||||
'codegen', f'{form} {function} Wasm', allow_failure=True)
|
||||
if row['returncode']:
|
||||
capabilities[f'wasm-{form}-{function}'] = {'generation': 'unsupported', 'execution': 'unavailable', 'reason': diagnostic, 'command': row}
|
||||
else:
|
||||
@@ -659,19 +664,23 @@ def main():
|
||||
if function != 'Validate':
|
||||
portable.append((f'{form}-wasm-{function[:-5]}', command, wanted))
|
||||
else:
|
||||
capabilities['wasm']['reason'] = 'zi2wasm tool is not built'
|
||||
capabilities['wasm']['reason'] = 'zx2wasm tool is not built'
|
||||
bundle = out / f'{form}-layout.zx'
|
||||
invoke([ziran, 'bundle', '--root', root, '--entry', 'codec_kernels_layout:Sizes', '-o', bundle, audit_entry], 'codegen', f'{form} logical size bundle')
|
||||
value = int(invoke([bins / 'zi2zx', 'run', '--vm', bundle], 'audit', f'{form} portable logical sizes')[0])
|
||||
invoke([bins / 'zi2zx', '--root', root, '--entry', 'codec_kernels_layout:Sizes', '-o', bundle, audit_entry], 'codegen', f'{form} logical size bundle')
|
||||
value = int(invoke([bins / 'zi2zx', 'run', bundle], 'audit', f'{form} portable logical sizes')[0])
|
||||
logical_fingerprint = 8 * 1000000 + 8 * 10000 + 16 * 100 + 24
|
||||
if value != logical_fingerprint:
|
||||
raise AssertionError(f'{form} portable size_of differs from TypeLayout: {value}')
|
||||
layout[f'{form}-portable-size-fingerprint'] = value
|
||||
if (bins / 'zi2wasm').is_file():
|
||||
if (bins / 'zx2wasm').is_file():
|
||||
wasm = out / f'{form}-layout.wasm'
|
||||
_, row, diagnostic = invoke([bins / 'zi2wasm', '--root', root, '--entry',
|
||||
'codec_kernels_layout:Sizes', '-o', wasm, audit_entry],
|
||||
'codegen', f'{form} Wasm layout audit', allow_failure=True)
|
||||
wasm_wire = out / f'{form}-layout-wasm.zx'
|
||||
_, row, diagnostic = invoke([bins / 'zi2zx', '--target', 'wasm', '--root', root,
|
||||
'--entry', 'codec_kernels_layout:Sizes', '-o', wasm_wire, audit_entry],
|
||||
'codegen', f'{form} Wasm layout ZX', allow_failure=True)
|
||||
if not row['returncode']:
|
||||
_, row, diagnostic = invoke([bins / 'zx2wasm', '-o', wasm, wasm_wire],
|
||||
'codegen', f'{form} Wasm layout audit', allow_failure=True)
|
||||
capabilities[f'wasm-{form}-layout'] = {'generation': 'unsupported' if row['returncode'] else 'succeeded',
|
||||
'execution': 'unavailable', 'reason': diagnostic, 'command': row}
|
||||
if not row['returncode'] and wasm_engine:
|
||||
@@ -787,7 +796,7 @@ def main():
|
||||
if digest(path) != identity['sha256']:
|
||||
raise RuntimeError(f'tool changed during run: {path}')
|
||||
capabilities['native-c'] = {'execution': 'validated', 'modes': ['dispatch', 'ZIRAN_NO_ASM']}
|
||||
capabilities['portable-zx'] = {'execution': 'validated', 'runner': str(bins / 'zi2zx') + ' run --vm'}
|
||||
capabilities['portable-zx'] = {'execution': 'validated', 'runner': str(bins / 'zi2zx') + ' run'}
|
||||
wasm_results = [value['execution'] for key, value in capabilities.items()
|
||||
if key.startswith('wasm-') and key.endswith('Bench')]
|
||||
if wasm_results and all(value == 'validated' for value in wasm_results):
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
#!/usr/bin/env -S ziran run --target=c
|
||||
// Time a full native rebuild. --profile records each make shell recipe.
|
||||
#import "std/byte_text_linux"
|
||||
#import "std/environment_linux"
|
||||
#import "std/file"
|
||||
#import "std/file_tree_linux"
|
||||
#import "std/float_text"
|
||||
#import "std/json_document"
|
||||
#import "std/number_text"
|
||||
#import "std/process_run_linux"
|
||||
#import "std/text_tools"
|
||||
#import "std/timer_linux"
|
||||
using Vectors :: #import "std/vec"
|
||||
|
||||
#scope_file
|
||||
libc_build :: #system_library "libc";
|
||||
ProcessId :: () -> s32 #foreign libc_build "getpid";
|
||||
TimeValue :: struct { seconds: isize; microseconds: isize }
|
||||
Usage :: struct { user: TimeValue; system: TimeValue; counters: [14]isize }
|
||||
GetUsage :: (kind: s32, usage: *Usage) -> s32 #foreign libc_build "getrusage";
|
||||
|
||||
Concat :: (left: string, right: string) -> string {
|
||||
parts: [2]string = .[left, right]
|
||||
return TextJoin(parts[:], "")
|
||||
}
|
||||
|
||||
Number :: (value: s64) -> string {
|
||||
bytes: [64]u8
|
||||
return TextDetach(TextCopy(FormatInteger(value, bytes[:])))
|
||||
}
|
||||
|
||||
PutText :: (doc: *JsonDocument, object: s32, key: string, value: string) {
|
||||
JsonSet(doc, object, key, JsonNewStringCopy(doc, value))
|
||||
}
|
||||
|
||||
PutInteger :: (doc: *JsonDocument, object: s32, key: string, value: s64) {
|
||||
JsonSet(doc, object, key, JsonNewInteger(doc, value))
|
||||
}
|
||||
|
||||
PutFloat :: (doc: *JsonDocument, object: s32, key: string, value: float64) {
|
||||
JsonSet(doc, object, key, JsonNewNumber(doc, Float64Repr(value)))
|
||||
}
|
||||
|
||||
Capture :: (arguments: []string, directory: string) -> string {
|
||||
options: ProcessOptions = .{arguments = arguments, directory = directory,
|
||||
capture_output = true, merge_error = true}
|
||||
run: ProcessRun
|
||||
if !RunProcess(options, *run) || run.code != 0 { return "" }
|
||||
return TextTrim(BuilderFinish(run.output))
|
||||
}
|
||||
|
||||
Fingerprint :: (repo: string) -> string {
|
||||
source_diff: [12]string = .["git", "diff", "--binary", "HEAD", "--", "Makefile",
|
||||
"cmd", "include", "std", "bootstrap", "scripts", "VERSION"]
|
||||
scratch := JoinPath(repo, "build/scratch")
|
||||
if !CreateDirectories(scratch) { return "" }
|
||||
difference := JoinPath(scratch, Concat("compiler-build-source-", Concat(Number(ProcessId()), ".diff")))
|
||||
if !WriteEntireFile(difference, Capture(source_diff[:], repo)) { return "" }
|
||||
hash_command: [2]string = .["sha256sum", difference]
|
||||
hash_text := Capture(hash_command[:], repo)
|
||||
RemoveFile(difference)
|
||||
return ifx hash_text.count >= 64 then hash_text[0:64] else ""
|
||||
}
|
||||
|
||||
ShellRecipe :: (argc: s32, argv: **u8) -> s32 {
|
||||
if argc < 4 || EnvironmentText("ZIRAN_BUILD_PROFILE") == "" { return 2 }
|
||||
command: Vec(string)
|
||||
VecPush(command, "/bin/sh")
|
||||
for index: 2..argc - 1 { VecPush(command, TextFromCString(argv[index])) }
|
||||
options: ProcessOptions = .{arguments = VecSlice(command, 0, command.count)}
|
||||
run: ProcessRun
|
||||
started := MonotonicNanoseconds()
|
||||
ok := RunProcess(options, *run)
|
||||
finished := MonotonicNanoseconds()
|
||||
doc: JsonDocument
|
||||
object := JsonNewObject(*doc)
|
||||
PutInteger(*doc, object, "pid", ProcessId())
|
||||
PutInteger(*doc, object, "started_ns", started)
|
||||
PutInteger(*doc, object, "finished_ns", finished)
|
||||
PutInteger(*doc, object, "wall_ns", finished - started)
|
||||
PutInteger(*doc, object, "exit_code", run.code)
|
||||
PutText(*doc, object, "command", TextJoin(VecSlice(command, 2, command.count), " "))
|
||||
name := Concat(Concat(Number(ProcessId()), "-"), Concat(Number(started), ".json"))
|
||||
record := JoinPath(EnvironmentText("ZIRAN_BUILD_PROFILE"), name)
|
||||
if !WriteEntireFile(record, JsonWrite(*doc, object, JsonPythonStyle(2))) {
|
||||
print("cannot write recipe profile: %\n", record)
|
||||
return 1
|
||||
}
|
||||
return ifx ok then run.code else 127
|
||||
}
|
||||
|
||||
CollectProfile :: (directory: string) -> bool {
|
||||
names: Vec(string)
|
||||
if !ListDirectory(directory, *names) { return false }
|
||||
defer { FreeDirectoryNames(*names) }
|
||||
collected: JsonDocument
|
||||
array := JsonNewArray(*collected)
|
||||
top: Vec(s32)
|
||||
for name: VecSlice(names, 0, names.count) {
|
||||
if !TextHasSuffix(name, ".json") { continue }
|
||||
text, found := ReadEntireFile(JoinPath(directory, name))
|
||||
document: JsonDocument
|
||||
if !found || !JsonRead(*document, text) { return false }
|
||||
node := JsonCopy(*collected, *document, document.root)
|
||||
if node < 0 || !JsonAppend(*collected, array, node) { return false }
|
||||
VecPush(top, node)
|
||||
index := top.count - 1
|
||||
value, value_ok := JsonInteger(*collected, JsonMember(*collected, node, "wall_ns"))
|
||||
if !value_ok { return false }
|
||||
while index > 0 {
|
||||
previous, previous_ok := JsonInteger(*collected, JsonMember(*collected, top[index - 1], "wall_ns"))
|
||||
if !previous_ok { return false }
|
||||
if previous >= value { break }
|
||||
top[index] = top[index - 1]
|
||||
top[index - 1] = node
|
||||
index -= 1
|
||||
}
|
||||
if top.count > 20 && !VecResize(top, 20) { return false }
|
||||
}
|
||||
summary: JsonDocument
|
||||
if JsonCount(*collected, array) == 0 { return false }
|
||||
slowest := JsonNewArray(*summary)
|
||||
for node: VecSlice(top, 0, top.count) {
|
||||
if !JsonAppend(*summary, slowest, JsonCopy(*summary, *collected, node)) { return false }
|
||||
}
|
||||
parent := PathParent(directory)
|
||||
if !WriteEntireFile(JoinPath(parent, "recipes.json"), JsonWrite(*collected, array, JsonCompactStyle())) ||
|
||||
!WriteEntireFile(JoinPath(parent, "slowest-recipes.json"), JsonWrite(*summary, slowest, JsonPythonStyle(2))) {
|
||||
return false
|
||||
}
|
||||
for name: VecSlice(names, 0, names.count) {
|
||||
if TextHasSuffix(name, ".json") && !RemoveFile(JoinPath(directory, name)) { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
#scope_export
|
||||
#program_export
|
||||
main :: (argc: s32, argv: **u8) -> s32 {
|
||||
if argc > 1 && TextFromCString(argv[1]) == "--shell" { return ShellRecipe(argc, argv) }
|
||||
if argc == 3 && TextFromCString(argv[1]) == "--collect-profile" {
|
||||
return ifx CollectProfile(TextFromCString(argv[2])) then 0 else 1
|
||||
}
|
||||
repo := PathParent(PathParent(EnvironmentText("ZIRAN_SCRIPT_FILE")))
|
||||
if repo == "" || !IsFile(JoinPath(repo, "Makefile")) { repo = ResolvePath(".") }
|
||||
if !IsFile(JoinPath(repo, "Makefile")) { print("run from the Ziran repository\n"); return 2 }
|
||||
nproc: [1]string = .["nproc"]
|
||||
cpus, count := IntegerPrefix(Capture(nproc[:], repo))
|
||||
if count == 0 { cpus = 2 }
|
||||
jobs := EnvironmentNumber("BUILD_QUEUE_JOBS", 0)
|
||||
if jobs < 1 {
|
||||
jobs = cpus / 2
|
||||
if jobs < 2 { jobs = 2 }
|
||||
if jobs > 16 { jobs = 16 }
|
||||
}
|
||||
output := JoinPath(repo, "bench/results/compiler-build")
|
||||
profile := false
|
||||
index: s32 = 1
|
||||
while index < argc {
|
||||
option := TextFromCString(argv[index])
|
||||
if option == "--help" {
|
||||
print("compiler_build.zi [--jobs N] [--out DIR] [--profile]\n")
|
||||
return 0
|
||||
}
|
||||
if option == "--profile" { profile = true; index += 1; continue }
|
||||
if index + 1 >= argc { print("% needs a value\n", option); return 2 }
|
||||
value := TextFromCString(argv[index + 1])
|
||||
if option == "--jobs" {
|
||||
parsed, valid := TextInteger(value)
|
||||
if !valid || parsed < 1 { print("--jobs must be positive\n"); return 2 }
|
||||
jobs = parsed
|
||||
} else if option == "--out" { output = value }
|
||||
else { print("unknown argument: %\n", option); return 2 }
|
||||
index += 2
|
||||
}
|
||||
if !CreateDirectories(output) { print("cannot create %\n", output); return 1 }
|
||||
output = ResolvePath(output)
|
||||
environment: [8]string = .["DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY",
|
||||
"DBUS_SESSION_BUS_ADDRESS", "MAKEFLAGS", "MFLAGS", "HARMONY_DESKTOP_RECOVERY=0",
|
||||
"ZIRAN_BUILD_PROFILE"]
|
||||
settings: Vec(string)
|
||||
for value: environment { VecPush(settings, value) }
|
||||
command: Vec(string)
|
||||
fixed: [4]string = .["make", "-B", Concat("-j", Number(jobs)), "all"]
|
||||
for value: fixed { VecPush(command, value) }
|
||||
if profile {
|
||||
directory := JoinPath(output, "recipes")
|
||||
if !CreateDirectories(directory) { return 1 }
|
||||
VecPush(settings, Concat("ZIRAN_BUILD_PROFILE=", directory))
|
||||
self := ResolvePath(TextFromCString(argv[0]))
|
||||
VecPush(command, Concat("SHELL=", self))
|
||||
VecPush(command, ".SHELLFLAGS=--shell -c")
|
||||
}
|
||||
git: [3]string = .["git", "rev-parse", "HEAD"]
|
||||
revision := Capture(git[:], repo)
|
||||
status: [3]string = .["git", "status", "--porcelain"]
|
||||
dirty := Capture(status[:], repo) != ""
|
||||
source_fingerprint := Fingerprint(repo)
|
||||
if source_fingerprint == "" { print("cannot fingerprint build inputs\n"); return 1 }
|
||||
compiler: [2]string = .["cc", "--version"]
|
||||
compiler_version := Capture(compiler[:], repo)
|
||||
log := JoinPath(output, "build.log")
|
||||
options: ProcessOptions = .{arguments = VecSlice(command, 0, command.count),
|
||||
directory = repo, environment = VecSlice(settings, 0, settings.count),
|
||||
output_path = log, merge_error = true}
|
||||
print("Fresh rebuild: %, % jobs\n", TextJoin(VecSlice(command, 0, command.count), " "), jobs)
|
||||
before: Usage; after: Usage
|
||||
GetUsage(-1, *before)
|
||||
run: ProcessRun
|
||||
started := MonotonicNanoseconds()
|
||||
ok := RunProcess(options, *run)
|
||||
elapsed := MonotonicNanoseconds() - started
|
||||
GetUsage(-1, *after)
|
||||
source_fingerprint_after := Fingerprint(repo)
|
||||
sources_unchanged := source_fingerprint_after == source_fingerprint
|
||||
text, found := ReadEntireFile(log)
|
||||
compilations: s64 = 0
|
||||
lines := TextLines(text)
|
||||
for line: VecSlice(lines, 0, lines.count) {
|
||||
if TextContains(line, " -c -o ") { compilations += 1 }
|
||||
}
|
||||
doc: JsonDocument
|
||||
object := JsonNewObject(*doc)
|
||||
PutInteger(*doc, object, "schema_version", 2)
|
||||
PutText(*doc, object, "implementation", "Ziran")
|
||||
PutText(*doc, object, "command", TextJoin(VecSlice(command, 0, command.count), " "))
|
||||
PutText(*doc, object, "revision", revision)
|
||||
PutText(*doc, object, "tracked_build_source_diff_sha256", source_fingerprint)
|
||||
PutText(*doc, object, "tracked_build_source_diff_sha256_after", source_fingerprint_after)
|
||||
JsonSet(*doc, object, "build_sources_unchanged", JsonNewBool(*doc, sources_unchanged))
|
||||
PutText(*doc, object, "compiler_version", compiler_version)
|
||||
PutText(*doc, object, "bootstrap_cflags", ifx EnvironmentText("BOOTSTRAP_CFLAGS") == ""
|
||||
then "-O0" else EnvironmentText("BOOTSTRAP_CFLAGS"))
|
||||
PutText(*doc, object, "final_cflags", ifx EnvironmentText("CFLAGS") == ""
|
||||
then "-O2" else EnvironmentText("CFLAGS"))
|
||||
PutInteger(*doc, object, "exit_code", run.code)
|
||||
PutFloat(*doc, object, "wall_seconds", cast(float64)elapsed / 1000000000.0)
|
||||
PutFloat(*doc, object, "user_cpu_seconds", cast(float64)(after.user.seconds - before.user.seconds) +
|
||||
cast(float64)(after.user.microseconds - before.user.microseconds) / 1000000.0)
|
||||
PutFloat(*doc, object, "system_cpu_seconds", cast(float64)(after.system.seconds - before.system.seconds) +
|
||||
cast(float64)(after.system.microseconds - before.system.microseconds) / 1000000.0)
|
||||
PutInteger(*doc, object, "parallel_jobs", jobs)
|
||||
PutInteger(*doc, object, "available_cpus", cpus)
|
||||
PutInteger(*doc, object, "c_compile_commands", compilations)
|
||||
JsonSet(*doc, object, "working_tree_dirty", JsonNewBool(*doc, dirty))
|
||||
JsonSet(*doc, object, "recipe_profile", JsonNewBool(*doc, profile))
|
||||
JsonSet(*doc, object, "measurement_valid", JsonNewBool(*doc,
|
||||
ok && run.code == 0 && found && elapsed >= 0 && sources_unchanged))
|
||||
PutText(*doc, object, "cache_state", "warm filesystem caches; make -B forces every build target")
|
||||
PutText(*doc, object, "includes", "all native compiler tools and libziran.a")
|
||||
PutText(*doc, object, "excludes", "queue waiting, benchmark compilation, tests, installation and website build")
|
||||
PutText(*doc, object, "log", "build.log")
|
||||
report := JsonWrite(*doc, object, JsonPythonStyle(2))
|
||||
history_path := JoinPath(output, "samples.jsonl")
|
||||
history, history_ok := ReadEntireFile(history_path)
|
||||
unused history_ok
|
||||
compact := JsonWrite(*doc, object, JsonCompactStyle())
|
||||
if !WriteEntireFile(JoinPath(output, "latest.json"), Concat(report, "\n")) ||
|
||||
!WriteEntireFile(history_path, Concat(history, Concat(compact, "\n"))) {
|
||||
print("cannot retain benchmark report\n"); return 1
|
||||
}
|
||||
if profile && !CollectProfile(JoinPath(output, "recipes")) {
|
||||
print("cannot collate recipe profiles\n"); return 1
|
||||
}
|
||||
print("%\n", report)
|
||||
if !ok || !found { return 127 }
|
||||
if !sources_unchanged { print("build inputs changed during measurement\n"); return 3 }
|
||||
return run.code
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
# Run on Alpha: build-queue -- sh bench/compiler_kernel_benchmarks.sh [options]
|
||||
set -eu
|
||||
repo=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS
|
||||
unset SESSION_MANAGER XDG_SESSION_ID XDG_SESSION_TYPE ZIRAN_PROFILE
|
||||
export YUE_DESKTOP_RECOVERY=0
|
||||
exec python3 "$repo/bench/codec_kernels.py" "$@"
|
||||
@@ -140,7 +140,7 @@ def main():
|
||||
*sorted(native.glob('*.c')), '-lm', '-o', binary], label, 'native-compile:c')
|
||||
run([binary], label, 'run:c', oracle)
|
||||
bundle = directory / form / 'program.zx'
|
||||
run([binaries/'zi2zx', 'bundle', '--root', root, '--entry', 'program:Answer', '-o', bundle, entry], label, 'bundle')
|
||||
run([binaries/'zi2zx', '--root', root, '--entry', 'program:Answer', '-o', bundle, entry], label, 'bundle')
|
||||
run([binaries/'zi2zx', 'run', bundle], label, 'run:vm', oracle)
|
||||
(directory / 'fixture-hashes.json').write_text(json.dumps(
|
||||
{str(path.relative_to(directory)): digest(path) for path in source.glob('*.zi')}, indent=2) + '\n')
|
||||
|
||||
@@ -210,7 +210,7 @@ def main():
|
||||
for form, root, file in [('source', output, entry), ('saved', output/'ir', output/'ir/counts.zir')]:
|
||||
generated = output/form
|
||||
repeated([binaries/'zi2c', '--root', root, '-o', generated, file], f'{form} emit C')
|
||||
repeated([binaries/'zi2zx', 'bundle', '--root', root, '--entry', 'counts:Answer',
|
||||
repeated([binaries/'zi2zx', '--root', root, '--entry', 'counts:Answer',
|
||||
'-o', output/f'{form}.zx', file], f'{form} bundle')
|
||||
host = generated/'host.c'
|
||||
host.write_text('#include "counts.h"\n#include <stdio.h>\n#include <stdlib.h>\n'
|
||||
|
||||
@@ -72,8 +72,8 @@ def main():
|
||||
bundle = directory/'values.zx'
|
||||
commands = [
|
||||
[ROOT/'build/bin/zi2zir', '--root', directory, '-o', directory/'ir', entry],
|
||||
[ROOT/'build/bin/zi2zx', 'bundle', '--root', directory, '--entry', 'values:Answer', '-o', bundle, entry],
|
||||
[ROOT/'build/bin/zi2zx', 'bundle', '--root', directory/'ir', '--entry', 'values:Answer',
|
||||
[ROOT/'build/bin/zi2zx', '--root', directory, '--entry', 'values:Answer', '-o', bundle, entry],
|
||||
[ROOT/'build/bin/zi2zx', '--root', directory/'ir', '--entry', 'values:Answer',
|
||||
'-o', directory/'saved.zx', directory/'ir/values.zir'],
|
||||
]
|
||||
for argv in commands:
|
||||
|
||||
@@ -32,14 +32,14 @@ typedef struct State { size_t calls, count; } State;
|
||||
typedef struct Context { size_t index; const char *function; State *state; } Context;
|
||||
|
||||
static int host_call(void *opaque, const char *module, const char *function,
|
||||
const VmHostValue *args, int count, VmHostValue *result)
|
||||
const HostValue *args, int count, HostValue *result)
|
||||
{
|
||||
Context *context = opaque;
|
||||
assert(strcmp(module, "api") == 0 && strcmp(function, context->function) == 0);
|
||||
assert(context->state->calls % context->state->count == context->index);
|
||||
assert(count == 1 && args[0].kind == VM_HOST_INTEGER);
|
||||
assert(count == 1 && args[0].kind == HOST_INTEGER);
|
||||
context->state->calls++;
|
||||
result->kind = VM_HOST_INTEGER;
|
||||
result->kind = HOST_INTEGER;
|
||||
result->integer = (int64_t)(((uint64_t)args[0].integer * 48271 + context->index + 1) & INT64_MAX);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# JSON string scanning and parsing
|
||||
|
||||
The 0.4.2 JSON readers share an allocation-free scanner that examines complete
|
||||
16-byte blocks through portable SIMD operations. Unescaped text remains a borrowed
|
||||
view. Escape decoding, error positions, duplicate member behavior and secure
|
||||
cleanup retain their existing policies. Short strings use the scalar tail.
|
||||
`Simd.Load` and `Simd.LoadLow` accept immutable strings for `u8` vector lanes;
|
||||
whole-load bounds checks apply on C, Go and the portable engine.
|
||||
|
||||
Run `sh bench/json_document.sh`. It builds through Zi2c with the normal native
|
||||
executable defaults, constructs a 1 MiB ASCII string outside the timer and checks
|
||||
every parse. Eleven batches of 64 parses report raw nanoseconds per parse and
|
||||
symmetric inclusive-quartile 1.5×IQR exclusions. Process startup, compilation,
|
||||
input construction and transport are excluded. The scanner-only comparison is
|
||||
`bench/json_string_scan.zi`; it checks byte semantics before timing alternating
|
||||
reference and vector scans. Repeated scans use an opaque start and a compiler
|
||||
memory barrier to prevent loop hoisting.
|
||||
|
||||
The retained reports name the CPU, compiler inputs and exact runtime binaries.
|
||||
These are warm-cache local measurements on a busy Ryzen 9 9950X Linux machine;
|
||||
they do not establish performance on other architectures. Go and the portable
|
||||
VM use the same lane semantics; native vector instructions depend on the target.
|
||||
|
||||
The corresponding Xcoder diagnostic also measures the original preserved Codex
|
||||
V8 host. It times repeated `JSON.parse` inside that actual host and `JsonRead`
|
||||
inside the sandboxed Zi2c cell, separately from the complete cell round trip.
|
||||
The JavaScript timer has 1 ms resolution, amortized across 512 parses per batch.
|
||||
Both validate payload length and its first and last bytes on every parse.
|
||||
|
||||
A parser improvement does not remove native sandbox creation and executable
|
||||
startup. The original single-cell JSON benchmark must remain visible alongside
|
||||
the direct parser result. Cold custom compilation is reported separately from
|
||||
warm execution. Ordinary precompiled tool plans are a different workload and do
|
||||
not invoke the custom-cell compiler or sandboxed executable.
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
repo=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
ziran=${1:-$repo/build/bin/ziran}
|
||||
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS
|
||||
cd "$repo"
|
||||
output="$repo/build/benchmarks/json-document"
|
||||
"$ziran" build --target=c --root bench --entry json_document:main --exe -o "$output" bench/json_document.zi
|
||||
nice -n 19 "$output/json_document"
|
||||
@@ -0,0 +1,43 @@
|
||||
// A direct JSON parser benchmark: construction, compilation and process startup
|
||||
// are outside the timer. Every parse result is checked; input remains alive.
|
||||
using V :: #import "std/vec"
|
||||
using J :: #import "std/json_document"
|
||||
using T :: #import "std/timer_linux"
|
||||
#import "benchmark_statistics"
|
||||
|
||||
Measure :: (text: string, length: s64) -> float64 {
|
||||
document: JsonDocument
|
||||
defer JsonReset(*document)
|
||||
started := MonotonicNanoseconds()
|
||||
for iteration: 0..63 {
|
||||
if !JsonRead(*document,text) { return -1.0 }
|
||||
payload := JsonString(*document,JsonMember(*document,document.root,"payload"))
|
||||
if payload.count != length || payload[0] != 120 || payload[length - 1] != 120 { return -1.0 }
|
||||
}
|
||||
return cast(float64)(MonotonicNanoseconds() - started) / 64.0
|
||||
}
|
||||
|
||||
Numbers :: (values: []float64) { for i: 0..values.count - 1 { if i > 0 { print(",") }; print("%",values[i]) } }
|
||||
Indices :: (values: []s64) { for i: 0..values.count - 1 { if i > 0 { print(",") }; print("%",values[i]) } }
|
||||
|
||||
#program_export
|
||||
main :: () -> s32 {
|
||||
bytes: Vec(u8)
|
||||
prefix := "{\"payload\":\""
|
||||
suffix := "\"}"
|
||||
length: s64 = 1048576
|
||||
if !VecResize(bytes,prefix.count + length + suffix.count) { return 1 }
|
||||
for i: 0..prefix.count - 1 { bytes[i] = prefix[i] }
|
||||
for i: 0..length - 1 { bytes[prefix.count + i] = 120 }
|
||||
for i: 0..suffix.count - 1 { bytes[prefix.count + length + i] = suffix[i] }
|
||||
text := TextView(bytes[:])
|
||||
if Measure(text,length) <= 0.0 { return 2 }
|
||||
samples: [11]float64
|
||||
for i: 0..10 { samples[i] = Measure(text,length) }
|
||||
result := BenchmarkAnalyze(samples[:])
|
||||
if !result.valid { return 3 }
|
||||
print("{\"case\":\"json_document_plain_1mib\",\"unit\":\"ns_per_parse\",\"rule\":\"symmetric inclusive 1.5xIQR\",\"raw\":[")
|
||||
Numbers(samples[:]); print("],\"excluded\":["); Indices(result.excluded[:])
|
||||
print("],\"median\":%}\n",result.median)
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using V :: #import "std/vec"
|
||||
using T :: #import "std/timer_linux"
|
||||
using J :: #import "std/json_bytes"
|
||||
#import "benchmark_statistics"
|
||||
|
||||
Reference :: (text: string, start: s64) -> s64 {
|
||||
if start < 0 { return start }
|
||||
at := start
|
||||
while at < text.count {
|
||||
byte := text[at]
|
||||
if byte < 32 || byte == 34 || byte == 92 { break }
|
||||
at += 1
|
||||
}
|
||||
return at
|
||||
}
|
||||
|
||||
// Opaque native input and a compiler memory barrier prevent a pure repeated
|
||||
// scan from being hoisted out of the measured loop. No instructions are needed.
|
||||
Opaque :: (value: u64) -> u64
|
||||
#asm("x86_64", "", "=r", "0", "memory", "volatile")
|
||||
#asm("aarch64", "", "=r", "0", "memory", "volatile") {
|
||||
return value
|
||||
}
|
||||
|
||||
Check :: () -> bool {
|
||||
bytes: [80]u8
|
||||
for size: 0..79 {
|
||||
for i: 0..79 { bytes[i] = 120 }
|
||||
for position: 0..size {
|
||||
for value: 0..255 {
|
||||
bytes[position] = cast(u8)value
|
||||
text := TextView(bytes[0:size])
|
||||
for start: cast(s64)-1..size + 1 {
|
||||
if Reference(text,start) != JsonStringRunEnd(text,start) {
|
||||
print("scan mismatch: size % position % value % start %\n",size,position,value,start)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
bytes[position] = 120
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
Measure :: (text: string, candidate: bool) -> float64 {
|
||||
total: s64
|
||||
started := MonotonicNanoseconds()
|
||||
for n: 0..63 {
|
||||
start := cast(s64)(Opaque(cast(u64)n) % cast(u64)7)
|
||||
end := ifx candidate then JsonStringRunEnd(text,start) else Reference(text,start)
|
||||
if end != text.count - 1 { return -1.0 }
|
||||
total += end - start
|
||||
}
|
||||
elapsed := MonotonicNanoseconds() - started
|
||||
if total != (text.count - 1) * 64 - 189 { return -1.0 }
|
||||
return cast(float64)elapsed / 64.0
|
||||
}
|
||||
|
||||
Numbers :: (values: []float64) {
|
||||
for index: 0..values.count - 1 { if index > 0 { print(",") }; print("%",values[index]) }
|
||||
}
|
||||
Indices :: (values: []s64) {
|
||||
for index: 0..values.count - 1 { if index > 0 { print(",") }; print("%",values[index]) }
|
||||
}
|
||||
|
||||
#program_export
|
||||
main :: () -> s32 {
|
||||
if !Check() { return 1 }
|
||||
bytes: Vec(u8)
|
||||
if !VecResize(bytes,1048577) { return 2 }
|
||||
for i: 0..1048575 { bytes[i] = 120 }
|
||||
bytes[1048576] = 34
|
||||
text := TextView(bytes[:])
|
||||
before: [9]float64
|
||||
after: [9]float64
|
||||
if Measure(text,false) <= 0.0 || Measure(text,true) <= 0.0 { return 3 }
|
||||
for sample: 0..8 {
|
||||
if sample % 2 == 0 { before[sample]=Measure(text,false); after[sample]=Measure(text,true) }
|
||||
else { after[sample]=Measure(text,true); before[sample]=Measure(text,false) }
|
||||
}
|
||||
old := BenchmarkAnalyze(before[:]); current := BenchmarkAnalyze(after[:])
|
||||
if !old.valid || !current.valid { return 4 }
|
||||
print("{\"case\":\"json_plain_string_1mib\",\"unit\":\"ns_per_scan\",\"rule\":\"symmetric inclusive 1.5xIQR\",\"reference_raw\":[")
|
||||
Numbers(before[:]); print("],\"candidate_raw\":["); Numbers(after[:])
|
||||
print("],\"reference_excluded\":["); Indices(old.excluded[:])
|
||||
print("],\"candidate_excluded\":["); Indices(current.excluded[:])
|
||||
print("],\"reference_median\":%,\"candidate_median\":%,\"speedup\":%}\n",old.median,current.median,old.median/current.median)
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build Ziran-authored JSON/UTF-8 workloads and measure all four targets on Alpha.
|
||||
|
||||
Uses the existing target hosts and their independent checksum validation. This
|
||||
is build/measurement orchestration; workload logic and oracles live in Ziran.
|
||||
"""
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import random
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE_SITE = ROOT / 'site'
|
||||
SITE = SOURCE_SITE
|
||||
HARNESS_ROOT = Path(os.environ.get('ZIRAN_BENCH_HARNESS_ROOT', ROOT)).resolve()
|
||||
sys.path.insert(0, str(HARNESS_ROOT / 'scripts'))
|
||||
import site_targets as base
|
||||
import site_target_platforms as hosts
|
||||
from benchmark_samples import GATE_METHOD, HostGate
|
||||
base.REPO = ROOT
|
||||
base.SITE = SITE
|
||||
hosts.ROOT = HARNESS_ROOT
|
||||
hosts.SITE = base.SITE
|
||||
|
||||
CASES = [
|
||||
('json_string_scan', 'JSON string scan · 16 KiB', 16418),
|
||||
('json_parse', 'JSON parse · 16 KiB string', 16624),
|
||||
('json_escaped', 'JSON parse · 128 escaped Unicode objects', 43904),
|
||||
('json_write', 'JSON write · 256 mixed Unicode strings', 5446),
|
||||
('json_quote_plain', 'JSON write · 64 KiB ASCII string', 65606),
|
||||
('text_processing', 'UTF-8 · scan, search, replace and split · 18 KiB', 33788),
|
||||
]
|
||||
OUTPUT = SITE / 'generated/json-text'
|
||||
WORK = ROOT / 'build/benchmarks/json-text'
|
||||
HARNESSES = ['bench/json_text.py', 'scripts/site_target_platforms.py', 'scripts/site_targets.py',
|
||||
'scripts/benchmark_samples.py', 'scripts/site_target_node.cjs',
|
||||
'bench/site_target_host.c', 'bench/site_target_host.go', 'site/target-abi.js', 'site/target-measure.js']
|
||||
|
||||
|
||||
def build(compiler, samples):
|
||||
if platform.node() != 'alpha':
|
||||
raise RuntimeError('Benchmark compilation and measurement require the selected Alpha physical host')
|
||||
os.nice(19)
|
||||
OUTPUT.mkdir(parents=True, exist_ok=True)
|
||||
WORK.mkdir(parents=True, exist_ok=True)
|
||||
env = hosts.environment()
|
||||
env['PATH'] = str(Path.home() / '.local/bin') + ':' + env['PATH']
|
||||
env['ZIRAN_JOBS'] = '1'
|
||||
env['ZIRAN_LEARN'] = 'off'
|
||||
# All helpers use the same scrubbed environment, including downstream Go.
|
||||
hosts.environment = lambda: env.copy()
|
||||
data = {'schema_version': 1, 'revision': hosts.run(['git', 'rev-parse', 'HEAD'], cwd=compiler), 'checks': False, 'learning': 'off', 'host': platform.node() + ' · ' + base.cpu_name(),
|
||||
'measured_at': datetime.now(timezone.utc).isoformat(), 'samples': samples,
|
||||
'compiler': {tool: base.sha(compiler / 'build/bin' / tool)
|
||||
for tool in ('zi2c', 'zi2go', 'zi2zx', 'zx2wasm')},
|
||||
'stdlib': {str(p.relative_to(compiler)): base.sha(p) for p in sorted((compiler / 'std').glob('*.zi'))},
|
||||
'harnesses': {p: base.sha((ROOT if p == 'bench/json_text.py' else HARNESS_ROOT) / p) for p in HARNESSES},
|
||||
'versions': {name: hosts.run(command, env=env).splitlines()[0] for name, command in
|
||||
{'cc': ['cc', '--version'], 'go': ['go', 'version'], 'node': ['node', '--version']}.items()},
|
||||
'methodology': hosts.metadata('', '', {}, samples)['methodology'].removesuffix(' Shared machines and uncontrolled clocks; no universal target ranking.') + GATE_METHOD, 'examples': []}
|
||||
zx = WORK / 'zx-runner'
|
||||
hosts.runtime_build('cc', compiler / 'build/libziran.a', zx,
|
||||
['-include', HARNESS_ROOT / 'bench/site_target_backend.h',
|
||||
'-DMATRIX_ZX_BACKEND=BUNDLE_BACKEND_NATIVE'])
|
||||
data['zx_backend'] = 'native'
|
||||
jobs = []
|
||||
for name, title, expected in CASES:
|
||||
source = ROOT / 'bench/json_text' / (name + '.zi')
|
||||
public_source=OUTPUT/'sources'/source.name
|
||||
public_source.parent.mkdir(parents=True,exist_ok=True)
|
||||
shutil.copyfile(source,public_source)
|
||||
row = {'id': name, 'title': title, 'source': public_source.relative_to(SITE).as_posix(),
|
||||
'source_input':source.relative_to(ROOT).as_posix(), 'entry': 'Answer',
|
||||
'expected': str(expected), 'stdout': '', 'source_sha256': base.sha(source), 'targets': {}}
|
||||
for target in ('c', 'go', 'zx', 'wasm'):
|
||||
directory = WORK / name / target
|
||||
if directory.exists():
|
||||
shutil.rmtree(directory)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
common = ['--root', source.parent, '--module-path', compiler / 'std',
|
||||
'--entry', name + ':Answer']
|
||||
if target in ('c', 'go'):
|
||||
command = [compiler / 'build/bin' / ('zi2' + target), '--no-main',
|
||||
*(['--pkg', 'main'] if target == 'go' else []), *common,
|
||||
'-o', directory, source]
|
||||
commands = [command]
|
||||
elif target == 'zx':
|
||||
command = [compiler / 'build/bin/zi2zx', *common,
|
||||
'-o', directory / (name + '.zx'), source]
|
||||
commands = [command]
|
||||
else:
|
||||
wire = directory / (name + '.zx')
|
||||
command = [compiler / 'build/bin/zi2zx', '--target', 'wasm', *common,
|
||||
'-o', wire, source]
|
||||
commands = [command, [compiler / 'build/bin/zx2wasm',
|
||||
'-o', directory / (name + '.wasm'), wire]]
|
||||
try:
|
||||
for stage in commands:
|
||||
hosts.run(stage, env=env)
|
||||
except RuntimeError as error:
|
||||
if target!='wasm' or 'outside the wasm execution subset' not in str(error):
|
||||
raise
|
||||
row['targets'][target]={'status':'unavailable','files':[], 'diagnostic':str(error)}
|
||||
continue
|
||||
public = OUTPUT / name / target
|
||||
public.mkdir(parents=True, exist_ok=True)
|
||||
emitted = []
|
||||
for path in sorted(directory.rglob('*')):
|
||||
if path.suffix not in ({'.c', '.h'} if target == 'c' else {'.go'} if target == 'go' else {'.' + target}):
|
||||
continue
|
||||
destination = public / path.relative_to(directory)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(path, destination)
|
||||
emitted.append(hosts.public(destination))
|
||||
cell = {'status': 'ok', 'files': emitted,
|
||||
'command': '\n'.join(base.command_text(stage) for stage in commands)}
|
||||
row['targets'][target] = cell
|
||||
if target == 'c':
|
||||
program = WORK / name / 'c-program'
|
||||
cell['build_command'] = base.command_text(hosts.c_build(row, 'cc', program))
|
||||
invoke = [program, '-', expected, samples]
|
||||
elif target == 'go':
|
||||
program = WORK / name / 'go-program'
|
||||
build_command = ['go', 'build', '-p=1', '-o', program, *hosts.go_source(row, WORK / name / 'go-host')]
|
||||
hosts.run(build_command, env=env)
|
||||
cell['build_command'] = base.command_text(build_command)
|
||||
invoke = [program, '-', expected, samples]
|
||||
elif target == 'zx':
|
||||
invoke = [zx, base.SITE / emitted[0]['path'], expected, samples]
|
||||
else:
|
||||
invoke = ['node', HARNESS_ROOT / 'scripts/site_target_node.cjs', base.SITE / emitted[0]['path'], expected, samples]
|
||||
jobs.append((row, cell, invoke))
|
||||
data['examples'].append(row)
|
||||
random.Random(42).shuffle(jobs)
|
||||
gate = HostGate()
|
||||
timed_env = gate.environment(env)
|
||||
for row, cell, command in jobs:
|
||||
print('Measuring', row['id'], command[0], flush=True)
|
||||
measured = hosts.measure(command, row, timed_env, gate)
|
||||
cell['measurement'] = {**measured, 'command': base.command_text(command)}
|
||||
(OUTPUT / 'matrix.json').write_text(json.dumps(data, indent=2) + '\n')
|
||||
|
||||
|
||||
def check():
|
||||
data = json.loads((OUTPUT / 'matrix.json').read_text())
|
||||
assert data['schema_version'] == 1 and data['host'].startswith('alpha · ') and 3 <= data['samples'] <= 31
|
||||
assert [(row['id'], row['expected']) for row in data['examples']] == [(name, str(oracle)) for name, _, oracle in CASES]
|
||||
base.check_committed(base.published_revision(OUTPUT / 'matrix.json'), data['harnesses'], 'Benchmark harness')
|
||||
base.check_committed(data['revision'], data['stdlib'], 'Standard library')
|
||||
base.check_committed(data['revision'], {row['source_input']: row['source_sha256'] for row in data['examples']}, 'Workload')
|
||||
for row in data['examples']:
|
||||
assert base.sha(SITE / row['source']) == row['source_sha256']
|
||||
assert set(row['targets']) == {'c', 'go', 'zx', 'wasm'}
|
||||
for cell in row['targets'].values():
|
||||
if cell['status']=='unavailable':
|
||||
assert row['targets']['wasm'] is cell and 'outside the wasm execution subset' in cell['diagnostic'] and not cell['files']
|
||||
continue
|
||||
measured = cell['measurement']
|
||||
assert measured['stdout_verified'] and hosts.summarize(measured, row['expected']) == measured
|
||||
assert len(measured['batch_samples_ms']) == data['samples']
|
||||
for file in cell['files']:
|
||||
path = SITE / file['path']
|
||||
assert path.stat().st_size == file['bytes'] and base.sha(path) == file['sha256']
|
||||
print('Alpha JSON/text source, artifact, oracle and raw-sample local validation passed')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--compiler-root', type=Path, default=ROOT)
|
||||
parser.add_argument('--site-dir', type=Path, default=SOURCE_SITE,
|
||||
help='write generated artifacts and the results page under this directory')
|
||||
parser.add_argument('--samples', type=int, default=11)
|
||||
parser.add_argument('--check', action='store_true')
|
||||
args = parser.parse_args()
|
||||
SITE = args.site_dir.resolve()
|
||||
base.SITE = hosts.SITE = SITE
|
||||
OUTPUT = SITE / 'generated/json-text'
|
||||
if not 3 <= args.samples <= 31:
|
||||
parser.error('--samples must be between 3 and 31')
|
||||
check() if args.check else build(args.compiler_root.resolve(), args.samples)
|
||||
@@ -0,0 +1,28 @@
|
||||
// Decode JSON: parse 128 objects with UTF-8, a control escape, a BMP escape and a
|
||||
// surrogate pair. The independent oracle is 128 * (9 bytes + 206 + 128).
|
||||
using V :: #import "vec"
|
||||
using J :: #import "json_document"
|
||||
input: Vec(u8);
|
||||
|
||||
Answer :: () -> s64 {
|
||||
if input.count==0 {
|
||||
if !BuilderAppend(input,"[") { return -1 }
|
||||
for index: 0..127 {
|
||||
if index>0 && !BuilderAppend(input,",") { return -2 }
|
||||
if !BuilderAppend(input,"{\"label\":\"λ\\n\\u03bb\\uD83D\\uDE80\"}") { return -3 }
|
||||
}
|
||||
if !BuilderAppend(input,"]") { return -4 }
|
||||
}
|
||||
document: JsonDocument
|
||||
defer JsonReset(*document)
|
||||
if !JsonRead(*document,TextView(input[:]))||JsonCount(*document,document.root)!=128 { return -5 }
|
||||
sum: s64
|
||||
child:=JsonFirst(*document,document.root)
|
||||
while child>=0 {
|
||||
text:=JsonString(*document,JsonMember(*document,child,"label"))
|
||||
if text.count!=9 { return -6 }
|
||||
sum+=text.count+cast(s64)text[0]+cast(s64)text[text.count-1]
|
||||
child=JsonNext(*document,child)
|
||||
}
|
||||
return sum
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Parse JSON: materialize a 16 KiB JSON string. The input is
|
||||
// prepared once, before measured calls; the result consumes its bytes.
|
||||
using V :: #import "vec"
|
||||
using J :: #import "json_document"
|
||||
input: Vec(u8);
|
||||
|
||||
Answer :: () -> s64 {
|
||||
if input.count==0 {
|
||||
if !BuilderAppend(input,"{\"payload\":\"") { return -1 }
|
||||
for index: 0..16383 { if !VecPush(input,120) { return -2 } }
|
||||
if !BuilderAppend(input,"\"}") { return -3 }
|
||||
}
|
||||
document: JsonDocument
|
||||
defer JsonReset(*document)
|
||||
if !JsonRead(*document,TextView(input[:])) { return -4 }
|
||||
payload:=JsonString(*document,JsonMember(*document,document.root,"payload"))
|
||||
if payload.count!=16384 { return -5 }
|
||||
return payload.count+cast(s64)payload[0]+cast(s64)payload[payload.count-1]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Quote ASCII: serialize 64 KiB and check the full output size and ends;
|
||||
// input generation is excluded after the first warmup call.
|
||||
using V :: #import "vec"
|
||||
using J :: #import "json_quote"
|
||||
input: Vec(u8);
|
||||
|
||||
Answer :: () -> s64 {
|
||||
if input.count==0 { if !VecResize(input,65536) { return -1 }; for index: 0..65535 { input[index]=120 } }
|
||||
output: Vec(u8)
|
||||
if !JsonQuoteInto(*output,TextView(input[:]),true)||output.count!=65538||output[1]!=120||output[65536]!=120 { return -2 }
|
||||
return output.count+cast(s64)output[0]+cast(s64)output[output.count-1]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Scan a JSON string: validate its span without building a document tree.
|
||||
// The closing quote follows 16 KiB of ASCII; consume the complete span.
|
||||
using V :: #import "vec"
|
||||
Json :: #import "json_bytes"
|
||||
input: Vec(u8);
|
||||
|
||||
Answer :: () -> s64 {
|
||||
if input.count==0 {
|
||||
if !VecResize(input,16385) { return -1 }
|
||||
for index: 0..16383 { input[index]=120 }
|
||||
input[16384]=34
|
||||
}
|
||||
end:=Json.JsonStringRunEnd(TextView(input[:]),0)
|
||||
if end!=16384||input[end]!=34 { return -2 }
|
||||
return end+cast(s64)input[end]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Quote Unicode: write 256 repetitions of ASCII, a BMP scalar and an astral scalar with
|
||||
// ensure-ASCII semantics: 256 * (3 + 6 + 12) + two quotation marks.
|
||||
using V :: #import "vec"
|
||||
using J :: #import "json_quote"
|
||||
input: Vec(u8);
|
||||
|
||||
Answer :: () -> s64 {
|
||||
if input.count==0 { for index: 0..255 { if !BuilderAppend(input,"abcλ😀") { return -1 } } }
|
||||
output: Vec(u8)
|
||||
if !JsonQuoteInto(*output,TextView(input[:]),true)||output.count!=5378||output[0]!=34||output[5377]!=34 { return -2 }
|
||||
if output[4]!=92||output[5]!=117||output[10]!=92 { return -3 }
|
||||
return output.count+cast(s64)output[0]+cast(s64)output[output.count-1]
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Process UTF-8: search, replace, split and count scalars. Input
|
||||
// preparation happens during warmup; output allocation stays in each call.
|
||||
using V :: #import "vec"
|
||||
using T :: #import "text_tools"
|
||||
Utf8 :: #import "utf8"
|
||||
input: Vec(u8);
|
||||
|
||||
Answer :: () -> s64 {
|
||||
if input.count==0 { for index: 0..1023 { if !BuilderAppend(input,"alpha λ😀 beta\n") { return -1 } } }
|
||||
text:=TextView(input[:])
|
||||
found:=TextFind(text,"beta\n",text.count-18)
|
||||
if found!=text.count-5||Utf8.Count(text)!=14336 { return -2 }
|
||||
rewritten:=TextReplace(text,"alpha","A")
|
||||
if rewritten.count!=14336 { return -3 }
|
||||
lines:=TextSplit(rewritten,"\n")
|
||||
if lines.count!=1025||lines[0]!="A λ😀 beta"||lines[1024]!="" { return -4 }
|
||||
return found+rewritten.count+lines.count
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
# Exact portable square-root normalization
|
||||
|
||||
`std/math.zi` normalizes a finite positive input to a mantissa in `[1, 2)`.
|
||||
After its existing 64-bit exponent steps, the residual exponent is in
|
||||
`[0, 63]`. Six descending comparisons against `2^32`, `2^16`, `2^8`,
|
||||
`2^4`, `2^2`, and `2^1` replace the old loop that constructed those powers
|
||||
with 63 multiplications. Each selected reciprocal is an exactly representable
|
||||
power of two. The normalized result is at least one, so replacing division by
|
||||
that power with multiplication by its reciprocal cannot underflow, overflow,
|
||||
or introduce rounding. The mantissa and exponent remain identical.
|
||||
|
||||
`Sqrt` keeps its six Newton iterations, neighboring-result selection and
|
||||
exceptional-input paths. This is not a hardware-sqrt substitution: its existing
|
||||
one-ULP accuracy contract, rather than correctly rounded libm behavior, remains
|
||||
unchanged. No allocation, compiler lowering, runtime feature or host shim is
|
||||
introduced. `Log`, which shares `MathSplit`, benefits from the same change.
|
||||
|
||||
## Local tests
|
||||
|
||||
Run from the canonical checkout, using an existing toolchain:
|
||||
|
||||
```sh
|
||||
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY \
|
||||
build/bin/check-runner --bin-dir "$PWD/build/bin" --jobs 1 --filter math
|
||||
```
|
||||
|
||||
Set `CC` to an existing managed compiler wrapper when compilation is assigned
|
||||
to another machine. Both math shell tests honor it. `math_sqrt.sh` tests exact
|
||||
agreement with the pre-change algorithm for one million deterministic IEEE
|
||||
patterns, every normal exponent boundary, all subnormal powers and their
|
||||
neighbors, signed zeros, NaNs, infinities and negative-domain inputs. Native
|
||||
source and saved IR both run the full set. Portable source and saved IR run
|
||||
the same bounded edge set and produce byte-identical bundles. The existing
|
||||
`math_float64.sh` also checks all 21 elementary functions against libm and in
|
||||
the portable engine. NaN tests compare classification, not payload bits.
|
||||
|
||||
## Repeatable microbenchmark
|
||||
|
||||
```sh
|
||||
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY \
|
||||
sh bench/math_sqrt.sh "$PWD/build/bin/ziran"
|
||||
```
|
||||
|
||||
The benchmark compiles the old algorithm from `tests/spec/math_sqrt_reference.zi`
|
||||
and the current standard library together at `-O2`, without fast-math or LTO.
|
||||
It first checks exact agreement on its inputs. Each sample makes 1,024,000
|
||||
calls; a warmup precedes nine samples, alternating baseline/candidate order.
|
||||
It covers squared-length-like values in `(0, 16]` and positive normal values
|
||||
spread across binary64 exponents. Checksums keep the calls observable. Raw
|
||||
nanoseconds per call and excluded sample indices are printed. Both algorithms
|
||||
use the same symmetric 1.5-times-IQR rule with inclusive interpolated quartiles.
|
||||
|
||||
The November 11, 2026 local result is retained in
|
||||
`results/math-sqrt-2026-11-11.json`: geometry median 32.04 to 11.44 ns/call
|
||||
(2.80x); exponent-spread median 57.44 to 25.74 ns/call (2.23x). C objects were
|
||||
compiled on physical Alpha with two workers and an 8 GiB managed limit;
|
||||
timing ran locally on the Ryzen 9 9950X desktop. These are microbenchmarks,
|
||||
not actual-room frame timings or proof of 60 fps. Parent-owned renderer
|
||||
reference-frame and application integration validation remain separate.
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
repo=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
ziran=${1:-$repo/build/bin/ziran}
|
||||
work="$repo/build/math-sqrt-bench"
|
||||
mkdir -p "$work"
|
||||
unset DISPLAY WAYLAND_DISPLAY
|
||||
cd "$repo"
|
||||
printf 'source_revision '; git rev-parse HEAD
|
||||
sha256sum std/math.zi tests/spec/math_sqrt_reference.zi bench/math_sqrt.zi
|
||||
"$ziran" build --target=c --root bench --module-path std --module-path tests/spec \
|
||||
-o "$work/c" bench/math_sqrt.zi
|
||||
"${CC:-cc}" -std=c11 -O2 -iquote "$work/c" "$work/c"/*.c -lm -o "$work/math_sqrt"
|
||||
"$work/math_sqrt"
|
||||
@@ -0,0 +1,68 @@
|
||||
#import "std/math"
|
||||
#import "std/binary"
|
||||
#import "std/timer_linux"
|
||||
#import "math_sqrt_reference"
|
||||
#import "benchmark_statistics"
|
||||
|
||||
Measure :: (values: []float64, reference: bool) -> float64 {
|
||||
total: float64 = 0.0
|
||||
started := MonotonicNanoseconds()
|
||||
for repeat: 0..999 {
|
||||
for value: values {
|
||||
if reference { total += ReferenceSqrt(value) }
|
||||
else { total += Sqrt(value) }
|
||||
}
|
||||
}
|
||||
elapsed := MonotonicNanoseconds() - started
|
||||
print("checksum %\n", total)
|
||||
return cast(float64)elapsed / (cast(float64)values.count * 1000.0)
|
||||
}
|
||||
|
||||
Report :: (name: string, samples: []float64) -> float64 {
|
||||
result := BenchmarkAnalyze(samples)
|
||||
for index: cast(s64)0..samples.count - 1 { print("% sample % ns_per_call %\n", name, index, samples[index]) }
|
||||
for index: result.excluded { print("% excluded_index %\n", name, index) }
|
||||
print("% median_ns_per_call %\n", name, result.median)
|
||||
if !result.valid { return 0.0 }
|
||||
return result.median
|
||||
}
|
||||
|
||||
Run :: (name: string, values: []float64) -> bool {
|
||||
baseline: [9]float64
|
||||
candidate: [9]float64
|
||||
Measure(values, true)
|
||||
Measure(values, false)
|
||||
for sample: 0..8 {
|
||||
if sample % 2 == 0 {
|
||||
baseline[sample] = Measure(values, true)
|
||||
candidate[sample] = Measure(values, false)
|
||||
} else {
|
||||
candidate[sample] = Measure(values, false)
|
||||
baseline[sample] = Measure(values, true)
|
||||
}
|
||||
}
|
||||
print("distribution %\n", name)
|
||||
before := Report("reference", baseline[:])
|
||||
after := Report("candidate", candidate[:])
|
||||
print("speedup %\n", before / after)
|
||||
return before > 0.0 && after > 0.0
|
||||
}
|
||||
|
||||
#program_export
|
||||
main :: () -> s32 {
|
||||
geometry: [1024]float64
|
||||
spread: [1024]float64
|
||||
state: u64 = 88172645463325252
|
||||
for index: 0..1023 {
|
||||
state ^= state << cast(u64)13
|
||||
state ^= state >> cast(u64)7
|
||||
state ^= state << cast(u64)17
|
||||
geometry[index] = 0.000001 + cast(float64)(state & 0xffffff) / 16777216.0 * 16.0
|
||||
bits := ((cast(u64)index * 2045 / 1023 + 1) << cast(u64)52) | (state & 0x000fffffffffffff)
|
||||
spread[index] = Float64FromBits(bits)
|
||||
if Sqrt(geometry[index]) != ReferenceSqrt(geometry[index]) ||
|
||||
Sqrt(spread[index]) != ReferenceSqrt(spread[index]) { return 1 }
|
||||
}
|
||||
if !Run("geometry_0_to_16", geometry[:]) || !Run("normal_exponent_spread", spread[:]) { return 2 }
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// Emit the same source/FFI fixture exercised by the native cache regression.
|
||||
#import "native_test"
|
||||
#import "native_cache_support"
|
||||
#import "check_support"
|
||||
#import "std/byte_text_linux"
|
||||
#import "std/environment_linux"
|
||||
#import "std/file_tree_linux"
|
||||
#import "std/json_document"
|
||||
#import "std/text_tools"
|
||||
using Vectors :: #import "std/vec"
|
||||
|
||||
#program_export
|
||||
main :: (argc: s32, argv: **u8) -> s32 {
|
||||
if argc != 3 { print("pass compiler and fixture directory\n"); return 2 }
|
||||
test: NativeTest
|
||||
test.repo = TextDetach(ResolvePath(PathParent(PathParent(EnvironmentText("ZIRAN_SCRIPT_FILE")))))
|
||||
test.ziran = TextDetach(ResolvePath(TextFromCString(argv[1])))
|
||||
directory := TextFromCString(argv[2])
|
||||
if !NativeAssert(*test, CreateDirectories(directory), "create requested native fixture directory") { return 1 }
|
||||
test.work = TextDetach(ResolvePath(directory)); output := CheckPath(test.work, "out with spaces"); compiler := NativeCompiler()
|
||||
command := string.[test.ziran, "build", "--target=c", "--exe", "--entry", "app:Answer", "--diagnostics=json", "--root", test.work, "-o", output, CheckPath(test.work, "app.zi")]
|
||||
fixture := CacheFixture.{*test, command[:], compiler, output}
|
||||
if !CachePrepare(fixture) { return 1 }
|
||||
document: JsonDocument; document.root = JsonNewObject(*document)
|
||||
CheckPut(*document, document.root, "out", output); CheckPut(*document, document.root, "headers", CheckPath(test.work, "headers"))
|
||||
arguments := JsonNewArray(*document); for argument: command { JsonAppend(*document, arguments, JsonNewString(*document, argument)) }; JsonSet(*document, document.root, "command", arguments)
|
||||
print("%\n", JsonWrite(*document, document.root, JsonCompactStyle()))
|
||||
return 0
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
/* Build the same insertion workload with the current or a preserved cache
|
||||
* implementation. This is a container benchmark, not total compiler time. */
|
||||
#include "../cmd/zir-c/zir_c_cache.c"
|
||||
#include <assert.h>
|
||||
#include <inttypes.h>
|
||||
|
||||
static uint64_t nanoseconds(void)
|
||||
{
|
||||
struct timespec value;
|
||||
assert(clock_gettime(CLOCK_MONOTONIC, &value) == 0);
|
||||
return (uint64_t)value.tv_sec * UINT64_C(1000000000) + (uint64_t)value.tv_nsec;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
assert(argc == 3);
|
||||
int count = atoi(argv[1]), rounds = atoi(argv[2]);
|
||||
assert(count > 0 && count <= MAX_ITEMS && !(count & (count - 1)) && rounds > 0);
|
||||
char **input = calloc((size_t)count, sizeof(*input));
|
||||
assert(input);
|
||||
for(int i = 0; i < count; i++)
|
||||
assert(asprintf(&input[i], "/shared/project/include/long/common/path/component/header-%08d.h", (i * 1297) % count) >= 0);
|
||||
uint64_t total = 0, checksum = 0;
|
||||
for(int round = 0; round < rounds; round++) {
|
||||
Names names = {0};
|
||||
uint64_t started = nanoseconds();
|
||||
for(int i = 0; i < count; i++) assert(add_name(&names, input[i]));
|
||||
for(int i = count - 1; i >= 0; i--) assert(add_name(&names, input[i]));
|
||||
assert(names.count == count);
|
||||
checksum = UINT64_C(14695981039346656037);
|
||||
for(int i = 0; i < count; i++) {
|
||||
assert(!strcmp(names.items[i], input[i]));
|
||||
for(const unsigned char *p = (const unsigned char *)names.items[i]; *p; p++)
|
||||
checksum = (checksum ^ *p) * UINT64_C(1099511628211);
|
||||
checksum *= UINT64_C(1099511628211);
|
||||
}
|
||||
free_names(&names);
|
||||
total += nanoseconds() - started;
|
||||
}
|
||||
for(int i = 0; i < count; i++) free(input[i]);
|
||||
free(input);
|
||||
printf("{\"count\":%d,\"rounds\":%d,\"total_ns\":%" PRIu64 ",\"checksum\":%" PRIu64 "}\n",
|
||||
count, rounds, total, checksum);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure the native cache's ordered name collection against a Git revision."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import random
|
||||
import shutil
|
||||
import statistics
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def expected_checksum(count):
|
||||
value = 14695981039346656037
|
||||
for index in range(count):
|
||||
key = f'/shared/project/include/long/common/path/component/header-{(index * 1297) % count:08d}.h'
|
||||
for byte in key.encode()+b'\0': value = ((value ^ byte) * 1099511628211) & ((1 << 64)-1)
|
||||
return value
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--out', type=Path, required=True)
|
||||
parser.add_argument('--before-ref', required=True)
|
||||
parser.add_argument('--repetitions', type=int, default=15)
|
||||
args = parser.parse_args()
|
||||
if args.repetitions < 1: parser.error('repetitions must be positive')
|
||||
out = args.out.resolve()
|
||||
if out.exists(): parser.error('archive records and remove inactive outputs before reuse')
|
||||
out.mkdir(parents=True)
|
||||
env = {k:v for k,v in os.environ.items() if k not in ('DISPLAY','WAYLAND_DISPLAY','XAUTHORITY','DBUS_SESSION_BUS_ADDRESS','ZIRAN_PROFILE')}
|
||||
env['YUE_DESKTOP_RECOVERY']='0'
|
||||
compiler, timer = shutil.which('cc'), []
|
||||
if tool := shutil.which('time'):
|
||||
probe = subprocess.run([tool,'--version'],capture_output=True,text=True)
|
||||
if probe.returncode == 0 and 'GNU' in probe.stdout+probe.stderr: timer = [tool]
|
||||
if not timer and (tool := shutil.which('busybox')):
|
||||
probe = subprocess.run([tool,'time','--help'],capture_output=True,text=True)
|
||||
if '-f FMT' in probe.stdout+probe.stderr and '-o FILE' in probe.stdout+probe.stderr: timer = [tool,'time']
|
||||
if not compiler or not timer: parser.error('requires cc and GNU or BusyBox time')
|
||||
ref = subprocess.check_output(['git','rev-parse','--verify',args.before_ref+'^{commit}'],cwd=ROOT,text=True).strip()
|
||||
old = subprocess.check_output(['git','show',ref+':cmd/zir-c/zir_c_cache.c'],cwd=ROOT,text=True)
|
||||
source = (ROOT/'bench/native_cache_names.c').read_text()
|
||||
marker = '#include "../cmd/zir-c/zir_c_cache.c"'
|
||||
assert source.count(marker)==1
|
||||
common = [compiler,'-O2','-D_GNU_SOURCE','-std=c11','-Iinclude','-Icmd/zir','-Ibootstrap/compiler_ir','-Icmd/zir-c']
|
||||
subprocess.run([*common,'-x','c','-','-x','none','build/libziran.a','-lm','-pthread','-o',str(out/'before')],input=source.replace(marker,old),text=True,cwd=ROOT,env=env,check=True)
|
||||
subprocess.run([*common,'bench/native_cache_names.c','build/libziran.a','-lm','-pthread','-o',str(out/'current')],cwd=ROOT,env=env,check=True)
|
||||
sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
meta = dict(schema=1,platform=platform.platform(),before_ref=ref,repetitions=args.repetitions,measurement_launcher=timer,
|
||||
cpu_affinity=sorted(os.sched_getaffinity(0)) if hasattr(os,'sched_getaffinity') else None,
|
||||
compiler_version=subprocess.check_output([compiler,'--version'],text=True),
|
||||
before_cache_sha256=hashlib.sha256(old.encode()).hexdigest(),current_cache_sha256=sha(ROOT/'cmd/zir-c/zir_c_cache.c'),
|
||||
benchmark_c_sha256=sha(ROOT/'bench/native_cache_names.c'),benchmark_py_sha256=sha(Path(__file__)),
|
||||
binaries={label:sha(out/label) for label in ('before','current')},
|
||||
caveats=['Ordered-name insertion/duplicate checking, content verification and cleanup in one native process; not whole compiler time.',
|
||||
'Common path prefixes and large sets stress the previous linear duplicate scans and repeated array growth.',
|
||||
'Process RSS includes the harness and its inputs; it does not isolate container allocations or whole compiler memory.'])
|
||||
rows=[]
|
||||
for count in (16,256,2048,8192):
|
||||
rounds=max(1,8192//count);expected=expected_checksum(count)
|
||||
for repetition in range(args.repetitions+1):
|
||||
order=['before','current'];random.Random(count+repetition).shuffle(order)
|
||||
for label in order:
|
||||
rss=out/'rss.txt'
|
||||
result=subprocess.run([*timer,'-f','%M','-o',str(rss),str(out/label),str(count),str(rounds)],env=env,capture_output=True,text=True,check=True,timeout=60)
|
||||
sample=json.loads(result.stdout)
|
||||
assert sample['count']==count and sample['rounds']==rounds and sample['checksum']==expected,sample
|
||||
row=dict(count=count,rounds=rounds,variant=label,repetition=repetition,warmup=repetition==0,
|
||||
container_ms=sample['total_ns']/rounds/1e6,max_rss_kib=int(rss.read_text()),checksum=expected)
|
||||
rows.append(row)
|
||||
with (out/'samples.jsonl').open('a') as f:f.write(json.dumps(row)+'\n')
|
||||
print('validated ordered names '+str(count),flush=True)
|
||||
summary=[]
|
||||
for count in (16,256,2048,8192):
|
||||
for label in ('before','current'):
|
||||
values=[row for row in rows if row['count']==count and row['variant']==label and not row['warmup']]
|
||||
summary.append(dict(count=count,variant=label,samples=len(values),median_container_ms=statistics.median(row['container_ms'] for row in values),median_max_rss_kib=statistics.median(row['max_rss_kib'] for row in values)))
|
||||
(out/'metadata.json').write_text(json.dumps(meta,indent=2)+'\n')
|
||||
(out/'summary.json').write_text(json.dumps(summary,indent=2)+'\n')
|
||||
print(f'{sum(not row["warmup"] for row in rows)} ordered-name samples validated against independent checksums.',flush=True)
|
||||
|
||||
|
||||
if __name__=='__main__': main()
|
||||
@@ -49,7 +49,7 @@ def generate(source, groups=GROUPS, width=WIDTH, consumers=CONSUMERS, read_last=
|
||||
def host_source(groups=GROUPS, width=WIDTH):
|
||||
GROUPS, WIDTH = groups, width
|
||||
size = GROUPS * WIDTH * 4
|
||||
return ('#include "common.h"\n'
|
||||
return ('#include <stddef.h>\n#include "common.h"\n'
|
||||
f'_Static_assert(sizeof(Bundle) == {size}, "full foreign ABI");\n'
|
||||
f'_Static_assert(offsetof(Bundle, g{GROUPS - 1}.l{WIDTH - 1}.value) == {size - 4}, "last ABI field");\n'
|
||||
f'uint32_t prepare(Bundle *value, uint32_t seed) {{ value->g{GROUPS - 1}.l{WIDTH - 1}.value = seed + 3; '
|
||||
|
||||
+25
-23
@@ -1,7 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure complete native builds under controlled probe-version interleaving."""
|
||||
import argparse
|
||||
import ast
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -11,7 +10,6 @@ import shlex
|
||||
import shutil
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -40,33 +38,36 @@ def main():
|
||||
if not compiler or not timer: parser.error('requires cc and GNU or BusyBox time')
|
||||
sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
|
||||
# Reuse the regression's real C compiler shim and five-object FFI fixture.
|
||||
# Execute only its setup, before the first build or any test mutations.
|
||||
test = ROOT/'tests/native_build_cache_test.py'
|
||||
tree = ast.parse(test.read_text(),str(test))
|
||||
setup = []
|
||||
for node in tree.body:
|
||||
if isinstance(node,ast.Expr) and isinstance(node.value,ast.Call) and isinstance(node.value.func,ast.Name) and node.value.func.id == 'build': break
|
||||
setup.append(node)
|
||||
assert len(setup) < len(tree.body)
|
||||
helper = [node.value.args[0].value for node in tree.body
|
||||
if isinstance(node,ast.Expr) and isinstance(node.value,ast.Call) and isinstance(node.value.func,ast.Attribute)
|
||||
and isinstance(node.value.func.value,ast.Name) and node.value.func.value.id == 'proxy_source' and node.value.func.attr == 'write_text']
|
||||
assert len(helper) == 1
|
||||
# The native regression and benchmark share one Ziran fixture producer.
|
||||
# Its real C compiler shim is ordinary input data, not a Python test import.
|
||||
test = ROOT/'bench/native_cache_fixture.zi'
|
||||
proxy_source = ROOT/'tests/fixtures/native_cache/proxy.c.in'
|
||||
shim = out/'gcc'
|
||||
subprocess.run([compiler,'-D_GNU_SOURCE','-DREVISION=0','-DREAL_CC='+json.dumps(compiler),'-x','c','-','-o',shim],input=helper[0],text=True,env=env,check=True)
|
||||
subprocess.run([compiler,'-D_GNU_SOURCE','-DREVISION=0','-DREAL_CC='+json.dumps(compiler),'-x','c',proxy_source,'-o',shim],env=env,check=True)
|
||||
cases = {}
|
||||
prefix = '\tcompiled by GNU C version 99.0.0, '
|
||||
banner = 'GNU assembler version 2.44 (target) using BFD version 2.44\n'
|
||||
for label,tools in [('before',args.before_bin_dir.resolve()),('current',args.bin_dir.resolve())]:
|
||||
work = out/label; work.mkdir()
|
||||
scope = {'__file__':str(test),'__name__':'fixture'}
|
||||
original = sys.argv
|
||||
try:
|
||||
sys.argv = [str(test),str(tools/'ziran'),str(work)]
|
||||
exec(compile(ast.Module(body=setup,type_ignores=[]),str(test),'exec'),scope)
|
||||
finally: sys.argv = original
|
||||
scope['env'].update(env)
|
||||
prepared = subprocess.run([args.bin_dir.resolve()/'ziran', 'run', '--target=c',
|
||||
'--root', ROOT/'bench', '--module-path', ROOT/'tests', test, '--', tools/'ziran', work],
|
||||
env=env,capture_output=True,text=True,check=True)
|
||||
record = json.loads(prepared.stdout)
|
||||
output, headers = Path(record['out']), Path(record['headers'])
|
||||
scope = dict(out=output,headers=headers,command=record['command'],env=dict(env))
|
||||
def objects(output=output):
|
||||
return {str(path.relative_to(output/'.objects')): (path.stat().st_mtime_ns,path.stat().st_ino)
|
||||
for path in (output/'.objects').rglob('*.o')}
|
||||
def build(answer,changed=None,scope=scope,objects=objects):
|
||||
before=objects()
|
||||
result=subprocess.run(scope['command'],env=scope['env'],capture_output=True,text=True,timeout=30)
|
||||
assert result.returncode==0,result.stderr
|
||||
for line in result.stderr.splitlines(): assert json.loads(line)['code']=='zir_c.toolchain',line
|
||||
assert subprocess.run([scope['out']/'app'],env=scope['env']).returncode==answer
|
||||
updates={name for name,value in objects().items() if before.get(name)!=value}
|
||||
if changed is not None: assert updates==changed,(updates,changed)
|
||||
return updates
|
||||
scope.update(objects=objects,build=build)
|
||||
scope['env'].update(CC=str(shim),CFLAGS='-O2 -isystem '+str(scope['headers']),LDFLAGS='-L'+str(work),LDLIBS='-lbase')
|
||||
probe = subprocess.run([compiler,*shlex.split(scope['env']['CFLAGS']),'-I',scope['out'],'-pthread','-I',ROOT/'include','-pipe','-v','-x','c','-c','/dev/null','-o','/dev/null'],env=scope['env'],capture_output=True,text=True,check=True).stderr
|
||||
saved = work/'probe.txt';scope['env']['CACHE_PROBE_TEXT'] = str(saved)
|
||||
@@ -117,6 +118,7 @@ def main():
|
||||
assert all(identity.values()),identity
|
||||
metadata=dict(schema=1,repetitions=args.repetitions,compiler=compiler,compiler_version=subprocess.check_output([compiler,'--version'],text=True),measurement_launcher=timer,
|
||||
cpu_affinity=sorted(os.sched_getaffinity(0)) if hasattr(os,'sched_getaffinity') else None,generator_sha256=sha(Path(__file__)),fixture_sha256=sha(test),shim_sha256=sha(shim),
|
||||
fixture_sources_sha256={str(path.relative_to(ROOT)):sha(path) for path in [test,ROOT/'tests/native_cache_support.zi',proxy_source]},
|
||||
source_hashes={str(p.relative_to(ROOT)):sha(p) for folder in ['cmd','std','include'] for p in (ROOT/folder).rglob('*') if p.is_file() and p.suffix in ['.c','.h','.zi']},
|
||||
tool_hashes={label:{name:sha(tools/name) for name in ['ziran','zi2c']} for label,tools in [('before',args.before_bin_dir.resolve()),('current',args.bin_dir.resolve())]},
|
||||
flags={label:{k:case['scope']['env'][k] for k in ['CC','CFLAGS','LDFLAGS','LDLIBS']} for label,case in cases.items()},output_identity=identity,
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Matched frozen-runtime A/B on the existing wasm_tier kernels (physical Alpha)."""
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import wasm_tier as tier
|
||||
from benchmark_samples import GATE_METHOD, HostGate, summarize_samples
|
||||
|
||||
|
||||
def identity(path):
|
||||
path = Path(path).resolve()
|
||||
digest = hashlib.sha256()
|
||||
with path.open('rb') as source:
|
||||
for block in iter(lambda: source.read(1024 * 1024), b''):
|
||||
digest.update(block)
|
||||
return {'path': str(path), 'sha256': digest.hexdigest(), 'bytes': path.stat().st_size}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--before', type=Path, required=True)
|
||||
parser.add_argument('--after', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
virt = subprocess.run(['systemd-detect-virt'], capture_output=True, text=True)
|
||||
if platform.node().split('.')[0].lower() != 'alpha' or virt.returncode != 1 or virt.stdout.strip() != 'none':
|
||||
parser.error('measurement requires physical Alpha')
|
||||
if args.output.exists():
|
||||
parser.error('output already exists')
|
||||
os.environ['ZIRAN_LEARN'] = 'off'
|
||||
env = HostGate.environment(tier.platforms.environment())
|
||||
gate = HostGate()
|
||||
rng = random.Random(29)
|
||||
kernels, artifacts, oracles = {}, {}, {}
|
||||
for name in tier.KERNELS:
|
||||
bundle = tier.WORK / (name + '.zx')
|
||||
output = subprocess.run([tier.tool('zi2zx'), 'run', '--backend', 'engine', bundle],
|
||||
env=env, check=True, capture_output=True, text=True).stdout
|
||||
expected = '0' if name == 'Printing' else output.splitlines()[-1]
|
||||
stdout = output if name == 'Printing' else output[:output.rstrip('\n').rfind('\n') + 1]
|
||||
example = {'id': name, 'expected': expected, 'stdout': stdout}
|
||||
commands = {'c': [tier.WORK / (name + '-c'), '-', expected],
|
||||
'before': [args.before, bundle, expected], 'after': [args.after, bundle, expected]}
|
||||
kernels[name] = (example, commands)
|
||||
oracles[name] = example
|
||||
artifacts[name] = {'bundle': identity(bundle), 'c': identity(commands['c'][0])}
|
||||
artifacts.update(before=identity(args.before), after=identity(args.after),
|
||||
engine=identity(tier.tool('zi2zx')), driver=identity(__file__))
|
||||
runs = {name: {label: [] for label in ('c', 'before', 'after')} for name in kernels}
|
||||
order = []
|
||||
for round_index in range(11):
|
||||
jobs = [(name, label) for name in kernels for label in runs[name]]
|
||||
rng.shuffle(jobs)
|
||||
for name, label in jobs:
|
||||
example, commands = kernels[name]
|
||||
command = [*commands[label], '11']
|
||||
measured = tier.platforms.measure(command, example, env, gate)
|
||||
measured['command'] = [str(part) for part in command]
|
||||
runs[name][label].append(measured)
|
||||
order.append([round_index, name, label])
|
||||
print(f'round {round_index + 1}/11 complete', flush=True)
|
||||
summary = {name: {label: summarize_samples([run['execution_ms'] for run in values])
|
||||
for label, values in labels.items()} for name, labels in runs.items()}
|
||||
report = {'host': platform.node(), 'virtualization': virt.stdout.strip(),
|
||||
'measured_at': datetime.now(timezone.utc).isoformat(), 'learning': 'off',
|
||||
'rounds': 11, 'samples_per_run': 11, 'seed': 29, 'artifacts': artifacts,
|
||||
'oracles': oracles, 'order': order, 'runs': runs, 'summary': summary,
|
||||
'methodology': '11 shuffled matched rounds; identical bundles, frozen static runtime runners and C references. '
|
||||
'Each run warms 150 ms then measures 11 calibrated batches; every checksum and stdout is verified '
|
||||
'against the instruction engine. Symmetric inclusive 1.5xIQR applied within each run and across '
|
||||
'run medians; raw samples and excluded indices retained. ' + GATE_METHOD}
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(json.dumps(report, indent=2) + '\n')
|
||||
print('kernel | C us | before us | after us | after/before')
|
||||
for name, labels in summary.items():
|
||||
c, before, after = (labels[label]['median_ms'] * 1000 for label in ('c', 'before', 'after'))
|
||||
print(f'{name} | {c:.3f} | {before:.3f} | {after:.3f} | {after / before:.4f}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -417,7 +417,7 @@ def main():
|
||||
if not equality[target]:
|
||||
raise AssertionError(f'{target} source and saved IR emission differ')
|
||||
for kind, root, source in [('source', FIX, ZI), ('saved', IR, SAVED)]:
|
||||
repeated([BIN / 'zi2zx', 'bundle', '--root', root,
|
||||
repeated([BIN / 'zi2zx', '--root', root,
|
||||
'--module-path', ROOT / 'std', '--entry', 'records:Answer',
|
||||
'-o', OUT / f'{kind}.zx', source], 'ziran', f'{kind} to zx')
|
||||
if (OUT / 'source.zx').read_bytes() != (OUT / 'saved.zx').read_bytes():
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
{"asset_bytes":1000000,"bundle_bytes":1000692,"identity":[147,148,66,160,185,37,92,215,181,45,229,48,116,97,194,17,173,248,74,122,33,182,120,24,121,31,155,135,145,43,82,196],"assets_identity":[37,194,20,27,176,58,156,51,209,194,4,13,69,223,87,93,255,20,92,193,155,239,170,211,42,234,171,211,37,3,109,169],"content_identity":[108,103,45,1,245,77,89,231,112,223,169,153,115,163,113,48,113,31,49,89,3,223,68,96,77,140,35,110,78,198,249,239],"samples_ns":[3903304,3873521,4031240,4568817,6078163,3885425,3876850,3944065,3884335,3928744,3890097]}
|
||||
{"asset_bytes":75000000,"bundle_bytes":75000692,"identity":[147,148,66,160,185,37,92,215,181,45,229,48,116,97,194,17,173,248,74,122,33,182,120,24,121,31,155,135,145,43,82,196],"assets_identity":[140,146,218,49,232,156,101,169,130,212,253,247,203,195,97,51,232,190,195,46,219,94,140,192,154,83,197,124,198,90,126,67],"content_identity":[64,40,38,203,59,101,215,125,236,47,86,79,228,16,218,27,45,233,227,11,167,141,242,136,122,26,95,251,42,38,194,28],"samples_ns":[291416430,283968212,291549050,298719639,289953063,292520883,291144700,294325959,288278339,295167755,294985478]}
|
||||
@@ -0,0 +1,2 @@
|
||||
{"asset_bytes":1000000,"bundle_bytes":1000692,"identity":[147,148,66,160,185,37,92,215,181,45,229,48,116,97,194,17,173,248,74,122,33,182,120,24,121,31,155,135,145,43,82,196],"samples_ns":[7222309,6136048,5406500,5068298,5066495,5061515,5073100,5063878,5085195,5071416,5097492]}
|
||||
{"asset_bytes":75000000,"bundle_bytes":75000692,"identity":[147,148,66,160,185,37,92,215,181,45,229,48,116,97,194,17,173,248,74,122,33,182,120,24,121,31,155,135,145,43,82,196],"samples_ns":[370829279,386735547,372795918,369875583,369998273,368584362,374932839,374786265,367915773,369741776,369379626]}
|
||||
@@ -0,0 +1,2 @@
|
||||
{"asset_bytes":1000000,"bundle_bytes":1000692,"identity":[147,148,66,160,185,37,92,215,181,45,229,48,116,97,194,17,173,248,74,122,33,182,120,24,121,31,155,135,145,43,82,196],"assets_identity":[37,194,20,27,176,58,156,51,209,194,4,13,69,223,87,93,255,20,92,193,155,239,170,211,42,234,171,211,37,3,109,169],"content_identity":[108,103,45,1,245,77,89,231,112,223,169,153,115,163,113,48,113,31,49,89,3,223,68,96,77,140,35,110,78,198,249,239],"samples_ns":[4990679,4987763,4987935,5142164,5027256,5087958,5318701,5087849,5219289,5103524,5232645]}
|
||||
{"asset_bytes":75000000,"bundle_bytes":75000692,"identity":[147,148,66,160,185,37,92,215,181,45,229,48,116,97,194,17,173,248,74,122,33,182,120,24,121,31,155,135,145,43,82,196],"assets_identity":[140,146,218,49,232,156,101,169,130,212,253,247,203,195,97,51,232,190,195,46,219,94,140,192,154,83,197,124,198,90,126,67],"content_identity":[64,40,38,203,59,101,215,125,236,47,86,79,228,16,218,27,45,233,227,11,167,141,242,136,122,26,95,251,42,38,194,28],"samples_ns":[372081671,372255239,371330025,372086237,376693237,368831105,376700490,374658442,371790001,372838035,367910734]}
|
||||
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"host": "alpha",
|
||||
"physical_host_verified": "systemd-detect-virt: none",
|
||||
"cpu": "Intel Core i7-8700 @ 3.20GHz",
|
||||
"affinity_cpu": 3,
|
||||
"cflags": "-O2",
|
||||
"learning": "off",
|
||||
"samples": 11,
|
||||
"warmups": 1,
|
||||
"comparison": "sequential before/after, not interleaved",
|
||||
"source_baseline_revision": "31f41848",
|
||||
"source_before_sha256": "81643c45850d1651b54589f38746254828e41884c9dc703036af9e84b955dc6d",
|
||||
"source_after_sha256": "6a0f297a22859a6cbbc51c34cd7fdef383ae4686efc7638827fc9cc018b28a57",
|
||||
"probe_sha256": "f622aea386518d3da48288321c956709426689637ee60c5006a849de784fd6b6",
|
||||
"generated_reader_before_sha256": "9c24004eea4ed3ece86a577c6b935a37ee52ba5b0fa18e9f391ebbc80200d7b0",
|
||||
"generated_reader_after_sha256": "1543fa2b1d5a0febc05f1c121440e5b449f651a7995a77df8fda398bea43d46a",
|
||||
"executable_before_sha256": "c4eded0e74d65498dc639b38f090aebcb5108dd88ec733b4c2ed194779e8d030",
|
||||
"executable_after_sha256": "918e9d027125774ab8add1c4e0a27e216662c446aef7e5ba1cc37f6648cb1eb7",
|
||||
"linked_runtime_sha256": "fe2641e24f151d0d00b8d0316e1b6820bb6eab09f4772ef8458ba93215272d02",
|
||||
"identities_match": true,
|
||||
"statistics": "symmetric 1.5xIQR fences, inclusive interpolated quartiles",
|
||||
"results": [
|
||||
{
|
||||
"asset_bytes": 1000000,
|
||||
"before": {
|
||||
"median_ms": 5.087958,
|
||||
"MB_s": 196.5425029058809,
|
||||
"excluded_indices": []
|
||||
},
|
||||
"after": {
|
||||
"median_ms": 3.890097,
|
||||
"MB_s": 257.06299868615105,
|
||||
"excluded_indices": [
|
||||
3,
|
||||
4
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"asset_bytes": 75000000,
|
||||
"before": {
|
||||
"median_ms": 372.170738,
|
||||
"MB_s": 201.52041077447632,
|
||||
"excluded_indices": [
|
||||
10
|
||||
]
|
||||
},
|
||||
"after": {
|
||||
"median_ms": 292.0349665,
|
||||
"MB_s": 256.8185614855131,
|
||||
"excluded_indices": [
|
||||
1
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"build_command": "env -u DISPLAY -u WAYLAND_DISPLAY CFLAGS=-O2 ZIRAN_LEARN=off LDLIBS=\"$PWD/build/libziran.a\" build-queue -- ziran build --target=c --exe --entry asset_digest:main --root bench --module-path cmd -o build/asset-digest bench/asset_digest.zi",
|
||||
"run_command": "env -u DISPLAY -u WAYLAND_DISPLAY ZIRAN_LEARN=off build-queue -- taskset -c 3 build/asset-digest/asset_digest",
|
||||
"limitations": [
|
||||
"Synthetic package; not a Breeze first-frame measurement.",
|
||||
"Alpha-only x86 result; Android SHA2 throughput is unmeasured.",
|
||||
"Baseline was taken before candidate; this is not an interleaved comparison.",
|
||||
"Content verification and byte/work limits are unchanged."
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
# Executable asset digest throughput on Alpha
|
||||
|
||||
The reader now uses the existing C streaming SHA-256 implementation. It feeds
|
||||
whole strings, encodes small integer fields in one stack buffer, and uses the
|
||||
runtime's shared constants and CPU dispatch. The separate Ziran compressor is
|
||||
removed. Domain tags, integer byte order, budget accounting and identity checks
|
||||
are unchanged.
|
||||
|
||||
| Synthetic asset | Before read (ms) | After read (ms) | Before MB/s | After MB/s |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| 1,000,000 bytes | 5.088 | 3.890 | 196.5 | 257.1 |
|
||||
| 75,000,000 bytes | 372.171 | 292.035 | 201.5 | 256.8 |
|
||||
|
||||
The 75 MB read takes 21.5% less time. These are direct `ZxExecRead` timings on
|
||||
physical Alpha (Intel Core i7-8700), pinned to CPU 3, compiled with `-O2` and
|
||||
learning off. Each series has one warmup and eleven retained raw samples.
|
||||
Before and after were measured sequentially; they were not interleaved.
|
||||
All program, asset and content identities match between implementations.
|
||||
The same symmetric 1.5×IQR rule with inclusive interpolated quartiles applies
|
||||
to every series. Excluded sample indices remain in the metadata.
|
||||
|
||||
The baseline reader source matches the current checkout before the change.
|
||||
Only `compiler_exec_link.zi` changed on Alpha between accepted measurements;
|
||||
the linked runtime archive, compiler, probe and other sources stayed fixed.
|
||||
The temporary reader source edit was restored afterward. Source, executable,
|
||||
generated-reader and runtime hashes, exact commands, excluded indices and
|
||||
computed medians are in [metadata](asset-digest-alpha-metadata.json).
|
||||
Raw samples are in [before](asset-digest-alpha-before.jsonl) and
|
||||
[after](asset-digest-alpha-after.jsonl). An earlier exploratory baseline,
|
||||
before adding all identity fields to the probe's output, is retained in
|
||||
[initial baseline](asset-digest-alpha-before-initial.jsonl) and is not used
|
||||
for the table. The reusable probe is [asset_digest.zi](../asset_digest.zi).
|
||||
|
||||
This is a synthetic asset-size measurement, not Breeze's startup or first-frame
|
||||
time. Android SHA2 acceleration and the application's nested bundles still
|
||||
need measurements on the device. A parent asset digest and a nested bundle's
|
||||
program/asset/file digests cover different byte streams and domain tags, so
|
||||
this change does not skip or reuse any of those validation steps.
|
||||
|
||||
Local verification: the executable bundle test passes independent SHA-256
|
||||
asset identity vectors at 17 sizes (empty payload, SHA padding and block
|
||||
boundaries, binary bytes, and more than 1 MiB), plus reader rejection after
|
||||
payload mutation. Forced portable SHA dispatch passes the same bundle cases.
|
||||
`env -u DISPLAY -u WAYLAND_DISPLAY ZIRAN_LEARN=off build-queue -- sh -c
|
||||
'make check && make check-bootstrap'` passes all 271 retained local tests
|
||||
(284.7 seconds, none reused), and bootstrap output matches. The benchmark
|
||||
registry test also passes; `bench/bench.zi -- asset-digest` supplies the
|
||||
compiler module path and runtime archive used by the probe.
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"baseline_receipt": "bench/results/c-teacher-alpha-six-before.json",
|
||||
"baseline_original_receipt": "bench/results/wasm-tier-targets-2026-11-16.json",
|
||||
"after_receipt": "bench/results/c-teacher-alpha-six-after.json",
|
||||
"meaning": "Calls is folded Fib(20); this control measures wrapper/startup, not recursive-call performance.",
|
||||
"complete": true,
|
||||
"five_fresh_baseline_native_artifacts_match_historical_six": true,
|
||||
"harness_original_sha256": "aaa48e7b68a238e20c33ac07762269f6ab3dce251aa463b0d95c098da0ec9044",
|
||||
"harness_control_sha256": "10f6981cb077a700e1dc15b5b4009eb5c039ef3c0528479df770060f26207dcc",
|
||||
"calls_native_artifact_unchanged": true,
|
||||
"tools_unchanged": true,
|
||||
"harness_restored": true,
|
||||
"finished_unix": 1794863895
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
# C teacher: physical Alpha checkpoint, 2026-11-16
|
||||
|
||||
Compared the baseline [compiler revision](https://github.com/ziranlang/ziran/commit/96c23c7de6bc622225a916dfce18bff04486ba2b) with the [verified learning feature](https://github.com/ziranlang/ziran/commit/36e6caf9643d82b58434f11aad507da79f895922) on physical Alpha, Intel i7-8700. This is a fixed, pushed compiler comparison; later SSA, rotation, vectorizer and returned-record changes are outside this checkpoint. Learning recording and runtime checks were off. All builds and measurements ran serially through Alpha build-queue; every timing has eleven raw samples and symmetric inclusive-quartile 1.5×IQR exclusions.
|
||||
|
||||
The [before](c-teacher-alpha-2026-11-16-before.md) and [after](c-teacher-alpha-2026-11-16-after.md) assembly reports cover all six kernels, Button, Text, Input and hello with GCC 15.2 and Clang 21.1.8 at `-O2`. The after report has 1,506 ranked function comparisons and zero failed workloads. Native map extents identify functions, backward branches identify static loop envelopes, and SIGPROF supplies estimated function shares. Counts and weighted excess are inspection priorities, not cycle estimates or speedup predictions.
|
||||
|
||||
| Ranked finding | Native / C instructions | Native stack reads / writes | Function SIGPROF share | Owner |
|
||||
| --- | ---: | ---: | ---: | --- |
|
||||
| Records / Clang | 382 / 73 | 4 / 260 | 162 / 162 | records and aggregate lane |
|
||||
| Sieve / Clang | 77 / 36 | 2 / 2 | 163 / 163 | SSA, rotation and loop lane |
|
||||
| Hash / GCC | 50 / 26 | 0 / 0 | 158 / 158 | SSA and loop lane |
|
||||
| Printing / GCC | 59 / 32 | 5 / 5 | 35 / 99 | call and memory selection candidates |
|
||||
|
||||
Vectors illustrates the limits of instruction counts: native has 104 instructions versus GCC’s 109, yet runs slower. Native has eleven stack reads and eleven writes versus seven and eight; GCC uses vector registers in its reduction. Stack traffic includes locals and saved registers, and vector-register uses include scalar floating point. Back-edge envelopes include cold paths; loop constants and missing C symbols do not prove LICM or inlining opportunities. Widget startup samples include session/theme setup and do not replace warm scenario timings. Zero samples mean unknown share. Existing detailed path findings were routed to the records, loop and vectorizer owners; this checkpoint adds the controlled Alpha measurements.
|
||||
|
||||
Fresh kernel medians, microseconds per call:
|
||||
|
||||
| Kernel | Native before | Native after | C after | Native/C after |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| Sieve | 64.481 | 64.040 | 34.923 | 1.83 |
|
||||
| Records | 47.748 | 47.181 | 15.743 | 3.00 |
|
||||
| Hash | 40.322 | 40.406 | 27.961 | 1.45 |
|
||||
| Vectors | 62.574 | 62.221 | 32.703 | 1.90 |
|
||||
| Printing | 11.292 | 13.047 | 9.352 | 1.40 |
|
||||
|
||||
The [fresh baseline](c-teacher-alpha-before.json) and [fresh after receipt](c-teacher-alpha-after.json) use the standard lane’s current five-kernel harness. Sieve and Hash emit identical native artifacts before and after, so their small timing differences are noise observations. Records, Vectors and Printing artifacts change. The small Records/Vectors timing changes do not establish a useful speedup; Printing regresses from 11.292 to 13.047 µs and remains open. Native timings amortize one process over 32 calls; C, engine and Wasm time warm in-process calls. Compilation is excluded.
|
||||
|
||||
The original request also includes Calls. The standard lane removed it from its current timing list because Fib(20) is constant folded. The [six-kernel baseline](c-teacher-alpha-six-before.json) preserves the earlier physical-Alpha receipt at the same baseline revision (19:35 UTC), and the [six-kernel after control](c-teacher-alpha-six-after.json) restores Calls for a separate 21:18 UTC run. All five fresh baseline native digests match that older receipt; Calls itself has exactly the same native artifact before and after. Its native median is 6.129 → 5.954 µs (C after 11.450 µs). This is a historical control of a folded result and wrapper/startup overhead, not a fresh paired measurement of recursion. The [control receipt](c-teacher-alpha-2026-11-16-calls-validation.json) records the temporary list change, unchanged tools and exact harness restoration.
|
||||
|
||||
Fresh widget medians, microseconds per scenario:
|
||||
|
||||
| Widget | Native before | Native after | Improvement | C after | Go after |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| Button | 8.807 | 6.969 | 20.9% | 2.726 | 4.162 |
|
||||
| Text | 9.716 | 8.557 | 11.9% | 3.129 | 3.735 |
|
||||
| Input | 12.882 | 9.963 | 22.7% | 3.924 | 6.610 |
|
||||
|
||||
The [before](c-teacher-alpha-2026-11-16-widgets-before.json) and [after](c-teacher-alpha-2026-11-16-widgets-after.json) widget receipts use the same Kryon revision and manifest. They exercise public layout, interaction and paint-command generation with checked batches, excluding pixel rasterization, system fonts and OS I/O. These improvements cover the integrated compiler revisions, including the constructor lane; they are not isolated gains from the learned scalar idioms. The gap to C and Go remains open.
|
||||
|
||||
Provenance required a correction: Alpha’s Kryon manifest pins Ziran v0.5, and `--project` selected that cached compiler even when invoked through the current launcher. The site harness’s compiler metadata alone did not establish the selected compiler. Earlier attempts failed safely and restored source/tools. Both accepted stages used an ignored temporary local override:
|
||||
|
||||
```toml
|
||||
[overrides]
|
||||
ziran = "/home/wao/Projects/ziranlang/ziran"
|
||||
```
|
||||
|
||||
Before each accepted stage, the absolute current `build/bin/ziran pkg path ziran` command from Kryon’s directory resolved to that canonical compiler repository. Generated widget IR was archived and regenerated. The local override and lock bytes were restored afterward. Omega already had the canonical local override, so this discovery does not invalidate its previous widget checkpoint. The parent coordinator and widget lane received the compiler-selection metadata issue for routing a general harness fix.
|
||||
|
||||
The [validation receipt](c-teacher-alpha-2026-11-16-validation.json) records eight tool/runtime hashes, aggregate digests over 1,811 baseline and 1,819 after source files (compiler, harness and Kryon inputs), stable hashes during each stage, and exact preservation of `bench/standard` plus `build/standard`. All 336 tracked compiler/stdlib inputs were verified against the pushed target tree. The receipt retains the failed incremental target build and the successful full rebuild recovery; restored archive timestamps had left generated engine files stale. Both accepted compiler epochs use a full forced rebuild.
|
||||
|
||||
Exact accepted build/measurement commands, inside Alpha `build-queue`, with `ZIRAN_LEARN=off`, `HARMONY_BUILD_LOCAL=1`, and display variables removed:
|
||||
|
||||
```sh
|
||||
make -B -j2 all
|
||||
build/bin/ziran run --target=c bench/bench.zi -- wasm-tier --samples 11 --label c-teacher-alpha-before --output bench/results/c-teacher-alpha-before.json
|
||||
build/bin/ziran run --target=c bench/bench.zi -- library-targets --project /home/wao/Projects/kryonlabs/kryon --manifest /home/wao/Projects/kryonlabs/kryon/tests/widget_benchmarks.json --samples 11
|
||||
build/bin/ziran run --target=c bench/bench.zi -- c-teacher --output bench/results/c-teacher-alpha-2026-11-16-before.md
|
||||
make -B -j2 all
|
||||
build/bin/ziran run --target=c bench/bench.zi -- wasm-tier --samples 11 --label c-teacher-alpha-after --output bench/results/c-teacher-alpha-after.json
|
||||
build/bin/ziran run --target=c bench/bench.zi -- library-targets --project /home/wao/Projects/kryonlabs/kryon --manifest /home/wao/Projects/kryonlabs/kryon/tests/widget_benchmarks.json --samples 11
|
||||
build/bin/ziran run --target=c bench/bench.zi -- c-teacher --output bench/results/c-teacher-alpha-2026-11-16-after.md
|
||||
build/bin/ziran run --target=c bench/bench.zi -- wasm-tier --samples 11 --label c-teacher-alpha-calls-control --output bench/results/c-teacher-alpha-six-after.json
|
||||
```
|
||||
|
||||
All accepted commands returned zero. The completed feature’s Ziran differential tests compare 70,210 C/native output lines across 34 multiply factors, deterministic edge/random inputs and eight integer widths, followed by retained parity. Offline training twice produced byte-identical checked-in table source. Full retained local tests and bootstrap provenance, including concurrent peer changes and the later successful focused site reruns, remain in the [Omega feature summary](c-teacher-omega-2026-11-16-summary.md). No compiler source changed for this report milestone. CI has not been checked for this report. Alpha build tools were updated for measurement; this does not claim an owner launcher installation or a release.
|
||||
@@ -0,0 +1,195 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"host": "alpha",
|
||||
"virtualization": "none",
|
||||
"learning": "off",
|
||||
"checks": false,
|
||||
"started_unix": 1794863300,
|
||||
"baseline_revision": "96c23c7de6bc622225a916dfce18bff04486ba2b",
|
||||
"target_revision": "36e6caf9643d82b58434f11aad507da79f895922",
|
||||
"commands": [
|
||||
{
|
||||
"command": [
|
||||
"make",
|
||||
"-B",
|
||||
"-j2",
|
||||
"all"
|
||||
],
|
||||
"code": 0
|
||||
},
|
||||
{
|
||||
"command": [
|
||||
"build/bin/ziran",
|
||||
"run",
|
||||
"--target=c",
|
||||
"bench/bench.zi",
|
||||
"--",
|
||||
"wasm-tier",
|
||||
"--samples",
|
||||
"11",
|
||||
"--label",
|
||||
"c-teacher-alpha-before",
|
||||
"--output",
|
||||
"bench/results/c-teacher-alpha-before.json"
|
||||
],
|
||||
"code": 0
|
||||
},
|
||||
{
|
||||
"command": [
|
||||
"build/bin/ziran",
|
||||
"run",
|
||||
"--target=c",
|
||||
"bench/bench.zi",
|
||||
"--",
|
||||
"library-targets",
|
||||
"--project",
|
||||
"/home/wao/Projects/kryonlabs/kryon",
|
||||
"--manifest",
|
||||
"/home/wao/Projects/kryonlabs/kryon/tests/widget_benchmarks.json",
|
||||
"--samples",
|
||||
"11"
|
||||
],
|
||||
"code": 0
|
||||
},
|
||||
{
|
||||
"command": [
|
||||
"build/bin/ziran",
|
||||
"run",
|
||||
"--target=c",
|
||||
"bench/bench.zi",
|
||||
"--",
|
||||
"c-teacher",
|
||||
"--output",
|
||||
"bench/results/c-teacher-alpha-2026-11-16-before.md"
|
||||
],
|
||||
"code": 0
|
||||
},
|
||||
{
|
||||
"command": [
|
||||
"git",
|
||||
"fetch",
|
||||
"origin",
|
||||
"master"
|
||||
],
|
||||
"code": 0
|
||||
},
|
||||
{
|
||||
"command": [
|
||||
"make",
|
||||
"-j2",
|
||||
"all"
|
||||
],
|
||||
"code": 2
|
||||
},
|
||||
{
|
||||
"command": [
|
||||
"make",
|
||||
"-B",
|
||||
"-j2",
|
||||
"all"
|
||||
],
|
||||
"code": 0
|
||||
},
|
||||
{
|
||||
"command": [
|
||||
"build/bin/ziran",
|
||||
"run",
|
||||
"--target=c",
|
||||
"bench/bench.zi",
|
||||
"--",
|
||||
"wasm-tier",
|
||||
"--samples",
|
||||
"11",
|
||||
"--label",
|
||||
"c-teacher-alpha-after",
|
||||
"--output",
|
||||
"bench/results/c-teacher-alpha-after.json"
|
||||
],
|
||||
"code": 0
|
||||
},
|
||||
{
|
||||
"command": [
|
||||
"build/bin/ziran",
|
||||
"run",
|
||||
"--target=c",
|
||||
"bench/bench.zi",
|
||||
"--",
|
||||
"library-targets",
|
||||
"--project",
|
||||
"/home/wao/Projects/kryonlabs/kryon",
|
||||
"--manifest",
|
||||
"/home/wao/Projects/kryonlabs/kryon/tests/widget_benchmarks.json",
|
||||
"--samples",
|
||||
"11"
|
||||
],
|
||||
"code": 0
|
||||
},
|
||||
{
|
||||
"command": [
|
||||
"build/bin/ziran",
|
||||
"run",
|
||||
"--target=c",
|
||||
"bench/bench.zi",
|
||||
"--",
|
||||
"c-teacher",
|
||||
"--output",
|
||||
"bench/results/c-teacher-alpha-2026-11-16-after.md"
|
||||
],
|
||||
"code": 0
|
||||
}
|
||||
],
|
||||
"stages": {
|
||||
"before": {
|
||||
"revision": "96c23c7de6bc622225a916dfce18bff04486ba2b",
|
||||
"tools": {
|
||||
"build/bin/ziran": "dd24f284ee21f1217a245b608a1a33b1632fcdbc0ce8938a963e35dcfa3d4f29",
|
||||
"build/bin/zi2c": "2e21cbdd222519dc2f54993721c5168719b0340fc00d4271c4ca101dd8300152",
|
||||
"build/bin/zi2go": "0628df64c2fc17eee1fb64d73e8182906cb559123668a0e648023b8adf1c34d9",
|
||||
"build/bin/zi2zir": "0bea673e4df7d9d8446e179564e60ebab8be739839b6b1047d9a7a8f56f55bd7",
|
||||
"build/bin/zi2zx": "eb47203a4eef36585fcca75340e026e86b2fd34895b22c8dda342e127f956c00",
|
||||
"build/bin/zx2native": "c1cf0932e45b017e8fbc90bb935966c4e67dbd4e700e22ecd52e0346597e1433",
|
||||
"build/bin/zx2wasm": "f621cdbae99ed4abf839861905eba2c22a18839a7c18c3da3d4f7e41bc05ba75",
|
||||
"build/libziran.a": "fdc99f231806aeed93dd1079625cb7e15903051beda4a34d040c22a3d01b4344"
|
||||
},
|
||||
"tools_unchanged": true,
|
||||
"source_files": 1811,
|
||||
"source_epoch_sha256": "e8065511e450ff5bd6cc5c6bc4fc19122d6c2c6de7b3f58fa6d2d57fb3b27297",
|
||||
"changed_sources": []
|
||||
},
|
||||
"after": {
|
||||
"revision": "36e6caf9643d82b58434f11aad507da79f895922",
|
||||
"tools": {
|
||||
"build/bin/ziran": "6f2433eefc3721145be0a6527a77156067b45e78f092d9c8c3e08c40b69c2e39",
|
||||
"build/bin/zi2c": "2e21cbdd222519dc2f54993721c5168719b0340fc00d4271c4ca101dd8300152",
|
||||
"build/bin/zi2go": "0628df64c2fc17eee1fb64d73e8182906cb559123668a0e648023b8adf1c34d9",
|
||||
"build/bin/zi2zir": "0bea673e4df7d9d8446e179564e60ebab8be739839b6b1047d9a7a8f56f55bd7",
|
||||
"build/bin/zi2zx": "50f84b648068e97d7e7ded2937f8cc4400edf5ba9a9b113f61e280275972777f",
|
||||
"build/bin/zx2native": "3e4ce36573c6bc0857b3a571e10088c24464093b5d08a1a7369a1af0cc75891f",
|
||||
"build/bin/zx2wasm": "f621cdbae99ed4abf839861905eba2c22a18839a7c18c3da3d4f7e41bc05ba75",
|
||||
"build/libziran.a": "9d160e94e3a009ad9881171570ae3aa720e4e5b380bebfc79dfa185831158b4e"
|
||||
},
|
||||
"tools_unchanged": true,
|
||||
"source_files": 1819,
|
||||
"source_epoch_sha256": "68b334fd8ed3cc79bc3fc23efb0c5d8a448116fa6f5300f310423034b97a22d8",
|
||||
"changed_sources": []
|
||||
}
|
||||
},
|
||||
"complete": true,
|
||||
"preparation_retry": "Prior attempts rolled back. Kryon --project selected pinned v0.5 despite current launcher; use temporary ignored local toolchain override and verify selected compiler path. Rebuild baseline completely and regenerate widget IR.",
|
||||
"standard_before_sha256": "283ab41156a967162e807d9dedd78aec2a1b54f7fc05f6543fb57784fa2db19b",
|
||||
"widget_selected_toolchain_before": "/home/wao/Projects/ziranlang/ziran",
|
||||
"verified_compiler_source_files": 336,
|
||||
"kryon_configuration_restored": true,
|
||||
"standard_after_sha256": "283ab41156a967162e807d9dedd78aec2a1b54f7fc05f6543fb57784fa2db19b",
|
||||
"standard_unchanged": true,
|
||||
"finished_unix": 1794863723,
|
||||
"recovered_attempts": [
|
||||
{
|
||||
"error": "command failed: make",
|
||||
"rolled_back": true,
|
||||
"reason": "Restored archive timestamps left generated engine files stale; force a complete target rebuild."
|
||||
}
|
||||
],
|
||||
"recovery_command_start_index": 6,
|
||||
"widget_selected_toolchain_after": "/home/wao/Projects/ziranlang/ziran"
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,117 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"native_sha256": "9978ae84253c8a66826459bd18f3379aa9b73784caf6e1942727fc5bffbfe82e",
|
||||
"zx_sha256": "5c47cb8218aeed347661abe511c183dca5e1278e852b5791595e3dcbe7f4b75e",
|
||||
"c_sha256": "c77c158bdc0e61b8c246fb0fb2efd8e62a5f537c6e0ef7fc7e573b897bd6d311",
|
||||
"compiler": "cc (Debian 14.2.0-19) 14.2.0",
|
||||
"candidates": [
|
||||
{
|
||||
"rule": "x86-multiply-constant",
|
||||
"function": "tree_input_SecondaryPointerSample",
|
||||
"factor": 3,
|
||||
"native": "imul r11,rax,0x3",
|
||||
"teacher": "lea rdx,[rax+rax*2]",
|
||||
"precondition": "integer-modulo-width; flags-dead; no-memory",
|
||||
"verified": false
|
||||
},
|
||||
{
|
||||
"rule": "x86-multiply-constant",
|
||||
"function": "tree_TreeRead",
|
||||
"factor": 65536,
|
||||
"native": "imul r11,rcx,0x10000",
|
||||
"teacher": "shl r8,0x10",
|
||||
"precondition": "integer-modulo-width; flags-dead; no-memory",
|
||||
"verified": false
|
||||
},
|
||||
{
|
||||
"rule": "x86-multiply-constant",
|
||||
"function": "cursor_CursorHoverFrameStart",
|
||||
"factor": 16,
|
||||
"native": "imul r11,rax,0x10",
|
||||
"teacher": "shl rdx,0x4",
|
||||
"precondition": "integer-modulo-width; flags-dead; no-memory",
|
||||
"verified": false
|
||||
},
|
||||
{
|
||||
"rule": "x86-multiply-constant",
|
||||
"function": "paint_queue_SnapshotTextJoin",
|
||||
"factor": 512,
|
||||
"native": "imul r11,rdi,0x200",
|
||||
"teacher": "shl rax,0x9",
|
||||
"precondition": "integer-modulo-width; flags-dead; no-memory",
|
||||
"verified": false
|
||||
},
|
||||
{
|
||||
"rule": "x86-multiply-constant",
|
||||
"function": "tree_TreeStoreLabel",
|
||||
"factor": 65536,
|
||||
"native": "imul r11,r9,0x10000",
|
||||
"teacher": "shl rdx,0x10",
|
||||
"precondition": "integer-modulo-width; flags-dead; no-memory",
|
||||
"verified": false
|
||||
},
|
||||
{
|
||||
"rule": "x86-multiply-constant",
|
||||
"function": "contextmenu_Draw",
|
||||
"factor": 16,
|
||||
"native": "imul r11,rax,0x10",
|
||||
"teacher": "shl rbx,0x4",
|
||||
"precondition": "integer-modulo-width; flags-dead; no-memory",
|
||||
"verified": false
|
||||
},
|
||||
{
|
||||
"rule": "x86-multiply-constant",
|
||||
"function": "cursor_CursorHoverFrameCommit",
|
||||
"factor": 16,
|
||||
"native": "imul r11,rax,0x10",
|
||||
"teacher": "shl rax,0x4",
|
||||
"precondition": "integer-modulo-width; flags-dead; no-memory",
|
||||
"verified": false
|
||||
},
|
||||
{
|
||||
"rule": "x86-multiply-constant",
|
||||
"function": "svg_icon_behavior_PaintSvgIcon",
|
||||
"factor": 5,
|
||||
"native": "imul r11,r14,0x5",
|
||||
"teacher": "lea rdx,[r12+r12*4]",
|
||||
"precondition": "integer-modulo-width; flags-dead; no-memory",
|
||||
"verified": false
|
||||
},
|
||||
{
|
||||
"rule": "x86-multiply-constant",
|
||||
"function": "svg_icon_behavior_SvgIconTexture",
|
||||
"factor": 5,
|
||||
"native": "imul r11,rcx,0x5",
|
||||
"teacher": "lea rcx,[rcx+rcx*4]",
|
||||
"precondition": "integer-modulo-width; flags-dead; no-memory",
|
||||
"verified": false
|
||||
},
|
||||
{
|
||||
"rule": "x86-multiply-constant",
|
||||
"function": "svg_icon_behavior_SvgIconCells",
|
||||
"factor": 5,
|
||||
"native": "imul r11,rcx,0x5",
|
||||
"teacher": "lea rsi,[rcx+rcx*4]",
|
||||
"precondition": "integer-modulo-width; flags-dead; no-memory",
|
||||
"verified": false
|
||||
},
|
||||
{
|
||||
"rule": "x86-multiply-constant",
|
||||
"function": "svg_shape_ShapeCoverEdges",
|
||||
"factor": 16,
|
||||
"native": "imul r11,rcx,0x10",
|
||||
"teacher": "shl r12,0x4",
|
||||
"precondition": "integer-modulo-width; flags-dead; no-memory",
|
||||
"verified": false
|
||||
},
|
||||
{
|
||||
"rule": "x86-multiply-constant",
|
||||
"function": "svg_shape_ShapeAddEdge",
|
||||
"factor": 16,
|
||||
"native": "imul r11,rdx,0x10",
|
||||
"teacher": "shl rdx,0x4",
|
||||
"precondition": "integer-modulo-width; flags-dead; no-memory",
|
||||
"verified": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
{
|
||||
"started_unix": 1794856923,
|
||||
"revision": "42dc1b0f41489e8affae19815a52aa3a875ff0d9",
|
||||
"commands": [
|
||||
{
|
||||
"command": [
|
||||
"make",
|
||||
"-j1",
|
||||
"check"
|
||||
],
|
||||
"code": 0
|
||||
},
|
||||
{
|
||||
"command": [
|
||||
"make",
|
||||
"-j1",
|
||||
"check-bootstrap"
|
||||
],
|
||||
"code": 0
|
||||
},
|
||||
{
|
||||
"command": [
|
||||
"build/bin/ziran",
|
||||
"run",
|
||||
"--target=c",
|
||||
"bench/bench.zi",
|
||||
"--",
|
||||
"wasm-tier",
|
||||
"--samples",
|
||||
"11",
|
||||
"--label",
|
||||
"c-teacher-final",
|
||||
"--output",
|
||||
"bench/results/c-teacher-omega-final.json"
|
||||
],
|
||||
"code": 0
|
||||
},
|
||||
{
|
||||
"command": [
|
||||
"build/bin/ziran",
|
||||
"run",
|
||||
"--target=c",
|
||||
"bench/bench.zi",
|
||||
"--",
|
||||
"library-targets",
|
||||
"--project",
|
||||
"/mnt/storage/Projects/kryonlabs/kryon",
|
||||
"--manifest",
|
||||
"/mnt/storage/Projects/kryonlabs/kryon/tests/widget_benchmarks.json",
|
||||
"--samples",
|
||||
"11"
|
||||
],
|
||||
"code": 0
|
||||
},
|
||||
{
|
||||
"command": [
|
||||
"build/bin/ziran",
|
||||
"run",
|
||||
"--target=c",
|
||||
"bench/bench.zi",
|
||||
"--",
|
||||
"c-teacher",
|
||||
"--output",
|
||||
"bench/results/c-teacher-omega-2026-11-16-final.md"
|
||||
],
|
||||
"code": 0
|
||||
}
|
||||
],
|
||||
"changed": [
|
||||
"cmd/compiler_machine_aggregate.zi",
|
||||
"tests/machine_place_cases.zi"
|
||||
],
|
||||
"finished_unix": 1794857182,
|
||||
"complete": false,
|
||||
"source_files": 1056,
|
||||
"start_epoch_sha256": "d1189e0d940d29b38732e3f6ba42344977b296d1369f10cf5c663f9671082574",
|
||||
"end_epoch_sha256": "76ce23f6965ad9660265dd485aaf17fee1e3a52457918f76f8b191efcf10fdde"
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"host": "omega",
|
||||
"learning": "off",
|
||||
"checks": "manual-safety default; test-specific assertions retained",
|
||||
"github_ci": "not checked",
|
||||
"local_tests": [
|
||||
{
|
||||
"receipt": "16151a4867e2fa478e3d0afde52731aaa7a0",
|
||||
"revision": "42dc1b0f41489e8affae19815a52aa3a875ff0d9",
|
||||
"suite": "make -j1 check",
|
||||
"code": 0,
|
||||
"passed": 281,
|
||||
"total": 281,
|
||||
"bootstrap_code": 0,
|
||||
"source_guard": "two concurrent constructor files changed; compiler binaries unchanged"
|
||||
},
|
||||
{
|
||||
"receipt": "34159fa4c599897ee55a627d0b74327deffa",
|
||||
"suite": "constructor canonical build, check and check-bootstrap",
|
||||
"build_code": 0,
|
||||
"bootstrap_code": 0,
|
||||
"passed": 279,
|
||||
"total": 281,
|
||||
"source_guard": "3409 guarded inputs and seven compiler identities unchanged",
|
||||
"failed": [
|
||||
"site_pages.sh: missing targets receipt",
|
||||
"site_targets.sh: Publish one measured host"
|
||||
]
|
||||
},
|
||||
{
|
||||
"receipt": "8382856e6704249164010f4a322be36d05e9",
|
||||
"revision": "efefbb1f40dacbd00972b41126bc26ef5349463e",
|
||||
"command": "env -u DISPLAY -u WAYLAND_DISPLAY ZIRAN_LEARN=off HARMONY_BUILD_LOCAL=1 build-queue -- sh -c 'sh tests/site_pages.sh build/bin/ziran && sh tests/site_targets.sh build/bin/ziran'",
|
||||
"code": 0,
|
||||
"result": "Both prior publication-data failures resolved; pages, matrices, hashes, samples and independent artifact oracles passed."
|
||||
}
|
||||
],
|
||||
"learning_verification": {
|
||||
"receipt": "d001bab87cfb730312d572c86d3128929bc9",
|
||||
"differential_output_lines": 70210,
|
||||
"retained_zx_parity": "passed"
|
||||
},
|
||||
"offline_calibration": {
|
||||
"receipt": "e5cffefb436f30c04174e17009bdec81bc1a",
|
||||
"c_optimization": "-O2",
|
||||
"deterministic_training_repeat": "byte-identical",
|
||||
"selected_policy": 1,
|
||||
"leaf_operations": 0,
|
||||
"same_artifacts": "Both leaf settings produce identical artifacts for all six kernels."
|
||||
}
|
||||
}
|
||||
Loaded 100 of 3478 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user