diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e1731134b78..5a4a262d569 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -149,7 +149,7 @@ jobs: - name: cargo clippy if: (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') && needs.changes.outputs.rust_full != 'false' - run: cargo clippy --locked --workspace --all-targets --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus --no-deps + run: cargo clippy --locked --workspace --exclude lydite-celox --all-targets --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus --no-deps - name: Lint the crates this pull request can affect if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_lint_packages != '' @@ -162,7 +162,7 @@ jobs: if: (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') && needs.changes.outputs.rust_full != 'false' env: RUSTDOCFLAGS: -D warnings - run: cargo doc --locked --workspace --no-deps + run: cargo doc --locked --workspace --exclude lydite-celox --no-deps - name: Build the API documentation this pull request can affect if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_doc_libraries != '' diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml index c7afb638c3f..a5509aebf40 100644 --- a/.github/workflows/codspeed.yml +++ b/.github/workflows/codspeed.yml @@ -4,6 +4,11 @@ on: schedule: - cron: "17 2 * * *" workflow_dispatch: + inputs: + runner_probe: + description: Check Macro Runner availability without building or benchmarking + type: boolean + default: false concurrency: group: ${{ github.workflow }}-${{ github.ref }} @@ -16,9 +21,20 @@ env: permissions: {} jobs: + runner-probe: + name: Probe CodSpeed runner + if: github.event_name == 'workflow_dispatch' && inputs.runner_probe + runs-on: codspeed-macro-arm64-graviton-ubuntu-22-04 + timeout-minutes: 2 + steps: + - name: Verify the ARM64 runner is available + run: test "$(uname -m)" = aarch64 + codspeed: name: CodSpeed - runs-on: ubuntu-latest + if: inputs.runner_probe != true + timeout-minutes: 60 + runs-on: codspeed-macro-arm64-graviton-ubuntu-22-04 outputs: run-id: ${{ steps.benchmarks.outputs.run-id }} permissions: @@ -39,19 +55,20 @@ jobs: tool: cargo-codspeed@5.0.1 - name: Build compile-time benchmarks - run: cargo codspeed build --locked -p celox --bench compilation + run: cargo codspeed build --locked --measurement-mode walltime -p celox --bench compilation - name: Run compile-time benchmarks id: benchmarks + timeout-minutes: 15 uses: CodSpeedHQ/action@v5 with: - mode: simulation - run: cargo codspeed run -p celox + mode: walltime + run: cargo codspeed run --measurement-mode walltime -p celox --bench compilation report: name: Report CodSpeed needs: codspeed - if: always() && (github.ref_name == 'master' || github.ref_name == 'develop') + if: always() && inputs.runner_probe != true && (github.ref_name == 'master' || github.ref_name == 'develop') runs-on: ubuntu-latest timeout-minutes: 10 permissions: diff --git a/.github/workflows/lydite-checks.yml b/.github/workflows/lydite-checks.yml index 92dff0e5283..1176b2834bc 100644 --- a/.github/workflows/lydite-checks.yml +++ b/.github/workflows/lydite-checks.yml @@ -5,8 +5,7 @@ name: Lydite # linted by ci.yml; this workflow owns Lydite tests and conformance gates. on: - # PRs select affected lanes; the heavy bridge runs on PRs only for Lydite-owned - # changes. Daily and manual runs enable every lane and report failures. + # Only Lydite core gates run here. Celox bridge/proof replay is disabled. pull_request: merge_group: schedule: @@ -37,7 +36,6 @@ jobs: runs-on: ubuntu-26.04 outputs: core: ${{ steps.scope.outputs.core }} - bridge: ${{ steps.scope.outputs.bridge }} defaults: run: working-directory: . @@ -57,7 +55,7 @@ jobs: rust: timeout-minutes: 30 needs: changes - if: always() && (needs.changes.result != 'success' || needs.changes.outputs.core == 'true' || needs.changes.outputs.bridge == 'true') + if: always() && (needs.changes.result != 'success' || needs.changes.outputs.core == 'true') runs-on: ubuntu-26.04 steps: - uses: actions/checkout@v7 @@ -72,21 +70,10 @@ jobs: - name: Install recorded solver version run: python -m pip install z3-solver==5.1.0 - name: Test affected Lydite packages and documentation - env: - CORE: ${{ needs.changes.outputs.core }} - BRIDGE: ${{ needs.changes.outputs.bridge }} - DETECTION: ${{ needs.changes.result }} run: | - args=() - if [ "$DETECTION" != success ] || [ "$CORE" = true ]; then - args+=(-p lydite -p lydite-ir -p lydite-solver -p lydite-syntax -p lydite-verify) - fi - if [ "$DETECTION" != success ] || [ "$BRIDGE" = true ]; then - args+=(-p lydite-celox) - fi Z3_BIN="$(command -v z3)" export Z3_BIN - cargo test --locked "${args[@]}" + cargo test --locked -p lydite -p lydite-ir -p lydite-solver -p lydite-syntax -p lydite-verify documentation: needs: changes @@ -110,7 +97,7 @@ jobs: persist-credentials: false - uses: ./.github/actions/setup-rust - name: Build the isolated editor worker - run: cargo build --release --locked --bin lydite-editor + run: cargo build --release --locked -p lydite --bin lydite-editor - name: Check bounded responses and reject deadlock and dropped-request mutants run: | cargo test --release --locked -p lydite --test responses --bin lydite-editor @@ -160,88 +147,9 @@ jobs: if-no-files-found: error retention-days: 14 - # The bridge lanes use the in-tree Celox and share one release build. - bridge: - needs: changes - if: always() && (needs.changes.result != 'success' || needs.changes.outputs.bridge == 'true') - runs-on: ubuntu-26.04 - # Cold builds plus replay and the sequential proof/mutation gates. - timeout-minutes: 150 - steps: - - uses: actions/checkout@v7 - with: - persist-credentials: false - - uses: ./.github/actions/setup-rust - with: - components: rustfmt - - name: Reproduce source violations and AXI4-Lite protocol regressions with Celox - run: ./conformance/axi4lite/run_ci.sh "$RUNNER_TEMP/celox-replay" - - name: Upload complete replay evidence - if: always() - uses: actions/upload-artifact@v7 - with: - name: celox-replay-${{ github.run_id }}-${{ github.run_attempt }} - path: ${{ runner.temp }}/celox-replay/ - if-no-files-found: error - retention-days: 14 - - # Keep collecting proof evidence after a replay failure. - # The conformance gates are pinned to Python 3.12. - - uses: actions/setup-python@v7 - if: ${{ !cancelled() }} - with: - python-version: "3.12" - - name: Run every reusable suite case with proof-backed reads - if: ${{ !cancelled() }} - run: ./conformance/veryl-proof/run_ci.sh "$RUNNER_TEMP/veryl-proof" - - name: Verify symbolic Veryl pipeline against ISA and reject RTL mutants - if: ${{ !cancelled() }} - run: ./conformance/veryl-symbolic/run_ci.sh "$RUNNER_TEMP/veryl-symbolic" - - name: Verify typed lemma candidates and proof-use diagnostics - if: ${{ !cancelled() }} - run: python3 -m audit.lemma_candidates.ci --out "$RUNNER_TEMP/lemma-candidates" - - name: Verify selected RV32I architecture, memory, latency and mutations - if: ${{ !cancelled() }} - run: ./conformance/veryl-symbolic/run_rv32i_ci.sh "$RUNNER_TEMP/selected-rv32i" - - name: Verify fixed automatic-proof held-outs and original-formula mutants - if: ${{ !cancelled() }} - run: ./conformance/veryl-symbolic/run_automatic_ci.sh "$RUNNER_TEMP/automatic-proof" - - name: Verify checked equality sharing and retain explicit Unknown diagnostics - if: ${{ !cancelled() }} - run: | - python3 -m unittest audit.equality_sharing.test_generate audit.equality_sharing.test_evidence audit.equality_sharing.test_ci - python3 -m audit.equality_sharing.ci --checker ../target/release/lydite --out "$RUNNER_TEMP/equality-sharing" - - name: Verify whole-word frontier controls and original-formula mutants - if: ${{ !cancelled() }} - run: | - python3 -m unittest audit.word_frontier.test_generate audit.word_frontier.test_ci - python3 -m audit.word_frontier.ci --checker ../target/release/lydite --expected-checker-sha256 "$(sha256sum ../target/release/lydite | cut -d' ' -f1)" --out "$RUNNER_TEMP/word-frontier" - - name: Verify guarded word expansion and reject escaped guards - if: ${{ !cancelled() }} - run: | - cargo test --release --locked -p lydite-solver equality_sharing::tests - python3 -m unittest audit.guarded_expansion.test_generate audit.guarded_expansion.test_ci - python3 -m audit.guarded_expansion.ci --checker ../target/release/lydite --expected-checker-sha256 "$(sha256sum ../target/release/lydite | cut -d' ' -f1)" --out "$RUNNER_TEMP/guarded-expansion" - - name: Upload proof and diagnostic evidence - if: always() - uses: actions/upload-artifact@v7 - with: - name: veryl-proof-${{ github.run_id }}-${{ github.run_attempt }} - path: | - ${{ runner.temp }}/veryl-proof/ - ${{ runner.temp }}/veryl-symbolic/ - ${{ runner.temp }}/selected-rv32i/ - ${{ runner.temp }}/automatic-proof/ - ${{ runner.temp }}/equality-sharing/ - ${{ runner.temp }}/word-frontier/ - ${{ runner.temp }}/guarded-expansion/ - ${{ runner.temp }}/lemma-candidates/ - if-no-files-found: error - retention-days: 14 - result: name: Lydite checks - needs: [changes, rust, documentation, editor, veryl-fv, bridge] + needs: [changes, rust, documentation, editor, veryl-fv] if: always() runs-on: ubuntu-26.04 defaults: @@ -256,17 +164,17 @@ jobs: import json, os needs = json.loads(os.environ["NEEDS"]) assert needs["changes"]["result"] == "success", needs - assert all(needs["changes"]["outputs"].get(key) in ("true", "false") for key in ("core", "bridge")), needs - for job, lane in {"rust": None, "documentation": "core", "editor": "core", "veryl-fv": "core", "bridge": "bridge"}.items(): + assert needs["changes"]["outputs"].get("core") in ("true", "false"), needs + for job in ("rust", "documentation", "editor", "veryl-fv"): outputs = needs["changes"]["outputs"] - selected = outputs.get(lane) == "true" if lane else any(outputs.get(key) == "true" for key in ("core", "bridge")) + selected = outputs.get("core") == "true" assert needs[job]["result"] == ("success" if selected else "skipped"), (job, needs[job]) PYCODE - # Report daily/manual runs; the bridge does not gate Celox PRs. + # Report daily/manual core runs. report: name: Report Lydite validation - needs: [changes, rust, documentation, editor, veryl-fv, bridge, result] + needs: [changes, rust, documentation, editor, veryl-fv, result] if: ${{ !cancelled() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && (github.ref_name == 'master' || github.ref_name == 'develop') }} runs-on: ubuntu-26.04 permissions: diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index bcc5e607f1e..58c3878c615 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -21,15 +21,14 @@ jobs: - name: Dispatch full CI on develop run: gh workflow run ci.yml --repo "$GITHUB_REPOSITORY" --ref develop - # lydite-checks.yml schedules the default branch itself; its bridge lanes do not run - # for Celox PRs, so check develop's in-tree Celox daily as well. + # Lydite core validation also runs on develop; bridge gates are disabled. queue-lydite-develop: name: Queue develop Lydite validation runs-on: ubuntu-latest env: GH_TOKEN: ${{ github.token }} steps: - - name: Dispatch every Lydite lane on develop + - name: Dispatch Lydite core validation on develop run: gh workflow run lydite-checks.yml --repo "$GITHUB_REPOSITORY" --ref develop # heliodor-bench.yml schedules the stable master lane directly. Dispatch the diff --git a/.github/workflows/publish-crates.yml b/.github/workflows/publish-crates.yml index adf6c1559f0..1854ecf87d2 100644 --- a/.github/workflows/publish-crates.yml +++ b/.github/workflows/publish-crates.yml @@ -107,7 +107,7 @@ jobs: - name: Build Rust API documentation env: RUSTDOCFLAGS: -D warnings - run: cargo doc --locked --workspace --no-deps + run: cargo doc --locked --workspace --exclude lydite-celox --no-deps publish: name: Publish to crates.io diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 095a0dad575..4a0f4e9c930 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -120,6 +120,12 @@ interpreter, native and Cranelift backends in both two-state and four-state mode wide-value latch checks, and a small sorter compilation smoke test. The 257/512-bit per-bit graph cases and sorter sizes 4/8/16/32 are measured by `benches/compilation.rs` in the existing daily/manual CodSpeed workflow. +Compilation benchmarks use CodSpeed walltime measurement on its ARM64 Graviton +Macro Runner: CPU simulation made +a single 512-bit case take tens of minutes. The benchmark step has a 15-minute +timeout and the complete job a 60-minute limit; a timeout is reported as failure. +The organization runner group must allow this public repository to use CodSpeed +Macro Runners. Simulation and walltime measurements have separate baselines. Nested-write benchmarks reuse the same semantic assertions as the small tests. Scaling cases use one iteration without per-case warmups or adaptive sampling; a small counter warms process-global analyzer state before measurement. @@ -130,8 +136,8 @@ CodSpeed reporting workflow. Build and run them with the same CodSpeed harness as CI: ```sh -cargo codspeed build --locked -p celox --bench compilation -cargo codspeed run -p celox +cargo codspeed build --locked --measurement-mode walltime -p celox --bench compilation +cargo codspeed run --measurement-mode walltime -p celox --bench compilation ``` ## Finish validation @@ -294,32 +300,31 @@ Job selection: Lydite has its own test cadence (`scripts/ci-lydite-changes.mjs`): -- Lydite sources and fixtures run its core and bridge lanes. The core lane owns - the proof-engine Rust tests, editor and standalone Veryl conformance. The - bridge lane (`bridge` job) runs replay and proof-backed Veryl/symbolic corpus - gates against the in-tree Celox exporter in one job sharing a release build. -- The bridge takes about an hour of runner time, so Celox changes do not run it - on PRs or queue drafts even when Cargo's dependency graph reaches - `lydite-celox`. The daily and manual runs on `master` (scheduled) and - `develop` (dispatched by `nightly.yml`) enable every lane and report failures - in the issue "Lydite validation is failing on ", closed by the next - passing run. NAPI/JS changes, upstream private tests and Markdown do not - reach Lydite. +- Lydite core sources and fixtures select proof-engine Rust tests, editor and + standalone Veryl conformance. Celox bridge/replay/proof-corpus CI is disabled + for PRs, merge queues, scheduled runs and manual workflow dispatches. + `lydite-celox` remains available for explicit local development, but normal + CI does not build, lint, document or test it. The routine pre-push Cargo + check also excludes it. +- Daily and manual core runs on `master` and `develop` report failures in the + issue "Lydite validation is failing on ". Celox and bridge-crate + changes do not select core gates. - Version-only Release Please diffs, including their queue drafts, skip Lydite. - PR workflows come from the PR's merge ref, so branches based on an older base still carry the earlier `lydite.yml`, which selected every lane. That workflow file stays disabled in repository settings; `lydite-checks.yml` replaces it. Re-enable nothing under the old path. - Shared dependency/toolchain configuration runs the core lane; an unreadable - diff or dependency graph runs both lanes. The graph includes optional, build + diff or dependency graph runs the core lane. The graph includes optional, build and dev edges. A `Cargo.lock` diff selects a lane only when a changed lock entry is in that lane's lockfile dependency closure, so adding a dependency to a Celox crate does not run Lydite. The Nix flake and `ci.yml` do not select Lydite; its jobs use neither. Celox's `conformance/sv-tests/` corpus also skips Lydite; Lydite's fixtures live under `lydite/conformance/`. - Ordinary `ci.yml` tests exclude `lydite*`, including daily and release runs; - formatting/lint/build checks remain there. The dedicated workflow tests the - selected Lydite packages, including doctests, and installs its solver. + lint and API documentation also exclude `lydite-celox`. The dedicated + workflow tests only core Lydite packages, including doctests, and installs + its solver. Cache warming excludes `lydite*`. - `Lydite checks` accepts skipped lanes only when change detection explicitly excludes them, and fails on selected-job failures or cancellations. Repository branch protection must require this check to make it a merge gate. @@ -373,7 +378,7 @@ Local validation uses the behavior-based matrix above. | Daily at 02:37 UTC (11:37 JST) | `heliodor-bench.yml` runs the complete master Linux suite on x86-64 and AArch64. Explicit manual selections retain focused suite runs and ARM64 profiling. PRs do not run this workflow; its tooling tests run in `Lint & Format` with the other script tests. | | Every daily/manual full CI run | Run the pinned upstream `common_cells` Gray code SV TB through `celox run --project`, plus an assertion negative control. Logs are retained for 14 days and failures feed the Full CI issue. See [the reproduction instructions](conformance/common-cells/README.md). | | Every full CI run | Run every shared Veryl and SystemVerilog case against both Verilator and Icarus, with locked Nix tools. Run the live adapter tests normally marked ignored because they need external tools. Preserve reports and per-case diagnostics as artifacts for 14 days, including on failure; matrix failures do not cancel the other comparisons. | -| Affected pull requests and merge groups; daily at 03:41 UTC (12:41 JST); on demand | `lydite-checks.yml` owns Lydite Rust tests, proof, conformance, editor, and mutation gates. Unrelated changes skip these jobs, and Celox changes skip the bridge. Daily and manual runs enable all lanes and report failures in an issue. | +| Affected pull requests and merge groups; daily at 03:41 UTC (12:41 JST); on demand | `lydite-checks.yml` owns Lydite Rust tests, proof, conformance, editor, and mutation gates. Unrelated changes skip these jobs. Bridge gates are disabled; daily and manual runs enable only core lanes and report failures in an issue. | | On demand | Dispatch `ci.yml` on the desired branch to run full CI and external comparisons, regardless of its diff. | | Pull requests that cut a release | A `master` pull request or legacy merge group whose diff changes `.release-please-manifest.json` (only the release pull request does there; syncing it into `develop` is not a release) runs full CI and the external comparisons. `Rust Test & NAPI Build` then requires the comparisons to pass, so a release cannot merge after only change-based checks. Daily and manual full runs do not gate on the comparisons; their failures reach the full CI issue below. A `master` pull request or legacy merge group whose diff cannot be determined is treated the same way. | diff --git a/Cargo.lock b/Cargo.lock index 248419dde03..445b4bbf425 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2851,9 +2851,9 @@ dependencies = [ [[package]] name = "memmap2" -version = "0.9.11" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" dependencies = [ "libc", ] diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 5e45cf13916..bdedcd2e93b 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -291,6 +291,9 @@ pub enum ProcessStatus { /// A synchronous host operation. The delay slot holds its family and /// local site index; the same process resumes after the host responds. HostRequest, + /// A program kernel called `$exit` (IEEE 1800-2023 24.7): it and every + /// other kernel of its program instance ([`ProcessSlots::program`]) end. + Exit, } impl ProcessStatus { @@ -308,6 +311,7 @@ impl ProcessStatus { Self::Yield => 8, Self::Stop => 9, Self::HostRequest => 10, + Self::Exit => 11, } } @@ -323,6 +327,7 @@ impl ProcessStatus { 8 => Some(Self::Yield), 9 => Some(Self::Stop), 10 => Some(Self::HostRequest), + 11 => Some(Self::Exit), _ => None, } } @@ -465,6 +470,12 @@ pub struct ProcessSlots { /// Every delay the kernel suspends for is a constant of at least one /// time unit. pub const_delays: bool, + /// For an `initial` procedure of a program instance (IEEE 1800-2023 + /// 24.3), the status slot of that instance's first such kernel, which + /// every kernel of the instance names: the kernel runs in the reactive + /// region set (24.3.1), and `$exit` and the end of the instance's + /// kernels act on them together (24.7). `None` for design code. + pub program: Option, pub resume: A, pub status: A, pub delay: A, @@ -476,6 +487,7 @@ impl ProcessSlots { is_initializer: self.is_initializer, requires_timed_simulation: self.requires_timed_simulation, const_delays: self.const_delays, + program: self.program.map(&mut map), resume: map(self.resume), status: map(self.status), delay: map(self.delay), @@ -1791,6 +1803,7 @@ mod tests { ProcessStatus::from_code(10), Some(ProcessStatus::HostRequest) ); + assert_eq!(ProcessStatus::from_code(11), Some(ProcessStatus::Exit)); } #[test] diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index 1931a26203b..b141ad8d532 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -368,6 +368,13 @@ impl ProcessKernelBuilder { self.end(ProcessStatus::Finish); } + /// End the kernel and the other kernels of its program instance + /// (`$exit`, IEEE 1800-2023 24.7). No block is open afterwards. + pub fn exit(&mut self) { + self.wait_site = None; + self.end(ProcessStatus::Exit); + } + /// Complete the kernel. If a block is still open, the process ends there. pub fn build(mut self) -> ExecutionUnit { if self.builder.has_open_block() { diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index f74172ab2a4..18232d0b2a4 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1732,6 +1732,7 @@ fn lower_processes( is_initializer: false, requires_timed_simulation: false, const_delays: false, + program: None, resume: lowering .hidden .declare(name("resume"), PROCESS_RESUME_WIDTH, false), diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 8cf8c077ad4..fa7ee3be2e1 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -4537,6 +4537,7 @@ fn lower_initial_processes( is_initializer: process.is_initializer(), requires_timed_simulation: process.is_scheduled_edge(), const_delays: false, + program: None, resume: declare("resume", PROCESS_RESUME_WIDTH), status: declare("status", PROCESS_STATUS_WIDTH), delay: declare("delay", PROCESS_DELAY_WIDTH), diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index b9a0e39311b..7585cab6a7e 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -21,6 +21,8 @@ pub struct ResolvedSchedule { pub(crate) signal_to_id: FxHashMap, pub(crate) signal_index_by_id: Vec, pub(crate) processes: Vec, + /// The kernels of program instances, in declaration order. + pub(crate) program_processes: Vec, /// Counted signals and the domains their counters trigger. pub(crate) counted: Vec, pub(crate) counted_by_offset: FxHashMap, @@ -190,6 +192,7 @@ impl ResolvedSchedule { .iter() .map(|process| ProcessRefs { is_initializer: process.slots.is_initializer, + program: process.slots.program.as_ref().map(resolve), resume: resolve(&process.slots.resume), starts_with_event_wait: process.slots.requires_timed_simulation, status: resolve(&process.slots.status), @@ -299,6 +302,12 @@ impl ResolvedSchedule { event_info, signal_to_id, signal_index_by_id, + program_processes: processes + .iter() + .enumerate() + .filter(|(_, process)| process.program.is_some()) + .map(|(index, _)| index) + .collect(), processes, counted, counted_by_offset, diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 7523e231da0..515b4cfb26e 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -454,7 +454,7 @@ impl SimulationState { E: SimulationExecutor, { self.slot_passes = 0; - match self.step_round(executor, time, Vec::new(), Vec::new(), true) { + match self.step_round(executor, time, Vec::new(), Vec::new(), true, false) { Ok(()) => { self.finish_timed_boundary(executor, time)?; Ok(Some(time)) diff --git a/crates/celox-runtime/src/simulation/nba.rs b/crates/celox-runtime/src/simulation/nba.rs index f2395e208c7..00b493f1180 100644 --- a/crates/celox-runtime/src/simulation/nba.rs +++ b/crates/celox-runtime/src/simulation/nba.rs @@ -32,7 +32,14 @@ impl SimulationState { let Some((lsb, width)) = refs.range(backend) else { return Ok(()); }; - self.process_state.nba_queue.push(NbaUpdate { + // A program process's update waits for the Re-NBA region (IEEE + // 1800-2023 24.3.1). + let queue = if self.model.processes[process].program.is_some() { + &mut self.process_state.re_nba_queue + } else { + &mut self.process_state.nba_queue + }; + queue.push(NbaUpdate { target: refs.target, lsb, width, @@ -57,6 +64,7 @@ impl SimulationState { self.model .processes .iter() + .filter(|process| process.program.is_none()) .flat_map(|process| &process.nba_sites) .filter_map(|site| site.pending) .filter(|&pending| backend.get_as::(pending) != 0) @@ -76,45 +84,12 @@ impl SimulationState { self.event_values(executor.backend(), &mut round.before); round.transitions.clear(); } - for update in &queued { - let new = NbaValue::Queued(&update.value); - self.publish_update(executor.backend_mut(), update, new); - if several { - self.record_transitions(executor.backend(), round); - } - } + self.publish_queued(executor, round, &queued, several); // Keep the queue's storage for the next time slot. queued.clear(); self.process_state.nba_queue = queued; if flagged > 0 { - for process in 0..self.model.processes.len() { - for site in 0..self.model.processes[process].nba_sites.len() { - let backend = executor.backend_mut(); - let Some(pending) = self.model.processes[process].nba_sites[site].pending - else { - continue; - }; - if backend.get_as::(pending) == 0 { - continue; - } - backend.set(pending, 0u8); - let site = &self.model.processes[process].nba_sites[site]; - let Some((lsb, width)) = site.range(backend) else { - continue; - }; - let (target, value) = (site.target, site.value); - let update = NbaUpdate { - target, - lsb, - width, - value: Value::default(), - }; - self.publish_update(backend, &update, NbaValue::Staged(value)); - if several { - self.record_transitions(executor.backend(), round); - } - } - } + self.publish_flagged(executor, round, false, several); } if several { let transitions = std::mem::take(&mut round.transitions); @@ -126,6 +101,103 @@ impl SimulationState { true } + /// Publish the nonblocking assignments of program processes (the Re-NBA + /// region, IEEE 1800-2023 4.4.2.8): the queued ones in issue order, then + /// the flagged ones. Like the writes of a process run, each is recorded + /// in `round.transitions` for the caller to settle. Returns whether any + /// was published. + pub(super) fn publish_re_nba(&mut self, executor: &mut E, round: &mut Round) -> bool + where + E: SimulationExecutor, + { + let any_flagged = self.model.has_pending_nba_sites && { + let backend = executor.backend(); + self.model + .program_processes + .iter() + .flat_map(|&process| &self.model.processes[process].nba_sites) + .filter_map(|site| site.pending) + .any(|pending| backend.get_as::(pending) != 0) + }; + if self.process_state.re_nba_queue.is_empty() && !any_flagged { + return false; + } + self.event_values(executor.backend(), &mut round.before); + let mut queued = std::mem::take(&mut self.process_state.re_nba_queue); + self.publish_queued(executor, round, &queued, true); + // Keep the queue's storage for the next time slot. + queued.clear(); + self.process_state.re_nba_queue = queued; + if any_flagged { + self.publish_flagged(executor, round, true, true); + } + true + } + + /// Publish `queued` in issue order, recording the transitions of each in + /// `round.transitions` if `record`. + fn publish_queued( + &mut self, + executor: &mut E, + round: &mut Round, + queued: &[NbaUpdate], + record: bool, + ) where + E: SimulationExecutor, + { + for update in queued { + let new = NbaValue::Queued(&update.value); + self.publish_update(executor.backend_mut(), update, new); + if record { + self.record_transitions(executor.backend(), round); + } + } + } + + /// Publish the flagged nonblocking sites of the program processes if + /// `program`, otherwise of the design's, in declaration order, recording + /// the transitions of each in `round.transitions` if `record`. + fn publish_flagged( + &mut self, + executor: &mut E, + round: &mut Round, + program: bool, + record: bool, + ) where + E: SimulationExecutor, + { + for process in 0..self.model.processes.len() { + if self.model.processes[process].program.is_some() != program { + continue; + } + for site in 0..self.model.processes[process].nba_sites.len() { + let backend = executor.backend_mut(); + let Some(pending) = self.model.processes[process].nba_sites[site].pending else { + continue; + }; + if backend.get_as::(pending) == 0 { + continue; + } + backend.set(pending, 0u8); + let site = &self.model.processes[process].nba_sites[site]; + let Some((lsb, width)) = site.range(backend) else { + continue; + }; + let (target, value) = (site.target, site.value); + let update = NbaUpdate { + target, + lsb, + width, + value: Value::default(), + }; + self.publish_update(backend, &update, NbaValue::Staged(value)); + if record { + self.record_transitions(executor.backend(), round); + } + } + } + } + /// Write `update`, whose value is `new`, into its target. An update /// inside a target of at most 64 bits with one state plane is merged as /// `u64`; any other as [`Value`]. diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index a5a5525fc53..aa0a94ff8e9 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -293,6 +293,9 @@ impl SimulationState { ready: state.ready.iter().copied().collect(), inactive: state.inactive.iter().copied().collect(), nba_queue: state.nba_queue.clone(), + reactive: state.reactive.iter().copied().collect(), + re_inactive: state.re_inactive.iter().copied().collect(), + re_nba_queue: state.re_nba_queue.clone(), domain_counters: state.domain_counters.clone(), declarations_pending: self.declarations_pending, host_pending: self.host_pending, @@ -319,6 +322,9 @@ pub struct ScheduleKey { pub ready: Vec, pub inactive: Vec, pub nba_queue: Vec, + pub reactive: Vec, + pub re_inactive: Vec, + pub re_nba_queue: Vec, pub domain_counters: Vec<[u32; 3]>, pub declarations_pending: bool, pub host_pending: bool, diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index 3faece18b35..bc74b2729d8 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -1,12 +1,19 @@ //! The process phase of a round: running ready kernels and filing them //! where they resume. +use std::collections::BTreeSet; + use celox_design::{HostRequestKind, ProcessStatus}; use super::SimulationState; use super::host::SimulationExecutor; use super::round::Round; -use crate::{SimulatorErrorCode, backend::SimBackend, timing::Halt}; +use super::wait::wake_in_region; +use crate::{ + SimulatorErrorCode, + backend::SimBackend, + timing::{Halt, ProcessState}, +}; impl SimulationState { /// Execute static declaration initializers before any ordinary process, @@ -132,13 +139,25 @@ impl SimulationState { } Some(ProcessStatus::InactiveDelay) => { let delay = delay(); - if delay == 0 { - self.process_state.inactive.insert(process); - } else { + if delay != 0 { self.wake_after(current_time, delay, process)?; + } else if self.model.processes[process].program.is_some() { + // A program process resumes in the Re-Inactive + // region (IEEE 1800-2023 4.4.2.7). + self.process_state.re_inactive.insert(process); + } else { + self.process_state.inactive.insert(process); + } + } + Some(ProcessStatus::Done) => { + if self.model.processes[process].program.is_some() { + self.program_kernel_ended(executor.backend())?; } } - Some(ProcessStatus::Done) => {} + Some(ProcessStatus::Exit) => { + self.exit_program(executor.backend_mut(), process)?; + self.program_kernel_ended(executor.backend())?; + } Some(ProcessStatus::Finish) => return Err(Halt::Finish), Some(ProcessStatus::Wait | ProcessStatus::Pending) => { let site = delay() as usize; @@ -169,7 +188,10 @@ impl SimulationState { // simulation does. Some(ProcessStatus::Stop) => { self.stopped = true; - self.process_state.ready.insert(process); + let ProcessState { + ready, reactive, .. + } = &mut self.process_state; + wake_in_region(&self.model.processes, ready, reactive, process); return Err(Halt::Stop); } Some(ProcessStatus::Yield) => { @@ -195,17 +217,18 @@ impl SimulationState { where E: SimulationExecutor, { - if self.process_state.ready.is_empty() { + let reactive = round.reactive; + if self.region_ready(reactive).is_empty() { return Ok(false); } self.event_values(executor.backend(), &mut round.before); let mut resume_process = round.resume_process.take(); if let Some(process) = resume_process { - self.process_state.ready.remove(&process); + self.region_ready(reactive).remove(&process); } while let Some(process) = resume_process .take() - .or_else(|| self.process_state.ready.pop_first()) + .or_else(|| self.region_ready(reactive).pop_first()) { loop { let again = self.run_process(executor, current_time, process, returns); @@ -222,7 +245,7 @@ impl SimulationState { // Before the next run, its edges must be seen. After the last // one, the check following the settle sees them: a settle // does not write what processes write. - if again || !self.process_state.ready.is_empty() { + if again || !self.region_ready(reactive).is_empty() { self.observe_driven(executor.backend()); } if !again { @@ -233,6 +256,55 @@ impl SimulationState { Ok(true) } + /// The processes ready in the Reactive region if `reactive`, otherwise in + /// the Active region. + #[inline] + fn region_ready(&mut self, reactive: bool) -> &mut BTreeSet { + if reactive { + &mut self.process_state.reactive + } else { + &mut self.process_state.ready + } + } + + /// `$exit` of program kernel `process` (IEEE 1800-2023 24.7): every + /// kernel of its program instance ends, as if it had run to its end. + fn exit_program(&mut self, backend: &mut B, process: usize) -> Result<(), Halt> { + let program = self.model.processes[process] + .program + .ok_or(SimulatorErrorCode::InternalError)?; + for &index in &self.model.program_processes { + let refs = &self.model.processes[index]; + if refs.program != Some(program) { + continue; + } + backend.set(refs.status, ProcessStatus::Done.code()); + let state = &mut self.process_state; + state.waiters.remove(index); + state.ready.remove(&index); + state.reactive.remove(&index); + state.re_inactive.remove(&index); + } + let model = &self.model; + self.process_wakeups + .retain(|std::cmp::Reverse((_, index))| { + model.processes[*index].program != Some(program) + }); + Ok(()) + } + + /// A program kernel ended. Once every program kernel has, the simulation + /// ends with an implicit `$finish` (IEEE 1800-2023 24.3). + fn program_kernel_ended(&self, backend: &B) -> Result<(), Halt> { + let done = ProcessStatus::Done.code(); + let all_done = self + .model + .program_processes + .iter() + .all(|&process| backend.get_as::(self.model.processes[process].status) == done); + if all_done { Err(Halt::Finish) } else { Ok(()) } + } + /// Mark the edges the processes of a pass caused and settle them. fn settle_pass(&mut self, executor: &mut E, round: &mut Round) -> Result<(), Halt> where @@ -290,6 +362,27 @@ impl SimulationState { } else { self.observe_driven(executor.backend()); } + if round.reactive { + // The Reactive region is empty: the Re-Inactive region's + // processes resume, and once both are empty the Re-NBA region + // publishes the program's nonblocking assignments. Design + // processes and domains wait for the active region set (IEEE + // 1800-2023 4.5, 24.3.1). + if !self.process_state.reactive.is_empty() { + continue; + } + if !self.process_state.re_inactive.is_empty() { + let inactive = std::mem::take(&mut self.process_state.re_inactive); + self.process_state.reactive.extend(inactive); + continue; + } + if self.publish_re_nba(executor, round) { + self.settle_pass(executor, round)?; + self.observe_driven(executor.backend()); + continue; + } + return Ok(()); + } if !self.process_state.ready.is_empty() { continue; } diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index 813b446c1a2..c1738942c0f 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -18,6 +18,10 @@ use crate::{ /// Bookkeeping of one round of a time slot. #[derive(Default)] pub(super) struct Round { + /// The round's process phase is the reactive region set's: it runs + /// program processes, and the design activity they create follows it + /// (IEEE 1800-2023 4.5). + pub(super) reactive: bool, /// The stopped process resumes before any newly woken ready processes. pub(super) resume_process: Option, /// Event ids whose trigger survives the settling filter. @@ -89,7 +93,8 @@ impl Round { impl Round { /// Start a round, keeping the buffers of earlier ones. - fn reset(&mut self, track_stable_edges: bool) { + fn reset(&mut self, track_stable_edges: bool, reactive: bool) { + self.reactive = reactive; self.resume_process = None; self.scheduled_trigger_ids.make_empty(); self.track_stable_edges = track_stable_edges; @@ -422,7 +427,8 @@ impl SimulationState { /// trigger evaluate, zero-delay processes run in the inactive region, /// and only then are nonblocking assignments published. A round /// without ready processes and counted signals does exactly the batch - /// step. + /// step. In a `reactive` round the process phase is that of the reactive + /// region set, and the domains its processes trigger evaluate after it. pub(super) fn step_round( &mut self, executor: &mut E, @@ -430,6 +436,7 @@ impl SimulationState { events_to_process: Vec>, ready_processes: Vec, entry: bool, + reactive: bool, ) -> Result<(), Halt> where E: SimulationExecutor, @@ -474,7 +481,7 @@ impl SimulationState { } let mut round = self.scratch.take().unwrap_or_default(); - round.reset(events_to_process.is_empty()); + round.reset(events_to_process.is_empty(), reactive); round.begin_scan(self.model.domain_kinds.len()); self.process_state.ready.extend(ready_processes); executor.backend_mut().clear_triggered_bits(); diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index f5e2bde7145..d516834414e 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -170,7 +170,14 @@ impl SimulationState { } ready.retain(|&process| !self.model.processes[process].starts_with_event_wait); } - self.step_round(executor, current_time, events_to_process, ready, true)?; + self.step_round( + executor, + current_time, + events_to_process, + ready, + true, + false, + )?; self.end_time(executor, current_time) } @@ -185,15 +192,32 @@ impl SimulationState { loop { let ready = self.take_ready_processes(current_time); if ready.is_empty() && self.process_state.ready.is_empty() { - break; + // The active region set is empty: the reactive region set + // runs, and the design activity it creates runs in the active + // region set again (IEEE 1800-2023 4.5). + if !self.reactive_pending() { + break; + } + self.charge_pass()?; + self.step_round(executor, current_time, Vec::new(), Vec::new(), false, true)?; + continue; } self.charge_pass()?; - self.step_round(executor, current_time, Vec::new(), ready, false)?; + self.step_round(executor, current_time, Vec::new(), ready, false, false)?; } executor.try_finish_timed_step(current_time)?; Ok(()) } + /// Whether a region of the reactive region set holds work. + #[inline] + fn reactive_pending(&self) -> bool { + let state = &self.process_state; + !state.reactive.is_empty() + || !state.re_inactive.is_empty() + || !state.re_nba_queue.is_empty() + } + /// Count a round or a pass of the process phase against the slot's /// budget, so that processes resuming at one time forever end the step /// with an error instead of hanging it. @@ -225,7 +249,9 @@ impl SimulationState { })) } - /// Remove the processes waiting for `time`, in declaration order. + /// Remove the processes waiting for `time`, in declaration order. Program + /// processes resume in the Reactive region (IEEE 1800-2023 24.3.1): they + /// join its queue, and only design processes are returned. fn take_ready_processes(&mut self, time: u64) -> Vec { let mut ready = Vec::new(); while let Some(&Reverse((wakeup, process))) = self.process_wakeups.peek() { @@ -233,7 +259,11 @@ impl SimulationState { break; } self.process_wakeups.pop(); - ready.push(process); + if self.model.processes[process].program.is_some() { + self.process_state.reactive.insert(process); + } else { + ready.push(process); + } } ready } @@ -259,7 +289,7 @@ impl SimulationState { if self.finished { return None; } - if !self.process_state.ready.is_empty() { + if !self.process_state.ready.is_empty() || !self.process_state.reactive.is_empty() { return Some(self.scheduler.time); } let process = self.process_wakeups.peek().map(|&Reverse((time, _))| time); diff --git a/crates/celox-runtime/src/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index bfbd004c30d..d9f4c083796 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -1,5 +1,7 @@ //! Waiting processes: registering waits and testing them against writes. +use std::collections::BTreeSet; + use celox_design::CounterKind; use super::SimulationState; @@ -7,8 +9,8 @@ use crate::{ SignalRef, SimulatorErrorCode, backend::SimBackend, timing::{ - Halt, ProcessState, StateView, Value, copy_planes, encode_planes, occurs, planes, - planes_equal, planes_occur, read, + Halt, ProcessRefs, ProcessState, StateView, Value, copy_planes, encode_planes, occurs, + planes, planes_equal, planes_occur, read, }, }; @@ -148,7 +150,12 @@ impl SimulationState { fn check_waits(&mut self, backend: &B, only: Option, driven_only: bool) { let processes = &self.model.processes; let state = StateView::new(backend); - let ProcessState { waiters, ready, .. } = &mut self.process_state; + let ProcessState { + waiters, + ready, + reactive, + .. + } = &mut self.process_state; waiters.retain(driven_only, |process, waiter| { let terms = &processes[process].wait_sites[waiter.site]; let mut wake = false; @@ -210,7 +217,7 @@ impl SimulationState { }; } if wake { - ready.insert(process); + wake_in_region(processes, ready, reactive, process); } !wake }); @@ -231,7 +238,12 @@ impl SimulationState { /// Show the waits one value the host wrote to `signal`. pub(super) fn observe_host_write(&mut self, signal: SignalRef, value: &Value) { let processes = &self.model.processes; - let ProcessState { waiters, ready, .. } = &mut self.process_state; + let ProcessState { + waiters, + ready, + reactive, + .. + } = &mut self.process_state; waiters.retain(false, |process, waiter| { let terms = &processes[process].wait_sites[waiter.site]; let mut wake = false; @@ -253,13 +265,29 @@ impl SimulationState { } } if wake { - ready.insert(process); + wake_in_region(processes, ready, reactive, process); } !wake }); } } +/// Make the woken `process` ready: in the Reactive region if it is a program +/// process (IEEE 1800-2023 24.3.1), otherwise in the Active region. +#[inline] +pub(super) fn wake_in_region( + processes: &[ProcessRefs], + ready: &mut BTreeSet, + reactive: &mut BTreeSet, + process: usize, +) { + if processes[process].program.is_some() { + reactive.insert(process); + } else { + ready.insert(process); + } +} + /// What one term of a waiting process compares against. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Baseline { diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 113a88a9975..9edb4ed0927 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -154,6 +154,10 @@ pub struct NbaSiteRefs { #[derive(Clone, Debug, PartialEq, Eq)] pub struct ProcessRefs { pub is_initializer: bool, + /// The status slot naming the program instance of a program kernel + /// ([`celox_design::ProcessSlots::program`]), which runs in the reactive + /// region set. + pub program: Option, pub resume: SignalRef, /// A converted edge procedure starts by registering its event control /// before scheduled time-zero inputs are applied. @@ -172,6 +176,7 @@ impl ProcessRefs { pub fn new(status: SignalRef, delay: SignalRef) -> Self { Self { is_initializer: false, + program: None, resume: status, starts_with_event_wait: false, status, @@ -333,6 +338,15 @@ pub struct ProcessState { pub inactive: std::collections::BTreeSet, /// Queued nonblocking assignments, in issue order. pub nba_queue: Vec, + /// Program processes ready to run in the Reactive region of the current + /// time (IEEE 1800-2023 4.4.2.6). + pub reactive: std::collections::BTreeSet, + /// Program processes that resume in the Re-Inactive region (`#0`, + /// 4.4.2.7). + pub re_inactive: std::collections::BTreeSet, + /// Nonblocking assignments of program processes for the Re-NBA region + /// (4.4.2.8), in issue order. + pub re_nba_queue: Vec, /// Counter values each counted domain last triggered on, by counted /// signal index and kind. pub domain_counters: Vec<[u32; 3]>, diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/block_opt.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/block_opt.rs index 29b2be92e07..4132ef88968 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/block_opt.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/block_opt.rs @@ -351,30 +351,20 @@ fn coalesce_static_stores>> = HashMap::default(); - // Pre-index loads by address for efficient safety checks. - // Each entry is (instruction_index, offset, width, is_dynamic). - let mut load_index: HashMap, usize)>> = HashMap::default(); + // Moving a store to the end of a merged run must cross neither a read + // nor a later overlapping write. In particular, a narrow overwrite can + // sit between two adjacent candidate ranges in instruction order. + let mut access_index: HashMap, usize)>> = HashMap::default(); + let mut barriers = Vec::new(); for (idx, inst) in instructions.iter().enumerate() { - match inst { - SIRInstruction::Load(_, addr, SIROffset::Static(off), w) => { - load_index - .entry(addr.clone()) - .or_default() - .push((idx, Some(*off), *w)); - } - SIRInstruction::Load(_, addr, SIROffset::PackedElements { bit_offset, .. }, w) => { - load_index - .entry(addr.clone()) - .or_default() - .push((idx, Some(*bit_offset), *w)); - } - SIRInstruction::Load(_, addr, SIROffset::Dynamic(_) | SIROffset::Element { .. }, w) => { - load_index - .entry(addr.clone()) - .or_default() - .push((idx, None, *w)); - } - _ => {} + if is_memory_barrier(inst) { + barriers.push(idx); + } + if let Some((addr, offset, width, _)) = mem_access_info(inst) { + access_index + .entry(addr.clone()) + .or_default() + .push((idx, offset, width)); } } @@ -438,7 +428,7 @@ fn coalesce_static_stores insert_at_index { - return false; - } + let first_barrier = barriers.partition_point(|&idx| idx <= s.index); + if barriers + .get(first_barrier) + .is_some_and(|&idx| idx <= insert_at_index) + { + return false; + } + let first = accesses.partition_point(|&(idx, _, _)| idx <= s.index); + let end = accesses.partition_point(|&(idx, _, _)| idx <= insert_at_index); + !accesses[first..end].iter().any(|&(_, load_off, load_w)| { match load_off { None => true, // dynamic offset — conservatively unsafe Some(lo) => { @@ -1823,6 +1817,73 @@ mod tests { assert_eq!(reg_counter, 1); } + #[test] + fn store_coalescing_preserves_intervening_overlapping_writes() { + for intervening_offset in [ + SIROffset::Static(3), + SIROffset::PackedElements { + bit_offset: 3, + element_width: 1, + }, + SIROffset::Dynamic(RegisterId(2)), + SIROffset::Element { + index: RegisterId(2), + element_width: 2, + bit_offset: 1, + dynamic_bit_offset: None, + }, + ] { + let mut instructions = vec![ + SIRInstruction::Imm(RegisterId(0), SIRValue::new(0u8)), + SIRInstruction::Imm(RegisterId(1), SIRValue::new(1u8)), + SIRInstruction::Imm(RegisterId(2), SIRValue::new(1u8)), + SIRInstruction::Store(7u32, SIROffset::Static(2), 2, RegisterId(0), vec![], vec![]), + SIRInstruction::Store(7, intervening_offset, 1, RegisterId(1), vec![], vec![]), + SIRInstruction::Store(7, SIROffset::Static(1), 1, RegisterId(1), vec![], vec![]), + ]; + let original = instructions.clone(); + let mut registers = [ + (RegisterId(0), logic(2)), + (RegisterId(1), logic(1)), + (RegisterId(2), logic(32)), + ] + .into_iter() + .collect(); + let mut counter = 2; + // Merging the writes at bits 1 and 2..3 would move the latter + // past the intervening write of bit 3, erasing its new value. + assert!(!coalesce_static_stores_with_types( + &mut instructions, + &mut registers, + &mut counter, + &HashMap::default() + )); + assert_eq!(instructions, original); + } + } + + #[test] + fn store_coalescing_keeps_disjoint_intervening_writes_optimizable() { + let mut instructions = vec![ + SIRInstruction::Imm(RegisterId(0), SIRValue::new(0u8)), + SIRInstruction::Imm(RegisterId(1), SIRValue::new(1u8)), + SIRInstruction::Store(7u32, SIROffset::Static(2), 2, RegisterId(0), vec![], vec![]), + SIRInstruction::Store(7, SIROffset::Static(5), 1, RegisterId(1), vec![], vec![]), + SIRInstruction::Store(7, SIROffset::Static(1), 1, RegisterId(1), vec![], vec![]), + ]; + let mut registers = [(RegisterId(0), logic(2)), (RegisterId(1), logic(1))] + .into_iter() + .collect(); + let mut counter = 1; + assert!(coalesce_static_stores_with_types( + &mut instructions, + &mut registers, + &mut counter, + &HashMap::default() + )); + verify(instructions, registers); + } + #[test] fn store_coalescing_marks_cross_element_transfer_explicitly() { let mut instructions = (0..4) diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_coalesce_stores.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_coalesce_stores.rs index 62c246c8e4b..7e265d4bce5 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_coalesce_stores.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_coalesce_stores.rs @@ -2,6 +2,7 @@ use crate::HashMap; use crate::HashSet; use crate::PassOptions; use crate::ir::*; +use std::collections::BTreeMap; use std::sync::Arc; use super::block_opt::aggregate_static_offset; @@ -51,6 +52,14 @@ struct StoreCandidate { comb_capture_sites: Vec, } +#[derive(Default)] +struct StoreGroup { + candidates: Vec, + // Open groups have disjoint ranges. The predecessor of a new range's + // end suffices to detect overlap without quadratic scans of large blocks. + ranges: BTreeMap, +} + fn coalesce_block( block: &mut BasicBlock, register_map: &mut HashMap, @@ -62,15 +71,38 @@ fn coalesce_block( // // groups: addr -> vec of candidates (current open group) // sealed_groups: completed groups ready for coalescing analysis - let mut groups: HashMap> = HashMap::default(); + let mut groups: HashMap = HashMap::default(); let mut sealed_groups: Vec> = Vec::new(); for (i, inst) in block.instructions.iter().enumerate() { + if inst.is_host_interaction() { + for (_, group) in groups.drain() { + if group.candidates.len() >= 2 { + sealed_groups.push(group.candidates); + } + } + } match inst { SIRInstruction::Store(addr, SIROffset::Static(off), width, src, triggers, sites) if triggers.is_empty() && sites.is_empty() => { - groups.entry(*addr).or_default().push(StoreCandidate { + let Some(end) = off.checked_add(*width) else { + seal_group(&mut groups, addr, &mut sealed_groups); + continue; + }; + let overlaps = groups.get(addr).is_some_and(|group| { + group + .ranges + .range(..end) + .next_back() + .is_some_and(|(_, &previous_end)| previous_end > *off) + }); + if overlaps { + seal_group(&mut groups, addr, &mut sealed_groups); + } + let group = groups.entry(*addr).or_default(); + group.ranges.insert(*off, end); + group.candidates.push(StoreCandidate { addr: *addr, inst_index: i, offset: *off, @@ -82,21 +114,12 @@ fn coalesce_block( SIRInstruction::Load(_, addr, _, _) => { seal_group(&mut groups, addr, &mut sealed_groups); } - SIRInstruction::Commit(src, _, _, _, _) => { - // Commit reads from src region + SIRInstruction::Commit(src, dst, _, _, _) => { seal_group(&mut groups, src, &mut sealed_groups); + seal_group(&mut groups, dst, &mut sealed_groups); } - // A Store with Dynamic offset could alias any static offset - SIRInstruction::Store( - addr, - SIROffset::Dynamic(_) - | SIROffset::Element { .. } - | SIROffset::PackedElements { .. }, - _, - _, - _, - _, - ) => { + // Noncandidate writes can overlap an open run or expose its state. + SIRInstruction::Store(addr, ..) => { seal_group(&mut groups, addr, &mut sealed_groups); } _ => {} @@ -104,9 +127,9 @@ fn coalesce_block( } // Flush remaining open groups - for (_, candidates) in groups.drain() { - if candidates.len() >= 2 { - sealed_groups.push(candidates); + for (_, group) in groups.drain() { + if group.candidates.len() >= 2 { + sealed_groups.push(group.candidates); } } @@ -273,13 +296,13 @@ fn coalesce_block( } fn seal_group( - groups: &mut HashMap>, + groups: &mut HashMap, addr: &RegionedAbsoluteAddr, sealed_groups: &mut Vec>, ) { - if let Some(candidates) = groups.remove(addr) { - if candidates.len() >= 2 { - sealed_groups.push(candidates); + if let Some(group) = groups.remove(addr) { + if group.candidates.len() >= 2 { + sealed_groups.push(group.candidates); } } } @@ -321,6 +344,33 @@ mod tests { } } + #[test] + fn overlapping_store_seals_the_open_run() { + let addr = make_addr(0); + for middle in [ + SIRInstruction::Store(addr, SIROffset::Static(3), 1, RegisterId(1), vec![], vec![]), + SIRInstruction::Commit(make_addr(1), addr, SIROffset::Static(3), 1, vec![]), + ] { + let instructions = vec![ + SIRInstruction::Imm(RegisterId(0), SIRValue::new(0u8)), + SIRInstruction::Imm(RegisterId(1), SIRValue::new(1u8)), + SIRInstruction::Store(addr, SIROffset::Static(2), 2, RegisterId(0), vec![], vec![]), + middle, + SIRInstruction::Store(addr, SIROffset::Static(1), 1, RegisterId(1), vec![], vec![]), + ]; + let registers = [ + (RegisterId(0), RegisterType::Logic { width: 2 }), + (RegisterId(1), RegisterType::Logic { width: 1 }), + ] + .into_iter() + .collect(); + let mut eu = make_eu(instructions.clone(), registers); + CoalesceStoresPass::default().run(&mut eu, &PassOptions::default()); + assert_eq!(eu.blocks[&BlockId(0)].instructions, instructions); + eu.verify(); + } + } + #[test] fn test_basic_contiguous_coalescing() { // 3 contiguous 1-bit stores to bits 0, 1, 2 of the same variable diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index 30c65da968d..26f8a919e5c 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -808,6 +808,47 @@ (eval) (assert_eq y 2)) +(case static_function_unpacked_scratch_bits_at_element_boundaries + (source "scratch_bits.sv" #" + module Top(input logic [5:0] index, output logic [57:0] y); + function [58:0] identity(input logic [5:0] selected); + logic [57:0] words[57:0]; + for (integer i=0; i<58; i=i+1) begin + words[i]='0; + words[i][i]=1'b1; + end + // The high result bit retains its value, so the function executes + // through the procedural path rather than symbolic substitution. + identity[57:0]=words[selected]; + endfunction + assign y=identity(index); + endmodule + "#) + (top Top) + (for bit (range 0 58) + (modify (set index bit)) + (assert_eq y (<< 1 bit)))) + +(case static_function_partial_writes_preserve_last_write + (source "partial_writes.sv" #" + module Top(input logic d, output wire [2:0] y); + function [4:0] update(input logic value); + update[3:2]='0; + update[3]=value; + update[1]=1'b1; + endfunction + wire [4:0] result=update(d); + assign y=result[3:1]; + endmodule + "#) + (top Top) + (modify (set d 1)) + (assert_eq y 5) + (modify (set d 0)) + (assert_eq y 1) + (modify (set d 1)) + (assert_eq y 5)) + (case constant_functions_preserve_concat_operand_widths (source "constant_concat.sv" #" module Top(output logic [15:0] a,b, output logic [7:0] zero_part); diff --git a/crates/celox/benches/compilation.rs b/crates/celox/benches/compilation.rs index d99104ba6c7..984d896b73d 100644 --- a/crates/celox/benches/compilation.rs +++ b/crates/celox/benches/compilation.rs @@ -58,7 +58,7 @@ fn benchmark_scaling(c: &mut Criterion) { // Warm analyzer state before any measured span, including filtered runs. compile_default(COUNTER, "Top", Some(("N", 1))); // Each large design runs once: no five-run warmup or adaptive resampling. - // CodSpeed simulation measures one iteration; walltime uses the same schedule. + // Walltime uses this fixed schedule even for the largest graphs. for n in [4, 8, 16, 32] { c.bench_function(&format!("compile/sorter_tree/n{n}"), |b| { b.iter_manual_unstable(IterManualOptions::new(), || { diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 0c95b249cc8..7278978181c 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 34; +const CONTAINER_VERSION: u16 = 35; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index ff7cbbfbb6e..4320699814e 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -59,7 +59,17 @@ impl NativeProgramInstance { /// /// The image's machine code must come from a trusted source. Image /// validation is structural and does not authenticate executable code. + /// + /// An image with process kernels, which only a timed + /// [`crate::Simulation`] runs, fails to attach. pub unsafe fn from_image(image: NativeProgramImage) -> Result { + let schema = image.runtime_schema(); + if !schema.processes.is_empty() { + let origin = schema.process_origins.first().cloned().unwrap_or_default(); + return Err(NativeProgramLoadError::Attach(SimulatorError::new( + crate::SimulatorErrorKind::ProcessRequiresSimulation(origin), + ))); + } // Safety: upheld by this constructor's caller. let shared = Arc::new( unsafe { SharedNativeCode::from_image(image) } diff --git a/crates/celox/src/optimizer/sir.rs b/crates/celox/src/optimizer/sir.rs index e0fe93ea969..2d6987d2f47 100644 --- a/crates/celox/src/optimizer/sir.rs +++ b/crates/celox/src/optimizer/sir.rs @@ -115,9 +115,10 @@ pub(crate) fn optimize_native_merged_chain( .unpacked_arrays .iter() .filter(|(_, array)| { - (1..=64).contains(&array.element_width) - && array.element_stride * 8 != array.element_width - && array.plane_size <= 256 + // Element boundaries are a storage contract, including for + // large arrays and wide elements. Omitting them lets merged + // block optimization coalesce writes across padding gaps. + array.element_width != 0 && array.element_stride * 8 != array.element_width }) .flat_map(|(&address, array)| { [STABLE_REGION, WORKING_REGION, SPARSE_WORKING_REGION].map(move |region| { diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index 6287e96a9ee..1bcda23254f 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -11,6 +11,10 @@ //! each kernel in [`SchedulerSlots::wake`]. It inlines the units the //! reference loop calls, so their code is unchanged. //! +//! A settle whose results nothing reads before the next one is deferred +//! (see [`Lazy`]): it runs only before what observes it, at the point the +//! reference loop ran it. +//! //! Periodic host clocks (`add_clock`) on clock events no design code writes //! run in the same loop: their edges apply at the start of a slot, before //! any kernel, and re-arm at its end. A design without kernels gets the @@ -166,6 +170,46 @@ struct Plan { /// The storage combinational logic reads, when a settle whose inputs did /// not change may be skipped; `None` when every settle runs. settle_reads: Option>, + /// Where the settles run when they wait until their results are read; + /// `None` when every settle runs where the reference loop's does. + lazy: Option, +} + +/// Deferred settles. The reference loop settles after every pass of the +/// process phase and after the NBA region; the unit keeps such a settle +/// pending (the dirty flag stays set) until something observes its +/// results, and runs it where the reference ran it last, so every observer +/// sees what it sees in the reference: a kernel, before the slot it may run +/// in; a domain, before it evaluates (or the fused unit computes what it +/// reads); the host, before the run returns. Observers of the settled state +/// are units that load storage combinational logic writes, and units that +/// may end the run in the middle of a slot (`$finish`, an error), where the +/// reference's state is the last settle's. Only a settle that is a function +/// of its inputs may wait: one that reads what an earlier settle left (see +/// [`retains_state`]) is an activation of its own. +struct Lazy { + /// Per process kernel, whether its runs observe the settled state. + kernels: Vec, + /// Per event, how its domain evaluates with a settle pending. + domains: Vec, + /// Whether the units of several triggered domains observe the settled + /// state. + several: bool, + /// The latest slot from which no delay of a kernel overflows: a run that + /// returns for an overflow in the middle of a later slot returns the last + /// settle's state. + latest: u64, +} + +/// How a domain evaluates while a settle is pending. +enum DomainSettle { + /// It does not observe the settled state. + Pending, + /// It reads what combinational logic writes: its fused units compute + /// what it reads, then evaluate and apply, leaving the settle pending. + Fused(Vec), + /// The settle runs first. + Settled, } impl Plan { @@ -355,6 +399,8 @@ impl Plan { let unit = &sir.processes[index]; let reason = if slots.is_initializer { Some("a declaration initializer") + } else if slots.program.is_some() { + Some("a program process runs in the reactive region set") } else if slots.requires_timed_simulation { Some("an edge procedure") } else if !process.host_requests.is_empty() { @@ -547,6 +593,95 @@ impl Plan { }) .collect() }); + // A settle may wait for its readers only when it is a function of + // its inputs that cannot fail: when it would end the run, it must do + // so in its own slot; when it reads what an earlier settle left (a + // latch, a guarded process's snapshots of its inputs, feedback), the + // settles in between are activations of their own. + let comb_stores: HashSet = sir.eval_comb.iter().flat_map(stores).collect(); + let lazy = settle_reads + .as_ref() + .filter(|_| { + !sir.eval_comb.iter().any(fails) + && !retains_state(&sir.eval_comb, &storage, &comb_stores) + }) + .map(|_| { + // The waits never watch what combinational logic writes, so + // they see the same with a settle pending. + debug_assert!( + kernels + .iter() + .flatten() + .filter_map(|kernel| kernel.wait.as_ref()) + .all(|wait| !comb_stores.contains(&storage(wait.signal))), + "a compiled wait watches a combinational output" + ); + let reads = + |unit: &Unit| loads(unit).any(|source| comb_stores.contains(&storage(source))); + let ends = |unit: &Unit| fails(unit) || emits_finish(unit, &finish_sites); + let observes = |unit: &Unit| reads(unit) || ends(unit); + let mut longest = 0; + for (index, kernel) in kernels.iter().enumerate() { + if kernel.as_ref().is_some_and(|kernel| kernel.wait.is_none()) { + let bound = + delay_bound(&sir.processes[index], schema.processes[index].delay); + longest = longest.max(bound); + } + } + let domains = events + .iter() + .map(|event| { + if event.eval_apply.iter().any(ends) { + return DomainSettle::Settled; + } + if !event.eval_apply.iter().any(reads) { + return DomainSettle::Pending; + } + let fused = &sir.eval_comb_apply_ffs; + let aliased = fused.keys().any(|key| { + *key != event.signal && topology.canonical(*key) == event.signal + }); + match fused.get(&event.signal) { + Some(units) if !aliased => DomainSettle::Fused(units.clone()), + _ => DomainSettle::Settled, + } + }) + .collect(); + let several = events.iter().any(|event| { + event + .eval_only + .iter() + .chain(&event.apply) + .flatten() + .any(observes) + }); + Lazy { + // A kernel's `$finish` is its status. + kernels: kernels + .iter() + .enumerate() + .map(|(index, kernel)| { + let unit = &sir.processes[index]; + kernel.is_some() + && (observes(unit) + || !statuses_only( + unit, + schema.processes[index].status, + &[ + ProcessStatus::Delay, + ProcessStatus::InactiveDelay, + ProcessStatus::Wait, + ProcessStatus::Nba, + ProcessStatus::Done, + ], + )) + }) + .collect(), + domains, + several, + latest: u64::MAX - longest, + } + }); let plan = Self { events, kernels, @@ -554,6 +689,7 @@ impl Plan { fallback, finish_sites, settle_reads, + lazy, }; let edged = plan.edged(); if edged.len() > 1 @@ -593,13 +729,17 @@ impl Plan { fn generate(&self, program: &LaidOutProgram, slots: &SchedulerSlots) -> Unit { let schema = &program.runtime.runtime_schema; let edged = self.edged(); + let mut b = Builder::new(); + let comb = b.new_block(); let mut g = Generator { - b: Builder::new(), + b, slots, finish_sites: &self.finish_sites, exits: Vec::new(), settle_reads: self.settle_reads.as_ref(), shared: program.shared_storage(), + comb, + continuations: Vec::new(), }; let waits: Vec<(usize, &Wait)> = self .kernels @@ -641,10 +781,14 @@ impl Plan { any = g.binary(1, any, BinaryOp::Or, waiting); } // Or the earliest next edge of a host clock, when the run has any. + // The clocks armed at the start of the slot, which the re-arm at its + // end compares with. + let mut started = None; if !self.clocks.is_empty() { let armed = g.load(slots.clock_armed, SCHEDULER_TIME_WIDTH); let zero = g.constant(0, SCHEDULER_CLOCKS); let clocked = g.binary(1, armed, BinaryOp::Ne, zero); + started = Some((armed, clocked)); let scan = g.b.new_block(); let joined_time = g.b.alloc_bit(SCHEDULER_TIME_WIDTH, false); let joined_any = g.b.alloc_bit(1, false); @@ -677,13 +821,70 @@ impl Plan { let stop = g.binary(1, after, BinaryOp::Or, none); let run = g.b.new_block(); let limit_exit = g.exit_block(SchedulerExit::Limit); + // The host reads the run's results settled. + let stopped = match &self.lazy { + Some(_) => g.b.new_block(), + None => limit_exit, + }; g.b.seal_block(SIRTerminator::Branch { cond: stop, - true_block: (limit_exit, Vec::new()), + true_block: (stopped, Vec::new()), false_block: (run, Vec::new()), }); + if self.lazy.is_some() { + g.b.switch_to_block(stopped); + g.settle_then(limit_exit); + } + // The kernels due now are ready. g.b.switch_to_block(run); + let mut ready = g.constant(0, MAX_KERNELS); + for &index in &delays { + let wake = g.load(slots.wake[index], SCHEDULER_TIME_WIDTH); + let waiting = g.waiting(index); + let due = g.binary(1, wake, BinaryOp::Eq, time); + let due = g.binary(1, due, BinaryOp::And, waiting); + let bit = g.bit(due, ordinals[index]); + ready = g.binary(MAX_KERNELS, ready, BinaryOp::Or, bit); + } + g.store(slots.ready, SCHEDULER_TIME_WIDTH, ready); + // A pending settle runs, as at the end of the last slot, before a + // kernel that observes it may run: one due now, any waiting one, + // which may wake in any pass, or any one in a slot after which a + // delay may overflow. + if let Some(lazy) = &self.lazy { + let waits = waits.iter().any(|&(index, _)| lazy.kernels[index]); + let observers = delays + .iter() + .filter(|&&index| lazy.kernels[index]) + .fold(0u64, |mask, &index| mask | 1 << ordinals[index]); + let late = lazy.latest < u64::MAX; + if waits || observers != 0 || late { + let mut observed = g.constant(u64::from(waits), 1); + if observers != 0 { + let mask = g.constant(observers, MAX_KERNELS); + let due = g.binary(MAX_KERNELS, ready, BinaryOp::And, mask); + let zero = g.constant(0, MAX_KERNELS); + let due = g.binary(1, due, BinaryOp::Ne, zero); + observed = g.binary(1, observed, BinaryOp::Or, due); + } + if late { + let latest = g.constant(lazy.latest, SCHEDULER_TIME_WIDTH); + let after = g.binary(1, time, BinaryOp::GtU, latest); + observed = g.binary(1, observed, BinaryOp::Or, after); + } + let settle = g.b.new_block(); + let slot = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: observed, + true_block: (settle, Vec::new()), + false_block: (slot, Vec::new()), + }); + g.b.switch_to_block(settle); + g.settle_then(slot); + g.b.switch_to_block(slot); + } + } g.store(slots.now, SCHEDULER_TIME_WIDTH, time); let count = g.load(slots.count, SCHEDULER_TIME_WIDTH); let one = g.constant(1, SCHEDULER_TIME_WIDTH); @@ -711,18 +912,6 @@ impl Plan { levels = g.binary(MAX_EVENTS, levels, BinaryOp::Or, value); } g.store(slots.levels, SCHEDULER_TIME_WIDTH, levels); - // The kernels due now are ready; the edges of the slot collect in - // `exit_arg`. - let mut ready = g.constant(0, MAX_KERNELS); - for &index in &delays { - let wake = g.load(slots.wake[index], SCHEDULER_TIME_WIDTH); - let waiting = g.waiting(index); - let due = g.binary(1, wake, BinaryOp::Eq, time); - let due = g.binary(1, due, BinaryOp::And, waiting); - let bit = g.bit(due, ordinals[index]); - ready = g.binary(MAX_KERNELS, ready, BinaryOp::Or, bit); - } - g.store(slots.ready, SCHEDULER_TIME_WIDTH, ready); // The host clocks due now set their levels, in event order, before // any kernel runs; their edges start the slot's edges, which // collect in `exit_arg`. A clock whose edge applied waits for its @@ -732,14 +921,7 @@ impl Plan { let finish_exit = g.exit_block(SchedulerExit::Finish); let internal_exit = g.exit_block(SchedulerExit::Internal); let pick = g.b.new_block(); - // The clocks armed at the start of the slot, which the re-arm at its - // end compares with. - let mut started = None; - if !self.clocks.is_empty() { - let armed = g.load(slots.clock_armed, SCHEDULER_TIME_WIDTH); - let zero = g.constant(0, SCHEDULER_CLOCKS); - let clocked = g.binary(1, armed, BinaryOp::Ne, zero); - started = Some((armed, clocked)); + if let Some((armed, clocked)) = started { let apply = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { cond: clocked, @@ -967,57 +1149,23 @@ impl Plan { } // The settles after a pass and after the domains share one copy of - // combinational logic. + // combinational logic. A deferred settle after a pass runs for the + // kernels that may run in another. g.b.switch_to_block(pass_end); let none = g.constant(u64::MAX, SCHEDULER_TIME_WIDTH); g.store(slots.current, SCHEDULER_TIME_WIDTH, none); - let comb = g.b.new_block(); - g.call_comb(comb, 1); - - // A settle whose inputs did not change since the last one would - // write what combinational logic already holds: it is skipped. - g.b.switch_to_block(comb); - if g.settle_reads.is_some() { - let dirty = g.load(slots.dirty, SCHEDULER_FLAG_WIDTH); - let zero = g.constant(0, SCHEDULER_FLAG_WIDTH); - let changed = g.binary(1, dirty, BinaryOp::Ne, zero); - let settle = g.b.new_block(); - let settled = g.b.new_block(); - g.b.seal_block(SIRTerminator::Branch { - cond: changed, - true_block: (settle, Vec::new()), - false_block: (settled, Vec::new()), - }); - g.b.switch_to_block(settle); - for unit in &program.sir.eval_comb { - g.inline(unit, finish_exit); - } - let clean = g.constant(0, SCHEDULER_FLAG_WIDTH); - g.store(slots.dirty, SCHEDULER_FLAG_WIDTH, clean); - g.b.seal_block(SIRTerminator::Jump(settled, Vec::new())); - g.b.switch_to_block(settled); - } else { - for unit in &program.sir.eval_comb { - g.inline(unit, finish_exit); - } - } - let continuation = g.load(slots.cont, SCHEDULER_FLAG_WIDTH); let settled = g.b.new_block(); let slot_end = g.b.new_block(); - g.b.seal_block(SIRTerminator::Switch { - selector: continuation, - cases: vec![ - SIRSwitchCase { - value: 1u8.into(), - target: settled, - }, - SIRSwitchCase { - value: 2u8.into(), - target: slot_end, - }, - ], - default: internal_exit, - }); + let wait_observers = self + .lazy + .as_ref() + .is_some_and(|lazy| waits.iter().any(|&(index, _)| lazy.kernels[index])); + match &self.lazy { + Some(_) => { + g.b.seal_block(SIRTerminator::Jump(settled, Vec::new())); + } + None => g.settle_then(settled), + } // After the settle of a pass the waits see its writes; woken // kernels run in another pass. @@ -1027,11 +1175,20 @@ impl Plan { let zero = g.constant(0, MAX_KERNELS); let more = g.binary(1, ready, BinaryOp::Ne, zero); let domains = g.b.new_block(); + let another = if wait_observers { + g.b.new_block() + } else { + pick + }; g.b.seal_block(SIRTerminator::Branch { cond: more, - true_block: (pick, Vec::new()), + true_block: (another, Vec::new()), false_block: (domains, Vec::new()), }); + if wait_observers { + g.b.switch_to_block(another); + g.settle_then(pick); + } // The domains the edges trigger, then the NBA region. g.b.switch_to_block(domains); @@ -1049,7 +1206,10 @@ impl Plan { // Without a domain, published nonblocking values settle once more. g.b.switch_to_block(untriggered); - if staged.is_empty() { + if self.lazy.is_some() { + g.publish(&staged); + g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); + } else if staged.is_empty() { g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); } else { let mut any = g.constant(0, 1); @@ -1065,7 +1225,7 @@ impl Plan { false_block: (slot_end, Vec::new()), }); g.b.switch_to_block(publish_settle); - g.call_comb(comb, 2); + g.settle_then(slot_end); } g.b.switch_to_block(triggered); @@ -1103,7 +1263,17 @@ impl Plan { false_block: (next, Vec::new()), }); g.b.switch_to_block(unit); - for unit in &event.eval_apply { + let units = match self.lazy.as_ref().map(|lazy| &lazy.domains[index]) { + None | Some(DomainSettle::Pending) => &event.eval_apply, + Some(DomainSettle::Fused(units)) => units, + Some(DomainSettle::Settled) => { + let evaluate = g.b.new_block(); + g.settle_then(evaluate); + g.b.switch_to_block(evaluate); + &event.eval_apply + } + }; + for unit in units { g.inline_writer(unit, finish_exit); } g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); @@ -1116,6 +1286,15 @@ impl Plan { if edged.len() < 2 { g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); } else { + let mut mask = mask; + let mut zero = zero; + if self.lazy.as_ref().is_some_and(|lazy| lazy.several) { + let evaluate = g.b.new_block(); + g.settle_then(evaluate); + g.b.switch_to_block(evaluate); + mask = g.load(slots.exit_arg, MAX_EVENTS); + zero = g.constant(0, MAX_EVENTS); + } for phase in [Phase::Evaluate, Phase::Apply] { for &index in &edged { let event = &self.events[index]; @@ -1150,7 +1329,12 @@ impl Plan { // combinational logic settles. g.b.switch_to_block(evaluated); g.publish(&staged); - g.call_comb(comb, 2); + match &self.lazy { + Some(_) => { + g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); + } + None => g.settle_then(slot_end), + } // At the end of the slot each clock whose edge applied waits for the // opposite level, half a period later, in event order (as @@ -1210,7 +1394,13 @@ impl Plan { g.b.switch_to_block(overflowed); let clock = g.constant(bit as u64, SCHEDULER_TIME_WIDTH); g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, clock); - g.b.seal_block(SIRTerminator::Jump(overflow_exit, Vec::new())); + // The slot is complete: the host reads its results settled. + match &self.lazy { + Some(_) => g.settle_then(overflow_exit), + None => { + g.b.seal_block(SIRTerminator::Jump(overflow_exit, Vec::new())); + } + } g.b.switch_to_block(in_range); g.store_at( slots.clock_next, @@ -1231,6 +1421,7 @@ impl Plan { g.b.switch_to_block(rearmed); } g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); + g.emit_settle(&program.sir.eval_comb, finish_exit, internal_exit); g.finish() } } @@ -1249,6 +1440,11 @@ struct Generator<'a> { /// See [`Plan::settle_reads`]. settle_reads: Option<&'a HashSet>, shared: HashMap, + /// The shared settle, emitted by [`Self::emit_settle`]. + comb: celox_sir::BlockId, + /// Where the shared settle continues, by case: case `i + 1` continues + /// at `continuations[i]`. + continuations: Vec, } impl Generator<'_> { @@ -1519,17 +1715,78 @@ impl Generator<'_> { } } - /// Run the shared settle, continuing at case `continuation` of its end. - fn call_comb(&mut self, comb: celox_sir::BlockId, continuation: u8) { - let value = self.constant(u64::from(continuation), SCHEDULER_FLAG_WIDTH); + /// Run the shared settle, then continue at `target`. The registers + /// `target` and its successors use must be defined in it or in the slot + /// loop's header, which alone dominates every entry of the settle. + fn settle_then(&mut self, target: celox_sir::BlockId) { + let case = match self.continuations.iter().position(|&block| block == target) { + Some(index) => index, + None => { + self.continuations.push(target); + self.continuations.len() - 1 + } + }; + let value = self.constant(case as u64 + 1, SCHEDULER_FLAG_WIDTH); self.store(self.slots.cont, SCHEDULER_FLAG_WIDTH, value); - self.b.seal_block(SIRTerminator::Jump(comb, Vec::new())); + self.b + .seal_block(SIRTerminator::Jump(self.comb, Vec::new())); + } + + /// Emit the shared settle: combinational logic, skipped when its inputs + /// did not change since the last one, as it would write what it already + /// holds; then the continuation of its caller. + fn emit_settle( + &mut self, + units: &[Unit], + finish_exit: celox_sir::BlockId, + internal_exit: celox_sir::BlockId, + ) { + self.b.switch_to_block(self.comb); + if self.settle_reads.is_some() { + let dirty = self.load(self.slots.dirty, SCHEDULER_FLAG_WIDTH); + let zero = self.constant(0, SCHEDULER_FLAG_WIDTH); + let changed = self.binary(1, dirty, BinaryOp::Ne, zero); + let settle = self.b.new_block(); + let settled = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: changed, + true_block: (settle, Vec::new()), + false_block: (settled, Vec::new()), + }); + self.b.switch_to_block(settle); + for unit in units { + self.inline(unit, finish_exit); + } + let clean = self.constant(0, SCHEDULER_FLAG_WIDTH); + self.store(self.slots.dirty, SCHEDULER_FLAG_WIDTH, clean); + self.b.seal_block(SIRTerminator::Jump(settled, Vec::new())); + self.b.switch_to_block(settled); + } else { + for unit in units { + self.inline(unit, finish_exit); + } + } + let continuation = self.load(self.slots.cont, SCHEDULER_FLAG_WIDTH); + let cases = self + .continuations + .iter() + .enumerate() + .map(|(index, &target)| SIRSwitchCase { + value: (index as u8 + 1).into(), + target, + }) + .collect(); + self.b.seal_block(SIRTerminator::Switch { + selector: continuation, + cases, + default: internal_exit, + }); } /// Inline `unit`. A `$finish` record it emits ends the run after it, as /// the reference loop ends the slot after the unit that emitted one. fn inline(&mut self, unit: &Unit, finish_exit: celox_sir::BlockId) { - if self.finish_sites.is_empty() || !self.emits_finish(unit) { + if self.finish_sites.is_empty() || !emits_finish(unit, self.finish_sites) { self.b.inline_execution_unit(unit); return; } @@ -1547,13 +1804,6 @@ impl Generator<'_> { self.b.switch_to_block(next); } - fn emits_finish(&self, unit: &Unit) -> bool { - instructions(unit).any(|inst| { - matches!(inst, SIRInstruction::RuntimeEvent { site_id, .. } - if self.finish_sites.contains(site_id)) - }) - } - /// A copy of `unit` that sets the finish slot after every `$finish` /// record. fn instrument(&self, unit: &Unit) -> Unit { @@ -1651,6 +1901,202 @@ fn homes_overlap_only_whole(layout: &crate::backend::MemoryLayout) -> bool { homes.windows(2).all(|pair| pair[0].1 <= pair[1].0) } +/// The storage `unit` reads. +fn loads(unit: &Unit) -> impl Iterator + '_ { + instructions(unit).filter_map(|inst| match inst { + SIRInstruction::Load(_, source, ..) | SIRInstruction::Commit(source, ..) => { + Some(source.absolute_addr()) + } + _ => None, + }) +} + +/// Whether a settle of `units` may read what an earlier settle left: a load +/// of storage they write (`stores`, by representative) that stores earlier +/// in the same settle do not cover on every path. +fn retains_state( + units: &[Unit], + storage: &impl Fn(AbsoluteAddr) -> AbsoluteAddr, + stores: &HashSet, +) -> bool { + /// The bits of each home a settle has stored so far, as sorted, + /// disjoint `[start, end)` ranges. + type Covered = HashMap<(u32, AbsoluteAddr), Vec<(usize, usize)>>; + fn add(covered: &mut Covered, key: (u32, AbsoluteAddr), start: usize, end: usize) { + let ranges = covered.entry(key).or_default(); + ranges.push((start, end)); + ranges.sort_unstable(); + let mut merged: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); + for &(start, end) in ranges.iter() { + match merged.last_mut() { + Some(last) if start <= last.1 => last.1 = last.1.max(end), + _ => merged.push((start, end)), + } + } + *ranges = merged; + } + fn meet(a: &Covered, b: &Covered) -> Covered { + let mut met = Covered::default(); + for (key, left) in a { + let Some(right) = b.get(key) else { continue }; + let both: Vec<(usize, usize)> = left + .iter() + .flat_map(|&(ls, le)| { + right.iter().filter_map(move |&(rs, re)| { + let (start, end) = (ls.max(rs), le.min(re)); + (start < end).then_some((start, end)) + }) + }) + .collect(); + if !both.is_empty() { + met.insert(*key, both); + } + } + met + } + // Runs `block` from `covered`; `false` when a load reads what it does + // not cover. + let step = |block: &celox_sir::BasicBlock, covered: &mut Covered| { + for inst in &block.instructions { + match inst { + SIRInstruction::Load(_, source, offset, width) + | SIRInstruction::Commit(source, _, offset, width, _) => { + let home = storage(source.absolute_addr()); + if stores.contains(&home) { + let read = match offset { + SIROffset::Static(start) => { + covered.get(&(source.region, home)).is_some_and(|ranges| { + ranges + .iter() + .any(|&(s, e)| s <= *start && start + width <= e) + }) + } + _ => false, + }; + if !read { + return false; + } + } + } + _ => {} + } + match inst { + SIRInstruction::Store(target, SIROffset::Static(start), width, ..) + | SIRInstruction::Commit(_, target, SIROffset::Static(start), width, _) => add( + covered, + (target.region, storage(target.absolute_addr())), + *start, + start + width, + ), + _ => {} + } + } + true + }; + let mut entry = Covered::default(); + for unit in units { + // What every path stores before each block, from the paths found + // so far: a fixed point from above, as loops only remove. + let mut before: HashMap = HashMap::default(); + before.insert(unit.entry_block_id, entry.clone()); + let mut after: HashMap = HashMap::default(); + let mut changed = true; + while changed { + changed = false; + let mut ids: Vec<_> = unit.blocks.keys().copied().collect(); + ids.sort_unstable(); + for id in ids { + let Some(start) = before.get(&id).cloned() else { + continue; + }; + let mut covered = start; + if !step(&unit.blocks[&id], &mut covered) { + return true; + } + if after.get(&id) == Some(&covered) { + continue; + } + let successors: Vec<_> = match &unit.blocks[&id].terminator { + SIRTerminator::Jump(target, _) => vec![*target], + SIRTerminator::Branch { + true_block, + false_block, + .. + } => vec![true_block.0, false_block.0], + SIRTerminator::Switch { cases, default, .. } => cases + .iter() + .map(|case| case.target) + .chain([*default]) + .collect(), + SIRTerminator::Return | SIRTerminator::Error(_) => Vec::new(), + }; + for successor in successors { + let next = match before.get(&successor) { + Some(known) => meet(known, &covered), + None => covered.clone(), + }; + before.insert(successor, next); + } + after.insert(id, covered); + changed = true; + } + } + // The next unit starts from what every return of this one stored. + let mut returns = unit + .blocks + .iter() + .filter(|(_, block)| matches!(block.terminator, SIRTerminator::Return)) + .filter_map(|(id, _)| after.get(id)); + entry = match returns.next() { + Some(first) => returns.fold(first.clone(), |met, next| meet(&met, next)), + None => Covered::default(), + }; + } + false +} + +/// Whether `unit` may end with an error. +fn fails(unit: &Unit) -> bool { + unit.blocks + .values() + .any(|block| matches!(block.terminator, SIRTerminator::Error(_))) +} + +/// Whether `unit` may record a `$finish`, one of `finish_sites`. +fn emits_finish(unit: &Unit, finish_sites: &HashSet) -> bool { + instructions(unit).any(|inst| { + matches!(inst, SIRInstruction::RuntimeEvent { site_id, .. } + if finish_sites.contains(site_id)) + }) +} + +/// The longest delay `unit` stores into `delay`: `u64::MAX` unless every +/// one is a constant. +fn delay_bound(unit: &Unit, delay: AbsoluteAddr) -> u64 { + let constants: HashMap = instructions(unit) + .filter_map(|inst| match inst { + SIRInstruction::Imm(register, value) => u64::try_from(&value.payload) + .ok() + .map(|value| (*register, value)), + _ => None, + }) + .collect(); + let delay = stable(delay); + instructions(unit) + .filter_map(|inst| match inst { + SIRInstruction::Store(target, offset, _, value, ..) if *target == delay => { + Some(match offset { + SIROffset::Static(0) => constants.get(value).copied().unwrap_or(u64::MAX), + _ => u64::MAX, + }) + } + SIRInstruction::Commit(_, target, ..) if *target == delay => Some(u64::MAX), + _ => None, + }) + .max() + .unwrap_or(0) +} + fn stable(address: AbsoluteAddr) -> RegionedAbsoluteAddr { RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address) } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index fa8d71e731d..e1f60ae082d 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -608,6 +608,28 @@ impl Simulation { Ok(()) } + /// Run every time slot before `time`, then move to `time` without + /// running its slot: the next [`Self::step`] or [`Self::run_until`] + /// runs it, together with the host writes made in between. A target not + /// after the current time changes nothing. Like [`Self::run_until`], it + /// returns early, before `time`, at a `$stop` or `$finish`. + pub fn advance_to(&mut self, time: u64) -> Result<(), RuntimeErrorCode> { + let Some(last) = time.checked_sub(1).filter(|&last| last >= self.time()) else { + return Ok(()); + }; + self.run_until(last)?; + if self.time() != last || self.is_finished() || self.is_stopped() { + return Ok(()); + } + self.state.advance_time(&mut self.simulator.backend, time); + if let Some(shadow) = &mut self.shadow { + shadow + .state + .advance_time(&mut shadow.simulator.backend, time); + } + Ok(()) + } + /// Like [`Self::run_until`], but takes at most `max_steps` steps. /// Returns `false`, with the simulation at the time of its last step, /// when another step would be needed to reach `end_time`, including when diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index ccde1df4cfd..8a8c3f1ff38 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -454,7 +454,8 @@ mod tests { /// A compiled kernel's `$finish` leaves the state the reference leaves: /// a kernel due in the same slot that did not run yet is still ready, - /// and a state file taken afterwards is the same. + /// combinational logic holds the last slot's settle, and a state file + /// taken afterwards is the same. #[test] fn compiled_slots_end_at_a_kernel_finish_as_the_reference_does() { let clock = "always #5 clk = ~clk;"; @@ -462,12 +463,13 @@ mod tests { for order in [[finish, clock], [clock, finish]] { let source = format!( "`timescale 1ns/1ns - module Top(output logic [7:0] count); + module Top(output logic [7:0] count, output logic [7:0] twice); logic clk = 1'b0; {} {} initial count = 8'd0; always_ff @(posedge clk) count <= count + 8'd1; + assign twice = count * 8'd2; endmodule", order[0], order[1] ); @@ -962,17 +964,18 @@ mod tests { /// The next edge of a host clock that overflows the simulation time /// fails the run as the reference's, after the clocks before it in the - /// slot re-armed. + /// slot re-armed and the slot settled. #[test] fn host_clock_overflow_fails_as_the_reference() { let source = r#" `timescale 1ns/1ns - module Top(input logic a, input logic b, output logic [7:0] n); + module Top(input logic a, input logic b, output logic [7:0] n, output logic [7:0] y); logic [7:0] ra = 8'd0; logic [7:0] rb = 8'd0; initial begin n = 8'd0; forever @(posedge b) n = n + 8'd1; end always_ff @(posedge a) ra <= ra + n; always_ff @(posedge b) rb <= rb + ra; + assign y = ra ^ rb; endmodule "#; let run = |mode: SchedulerMode| { @@ -1061,6 +1064,170 @@ mod tests { ); } + /// Settles wait for their readers, which see what they see in the + /// reference: a domain whose next state combinational logic computes, + /// a kernel that samples a combinational output after a delay, one that + /// samples it at an edge, in the pass after the clock's kernel changed + /// it, and the host between runs. + #[test] + fn deferred_settles_reach_their_readers() { + for reader in [ + "", + "always #3 seen = y;", + "initial forever @(negedge clk) seen = y + stim;", + ] { + let source = format!( + "`timescale 1ns/1ns + module Top(input logic [7:0] k, output logic [7:0] y); + logic clk = 1'b0; + logic [7:0] stim = 8'd0; + logic [7:0] r = 8'd0; + logic [7:0] q = 8'd0; + logic [7:0] seen = 8'd0; + logic [7:0] t = 8'd0; + logic [7:0] nxt; + always #5 begin t = t + 8'd1; clk = ~clk; end + always #7 stim = stim + 8'd1; + {reader} + always_comb nxt = r + stim + k; + always_ff @(posedge clk) r <= nxt; + always_ff @(posedge clk) q <= q + stim; + assign y = r ^ q ^ seen ^ t; + endmodule" + ); + host_driven_agrees( + &source, + &[ + (100, &[Host::Set("k", 1)]), + (200, &[Host::Set("k", 5)]), + (300, &[]), + ], + ); + } + } + + /// Combinational logic that keeps state between settles (a latch, the + /// snapshots an `always @*` waits on) settles where the reference + /// does: every activation in between counts, though no reader observes + /// it before the run ends. + #[test] + fn stateful_combinational_logic_settles_every_activation() { + let opened = r#" + `timescale 1ns/1ns + module Top(output logic [7:0] n); + logic [7:0] d = 8'd0; + logic en = 1'b0; + logic [7:0] q = 8'd0; + initial begin + #5 d = 8'd7; en = 1'b1; + #5 en = 1'b0; + #5 d = 8'd9; + end + always_latch if (en) q = d; + assign n = q; + endmodule + "#; + agrees_with_the_reference(opened, 30); + for process in [ + "always_latch if (g) l = d;", + "always @* if (g) l = d;", + "always @* l = d + 8'd1;", + ] { + let source = format!( + "`timescale 1ns/1ns + module Top(output logic [7:0] n); + logic clk = 1'b0; + logic [7:0] d = 8'd0; + logic g = 1'b1; + logic [7:0] l; + always #5 begin clk = ~clk; d = d + 8'd1; end + always_ff @(posedge clk) g <= ~g; + {process} + assign n = l; + endmodule" + ); + agrees_with_the_reference(&source, 30); + agrees_with_the_reference(&source, 300); + } + } + + /// A domain whose next state combinational logic computes runs its + /// fused units with a settle pending: they compute what it reads. + #[test] + fn fused_domains_compute_what_they_read() { + let source = r#" + module Top ( + clk: input clock, + k : input logic<8>, + y : output logic<8>, + ) { + var r : logic<8>; + var nxt: logic<8>; + always_comb { + nxt = r + k; + } + always_ff (clk) { + r = nxt; + } + assign y = r ^ k; + } + "#; + let run = |mode: SchedulerMode| { + let mut sim = Simulation::builder(source, "Top") + .scheduler_mode(mode) + .build() + .unwrap(); + sim.add_clock("clk", 10, 5); + let k = sim.signal("k"); + let mut states = Vec::new(); + for (end, value) in [(100, 1u8), (200, 5), (300, 9)] { + sim.modify(|io| io.set(k, value)).unwrap(); + sim.run_until(end).unwrap(); + states.push(sim.save_state().unwrap()); + } + (states, sim.scheduler_stats().compiled_slots) + }; + let (expected, _) = run(SchedulerMode::Reference); + for mode in MODES { + let (states, compiled) = run(mode); + assert_eq!(states, expected, "{mode:?}"); + assert!(compiled > 0, "{mode:?}"); + } + } + + /// A `$fatal` in a domain ends the run with combinational logic as the + /// slot's settle before the domain left it. + #[test] + fn compiled_slots_fail_in_a_domain_as_the_reference() { + let source = r#" + `timescale 1ns/1ns + module Top(output logic [7:0] y); + logic clk = 1'b0; + logic [7:0] r = 8'd0; + always #5 clk = ~clk; + always_ff @(posedge clk) begin + r <= r + 8'd1; + if (r == 8'd6) $fatal(1, "stop"); + end + assign y = r * 8'd3; + endmodule + "#; + let run = |mode: SchedulerMode| { + let mut sim = build_in(source, mode); + let result = sim.run_until(1000).map_err(|error| error.to_string()); + (result, sim.time(), sim.save_state().unwrap(), sim) + }; + let (result, time, state, _) = run(SchedulerMode::Reference); + assert!(result.is_err(), "{result:?}"); + for mode in MODES { + let (mode_result, mode_time, mode_state, sim) = run(mode); + assert_eq!(mode_result, result, "{mode:?}"); + assert_eq!(mode_time, time, "{mode:?}"); + assert_eq!(mode_state, state, "{mode:?}"); + assert!(sim.scheduler_stats().compiled_slots > 0, "{mode:?}"); + } + } + /// A design without process kernels runs its host clocks in compiled /// slots: one domain, which has no units for several domains, coinciding /// domains and a domain-less edge, with host writes between runs and a @@ -1158,16 +1325,18 @@ mod tests { /// A compiled run of several slots that fails in a later one: the /// shadow catches up to that slot and fails the same way, so every mode - /// reports the reference's error and leaves its state. + /// reports the reference's error and leaves its state, combinational + /// outputs as the last slot settled them. #[test] fn compiled_runs_that_fail_after_several_slots_agree() { let source = r#" `timescale 1fs/1fs - module Top(output logic [7:0] x); + module Top(output logic [7:0] x, output logic [7:0] y); logic clk = 1'b0; logic [7:0] r = 8'd0; always #5 clk = ~clk; always_ff @(posedge clk) r <= r + 8'd1; + assign y = r + x; initial begin x = 8'd0; #30 x = 8'd1; diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 7f8b600c462..bb675f04160 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1710,20 +1710,24 @@ mod host { /// /// Keeping compilation separate from initialization lets compiler-only /// clients stop after native code generation without applying initial - /// values or executing the first combinational settle. + /// values or executing the first combinational settle. `Target` is what + /// [`Self::initialize`] builds: a [`Simulator`], or a timed + /// [`crate::Simulation`] whose image carries the process kernels and the + /// compiled scheduler. #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", target_arch = "aarch64" ))] #[must_use] - pub struct NativeCompilation { + pub struct NativeCompilation { image: crate::backend::native::NativeProgramImage, program: LaidOutProgram, warnings: Vec, options: SimulatorOptions, vcd_path: Option, injected_components: crate::InjectedComponents, + _target: std::marker::PhantomData, } /// `Simulator` runs no process kernel, so a design with one would @@ -1741,6 +1745,37 @@ mod host { )) } + /// A native image records waveforms only if its arrays are packed, + /// which an image compiled with VCD enabled has: a VCD file of the host + /// (`vcd_path`) or of the design (`$dumpvars`) needs one. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + fn validate_native_vcd_layout( + layout: &crate::MemoryLayout, + program: &crate::ir::RuntimeProgram, + vcd_path: &Option, + ) -> Result<(), SimulatorError> { + let source_vcd = program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Vcd); + if (vcd_path.is_some() || source_vcd) + && layout.unpacked_arrays.values().any(|array| { + !array.element_width.is_multiple_of(8) + || array.element_stride != array.element_width / 8 + }) + { + return Err(SimulatorError::from(crate::CodegenError::message( + "VCD requires packed array storage; compile this native image with VCD enabled", + ))); + } + Ok(()) + } + #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -1759,22 +1794,8 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); - let source_vcd = sim - .program - .runtime_schema - .host_request_sites - .iter() - .any(|site| site.kind == celox_design::HostRequestKind::Vcd); - if vcd_path.is_some() || source_vcd { - if sim.layout().unpacked_arrays.values().any(|array| { - !array.element_width.is_multiple_of(8) - || array.element_stride != array.element_width / 8 - }) { - return Err(SimulatorError::from(crate::CodegenError::message( - "VCD requires packed array storage; compile this native image with VCD enabled", - )) - .with_warnings(std::mem::take(&mut sim.warnings))); - } + if let Err(error) = validate_native_vcd_layout(sim.layout(), &sim.program, &vcd_path) { + return Err(error.with_warnings(std::mem::take(&mut sim.warnings))); } if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); @@ -1851,7 +1872,7 @@ mod host { feature = "arm64-codegen", target_arch = "aarch64" ))] - impl NativeCompilation { + impl NativeCompilation { /// Warnings emitted while compiling this artifact. pub fn warnings(&self) -> &[CompilationWarning] { &self.warnings @@ -1885,7 +1906,14 @@ mod host { ) -> Result<(), crate::backend::native::NativeImageContainerError> { self.image.write_container(output_path) } + } + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + impl NativeCompilation { /// Load the image into executable memory and initialize runtime state. pub fn initialize( self, @@ -1897,6 +1925,7 @@ mod host { options, vcd_path, injected_components, + _target, } = self; initialize_native_image( image, @@ -1909,6 +1938,38 @@ mod host { } } + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + impl NativeCompilation { + /// Load the image into executable memory and start a timed + /// simulation of it. + pub fn initialize( + self, + ) -> Result, SimulatorError> + { + let Self { + image, + program, + warnings, + options, + vcd_path, + injected_components, + _target, + } = self; + SimulatorBuilder::::start_native_image( + image, + program.into_runtime(), + warnings, + options, + vcd_path, + injected_components, + ) + } + } + impl Default for SimulatorOptions { fn default() -> Self { let opt = crate::optimizer::OptimizeOptions::default(); @@ -3175,6 +3236,7 @@ mod host { options, vcd_path, injected_components, + _target: std::marker::PhantomData, }) } @@ -3230,6 +3292,7 @@ mod host { options, vcd_path, injected_components, + _target: std::marker::PhantomData, }, trace, )) @@ -3716,6 +3779,68 @@ mod host { ) } + /// Compiles a timed simulation into a native image without loading + /// it. The image carries the process kernels and the compiled + /// scheduler; [`NativeCompilation::initialize`] or + /// [`Self::build_native_from_image`] starts a simulation of it. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + pub fn compile_native( + mut self, + ) -> Result, SimulatorError> { + self.options.emit_triggers = true; + let (laid_out, mut warnings, options, vcd_path, injected_components) = self + .into_laid_out_program( + crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, + )?; + let image = crate::backend::native::NativeBackend::compile_image(&laid_out, &options) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; + Ok(NativeCompilation { + image, + program: laid_out, + warnings, + options, + vcd_path, + injected_components, + _target: std::marker::PhantomData, + }) + } + + /// Starts a timed simulation of a native image from + /// [`Self::compile_native`], without code generation. The design's + /// runtime metadata comes from `image`; the sources of this builder + /// are not used, its runtime options (scheduler, DPI symbols, + /// plusargs, VCD output) are. + /// + /// An image from [`Simulator::builder`] has no compiled scheduler, + /// so every time slot runs in the reference loop. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + pub fn build_native_from_image( + self, + image: crate::backend::native::NativeProgramImage, + ) -> Result, SimulatorError> + { + let mut options = self.options; + options.four_state = image.four_state(); + options.emit_triggers = true; + let program = image.runtime_program(); + Self::start_native_image( + image, + program, + Vec::new(), + options, + self.vcd_path, + self.injected_components, + ) + } + /// Compiles a timed simulation using the Wasmtime WASM backend. pub fn build_wasm( self, @@ -3758,36 +3883,118 @@ mod host { self.into_laid_out_program(layout_mode)?; let backend = compile(&laid_out, &options) .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; - let shadow = if !matches!( + let shadow = Self::start_shadow( + |shadow_options| compile(&laid_out, shadow_options), + &laid_out.runtime, + &options, + &injected_components, + )?; + let mut simulation = Self::start_simulation( + backend, + laid_out.into_runtime(), + warnings, + &options, + vcd_path, + injected_components, + )?; + if let Some(shadow) = shadow { + simulation.set_shadow(shadow); + } + Ok(simulation) + } + + /// The reference-loop shadow of a differential simulation of + /// `program`, with `backend` providing its own copy of the code, or + /// why it has none. Other scheduler modes have no shadow. + #[allow(clippy::type_complexity)] + fn start_shadow( + backend: impl FnOnce(&SimulatorOptions) -> Result, + program: &crate::ir::RuntimeProgram, + options: &SimulatorOptions, + injected_components: &crate::InjectedComponents, + ) -> Result>, &'static str>>, SimulatorError> + { + if !matches!( options.scheduler, crate::SchedulerMode::Differential | crate::SchedulerMode::DifferentialRuns ) { - None - } else if !injected_components.definitions.is_empty() { - Some(Err("the design has external components")) - } else { - let mut shadow_options = options.clone(); - shadow_options.trace = Default::default(); - shadow_options.scheduler = crate::SchedulerMode::Reference; - let backend = compile(&laid_out, &shadow_options)?; - let shadow = Self::start_simulation( - backend, - laid_out.runtime.clone(), - Vec::new(), - &shadow_options, - None, - Default::default(), - )?; - // Host state outside the memory image, such as open files, - // cannot be shared with a shadow. - Some(match shadow.simulator.check_host_checkpoint_support() { + return Ok(None); + } + if !injected_components.definitions.is_empty() { + return Ok(Some(Err("the design has external components"))); + } + let mut shadow_options = options.clone(); + shadow_options.trace = Default::default(); + shadow_options.scheduler = crate::SchedulerMode::Reference; + let backend = backend(&shadow_options)?; + let shadow = Self::start_simulation( + backend, + program.clone(), + Vec::new(), + &shadow_options, + None, + Default::default(), + )?; + // Host state outside the memory image, such as open files, + // cannot be shared with a shadow. + Ok(Some( + match shadow.simulator.check_host_checkpoint_support() { Ok(()) => Ok(Box::new(shadow)), Err(_) => Err("the design keeps host state outside its memory image"), - }) + }, + )) + } + + /// Load `image` into executable memory and start a timed simulation + /// of `program`, its runtime metadata. A differential simulation + /// loads a second copy of the image for its shadow. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + #[allow(unreachable_code)] + fn start_native_image( + image: crate::backend::native::NativeProgramImage, + program: crate::ir::RuntimeProgram, + mut warnings: Vec, + options: SimulatorOptions, + vcd_path: Option, + injected_components: crate::InjectedComponents, + ) -> Result, SimulatorError> + { + #[cfg(any( + all(feature = "arm64-codegen", not(target_arch = "aarch64")), + all(feature = "x86_64-codegen", not(target_arch = "x86_64")) + ))] + { + let _ = (image, program, options, vcd_path, injected_components); + return Err(SimulatorError::from(crate::RuntimeErrorCode::InternalError) + .with_warnings(warnings)); + } + + validate_native_vcd_layout(image.layout(), &program, &vcd_path) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; + let load = |image, options: &SimulatorOptions| { + // Safety: callers either produced the image in this process + // or loaded it from an explicitly trusted native-image + // artifact, and `from_image` validates its structure first. + unsafe { + crate::backend::native::NativeBackend::from_image_with_dpi(image, &options.dpi) + } }; + let shadow = Self::start_shadow( + |shadow_options| load(image.clone(), shadow_options), + &program, + &options, + &injected_components, + ) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; + let backend = load(image, &options) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; let mut simulation = Self::start_simulation( backend, - laid_out.into_runtime(), + program, warnings, &options, vcd_path, diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 2fc6b63fb8e..803b46afdaa 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -829,6 +829,7 @@ impl Simulator { inactive, nba_queue, domain_counters, + ..ProcessState::default() }, )) } diff --git a/crates/celox/tests/false_loop.rs b/crates/celox/tests/false_loop.rs index 4429fd66402..e073b3eac9e 100644 --- a/crates/celox/tests/false_loop.rs +++ b/crates/celox/tests/false_loop.rs @@ -400,9 +400,30 @@ module Top ( (vec![], vec!["v".to_owned()]), ) .build_with_trace(); + let mut sim = result.res.unwrap(); let trace = result.trace; let sir_output = trace.format_program().unwrap(); + // Check the fixed point for every input before reviewing the optimized IR. + let select = sim.signal("sel"); + let input = sim.signal("i"); + let output = sim.signal("o"); + for select_value in 0u8..2 { + for input_value in 0u8..4 { + sim.modify(|io| { + io.set(select, select_value); + io.set(input, input_value); + }) + .unwrap(); + let bit = if select_value == 1 { + input_value & 1 + } else { + input_value >> 1 + }; + assert_eq!(sim.get(output), (bit * 3).into()); + } + } + // Snapshot will catch: // 1. Redundant emits of the mux/selection logic. // 2. Incorrect Store Forwarding where the 'old' value of v[x] is lost. diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index dd47e78f796..a9b5632084c 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -1,6 +1,63 @@ use super::*; +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +#[test] +fn native_merged_optimization_preserves_large_and_wide_array_boundaries() { + for width in [58, 65, 129] { + let source = format!( + r#" + module Top(input logic [7:0] index, output logic [{top}:0] y); + function [{width}:0] identity(input logic [7:0] selected); + logic [{top}:0] words[{top}:0]; + for (integer i=0; i<{width}; i=i+1) begin + words[i]='0; + words[i][i]=1'b1; + end + identity[{top}:0]=words[selected]; + endfunction + assign y=identity(index); + endmodule + "#, + top = width - 1, + ); + for four_state in [false, true] { + for level in [ + celox::OptLevel::O0, + celox::OptLevel::O1, + celox::OptLevel::O2, + ] { + let mut sim = Simulator::from_sv_sources( + vec![(&source, Path::new("native_array_boundaries.sv"))], + "Top", + ) + .four_state(four_state) + .opt_level(level) + .build_native() + .unwrap(); + let index = sim.signal("index"); + let y = sim.signal("y"); + for bit in 0..width { + sim.modify(|io| io.set(index, bit as u32)).unwrap(); + assert_eq!( + sim.get(y), + BigUint::from(1u8) << bit, + "width={width}, four_state={four_state}, level={level:?}, bit={bit}", + ); + } + } + } + } +} + sv_backends! { + fn static_function_partial_writes_preserve_last_write(sim) { + @case "procedural::static_function_partial_writes_preserve_last_write"; + } + + fn static_function_unpacked_scratch_bits_at_element_boundaries(sim) { + @case "procedural::static_function_unpacked_scratch_bits_at_element_boundaries"; + } + fn constant_functions_inside_selected_parameter_initializers(sim) { @case "procedural::constant_functions_inside_selected_parameter_initializers"; } diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index f10ac99fc15..772ad6c685a 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -301,6 +301,18 @@ fn build(design: &Design, backend: &str) -> Result> { ); return Ok(match backend { "native" => Box::new(TimedBackend::new(builder.build_native()?)), + // The image goes through its container bytes, as an attached + // image does, and the simulation takes its metadata from it. + "native-image" => { + let image = builder.compile_native()?.into_program_image(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes()?)?; + Box::new(TimedBackend::new( + Simulation::from_sv_sources(Vec::new(), &design.top) + .scheduler_mode(scheduler_mode()) + .build_native_from_image(image)?, + )) + } "cranelift" => Box::new(TimedBackend::new(builder.build_cranelift()?)), "native-parallel" => Box::new(TimedBackend::new( builder diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 5c66fcb5cb0..705a5552867 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -2,7 +2,8 @@ //! processes, driven through the timed `Simulation`. //! //! Every exclusion names what Celox lacks for the case, so the change that -//! adds it removes the exclusion. Supported cases run on every backend. +//! adds it removes the exclusion. Supported cases run on every backend, +//! and natively also from a serialized native image. macro_rules! timed_cases { () => {}; @@ -25,6 +26,13 @@ macro_rules! timed_cases { crate::suite::run_case($case, "cranelift"); } + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + #[test] + $(#[$attr])* + fn native_image() { + crate::suite::run_case($case, "native-image"); + } + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] #[test] $(#[$attr])* diff --git a/crates/celox/tests/native_simulation_image.rs b/crates/celox/tests/native_simulation_image.rs new file mode 100644 index 00000000000..aab956b1f94 --- /dev/null +++ b/crates/celox/tests/native_simulation_image.rs @@ -0,0 +1,243 @@ +//! A timed `Simulation` built from a native image: the image carries the +//! process kernels and the compiled scheduler, so a serialized image runs as +//! the in-process build does (#1730). +#![cfg(all( + feature = "systemverilog", + any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ) +))] + +use std::path::Path; + +use celox::{ + NativeProgramImage, NativeProgramInstance, RuntimeEvent, SchedulerMode, Simulation, + SimulatorErrorKind, +}; + +const PROCESSES: &str = r#"`timescale 1ns/1ns +module Top(output logic [7:0] count, output logic [7:0] seen); + logic clk = 0; + always #5 clk = ~clk; + always_ff @(posedge clk) count <= count + 1; + initial begin + count = 0; + seen = 0; + #12 $display("at %0t count=%0d", $time, count); + @(posedge clk) seen = count; + #20 $display("at %0t seen=%0d count=%0d", $time, seen, count); + end +endmodule +"#; + +fn builder(source: &str) -> celox::SimulatorBuilder<'_, Simulation> { + Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") +} + +/// The image, through its container bytes. +fn reloaded(image: &NativeProgramImage) -> NativeProgramImage { + NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()).unwrap() +} + +/// What a simulation shows up to `end`: its events and outputs. +fn transcript( + sim: &mut Simulation, + end: u64, +) -> (Vec, u64, u64) { + sim.run_until(end).unwrap(); + let count = sim.get(sim.signal("count")).try_into().unwrap(); + let seen = sim.get(sim.signal("seen")).try_into().unwrap(); + (sim.drain_runtime_events(), count, seen) +} + +#[test] +fn a_serialized_native_image_runs_its_processes() { + let expected = transcript(&mut builder(PROCESSES).build_native().unwrap(), 60); + assert_eq!( + expected.0, + vec![ + RuntimeEvent::Display { + message: b"at 12 count=1".to_vec() + }, + RuntimeEvent::Display { + message: b"at 35 seen=1 count=3".to_vec() + }, + ] + ); + let image = reloaded( + &builder(PROCESSES) + .compile_native() + .unwrap() + .into_program_image(), + ); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + assert_eq!(transcript(&mut sim, 60), expected); + assert!(sim.scheduler_stats().compiled_slots > 0); + let mut sim = builder(PROCESSES) + .compile_native() + .unwrap() + .initialize() + .unwrap(); + assert_eq!(transcript(&mut sim, 60), expected); +} + +#[test] +fn a_differential_simulation_loads_its_shadow_from_the_image() { + let image = reloaded( + &builder(PROCESSES) + .compile_native() + .unwrap() + .into_program_image(), + ); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .scheduler_mode(SchedulerMode::Differential) + .build_native_from_image(image) + .unwrap(); + let (events, count, _) = transcript(&mut sim, 60); + assert_eq!(events.len(), 2); + assert_eq!(count, 6); + assert!(sim.scheduler_stats().checked_steps > 0); +} + +/// An image from `Simulator` has no compiled scheduler: every slot runs in +/// the reference loop, to the same state as a fresh `Simulation` build. +#[test] +fn an_untimed_image_runs_as_a_simulation_in_the_reference_loop() { + let source = "module Top(input logic clk, input logic [7:0] step, output logic [7:0] count, + output logic [7:0] sum); + always_ff @(posedge clk) count <= count + 1; + always_ff @(negedge clk) sum <= sum + count + step; + endmodule"; + let run = |sim: &mut Simulation| { + let step = sim.signal("step"); + sim.modify(|io| io.set(step, 3u8)).unwrap(); + sim.add_clock("clk", 10, 5); + sim.run_until(97).unwrap(); + sim.save_state().unwrap() + }; + let mut fresh = builder(source).build_native().unwrap(); + let expected = run(&mut fresh); + let image = celox::Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .compile_native() + .unwrap() + .into_program_image(); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(reloaded(&image)) + .unwrap(); + assert_eq!(run(&mut sim), expected); + assert_eq!(sim.get(sim.signal("count")), 10u8.into()); + assert_eq!(sim.scheduler_stats().compiled_slots, 0); +} + +#[test] +fn process_images_do_not_load_as_untimed_programs() { + let image = builder(PROCESSES) + .compile_native() + .unwrap() + .into_program_image(); + let Err(error) = + celox::Simulator::from_sv_sources(Vec::new(), "Top").build_native_from_image(image.clone()) + else { + panic!("a Simulator runs no process"); + }; + assert!(matches!( + error.kind(), + SimulatorErrorKind::ProcessRequiresSimulation(_) + )); + // SAFETY: the image was compiled from the trusted source above. + let Err(error) = (unsafe { NativeProgramInstance::from_image(image) }) else { + panic!("a native program instance runs no process"); + }; + assert!(error.to_string().contains("is a process"), "{error}"); +} + +#[test] +fn advance_to_stops_before_the_slot_and_its_host_writes_join_it() { + let source = r#"`timescale 1ns/1ns +module Top(input logic [7:0] value, output logic [7:0] seen); + initial begin + seen = 0; + #5 seen = value; + $display("at %0t value=%0d", $time, value); + end +endmodule +"#; + let image = reloaded( + &builder(source) + .compile_native() + .unwrap() + .into_program_image(), + ); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + sim.advance_to(5).unwrap(); + assert_eq!(sim.time(), 5); + assert_eq!(sim.get(sim.signal("seen")), 0u8.into()); + assert_eq!(sim.drain_runtime_events(), Vec::new()); + // The write is the host's at time 5, before the process resumes there. + let value = sim.signal("value"); + sim.modify(|io| io.set(value, 7u8)).unwrap(); + sim.advance_to(5).unwrap(); + assert_eq!(sim.get(sim.signal("seen")), 0u8.into()); + sim.run_until(5).unwrap(); + assert_eq!(sim.get(sim.signal("seen")), 7u8.into()); + assert_eq!( + sim.drain_runtime_events(), + vec![RuntimeEvent::Display { + message: b"at 5 value=7".to_vec() + }] + ); + sim.advance_to(3).unwrap(); + assert_eq!(sim.time(), 5); +} + +/// Element-strided unpacked arrays cannot be dumped: an image compiled +/// without VCD is rejected for a VCD run, as `Simulator` rejects it, and one +/// compiled with VCD records the elements. +#[test] +fn a_vcd_run_needs_an_image_compiled_with_vcd() { + let source = r#"`timescale 1ns/1ns +module Top; + logic [2:0] values [4]; + initial begin + values[2] = 3'd0; + #1 values[2] = 3'd5; + end +endmodule +"#; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("top.vcd"); + let strided = builder(source) + .compile_native() + .unwrap() + .into_program_image(); + let Err(error) = Simulation::from_sv_sources(Vec::new(), "Top") + .vcd(&path) + .build_native_from_image(reloaded(&strided)) + else { + panic!("a strided image cannot record VCD"); + }; + assert!( + error + .to_string() + .contains("compile this native image with VCD enabled"), + "{error}" + ); + let packed = builder(source) + .vcd(&path) + .compile_native() + .unwrap() + .into_program_image(); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .vcd(&path) + .build_native_from_image(reloaded(&packed)) + .unwrap(); + sim.run_until(2).unwrap(); + drop(sim); + let vcd = std::fs::read_to_string(&path).unwrap(); + assert!(vcd.contains("b101"), "{vcd}"); +} diff --git a/crates/celox/tests/snapshots/false_loop__scc_bit_cross_dependency.snap b/crates/celox/tests/snapshots/false_loop__scc_bit_cross_dependency.snap index 429607a870b..bf976556a16 100644 --- a/crates/celox/tests/snapshots/false_loop__scc_bit_cross_dependency.snap +++ b/crates/celox/tests/snapshots/false_loop__scc_bit_cross_dependency.snap @@ -25,6 +25,7 @@ Execution Unit 0: r13: logic<64> r14: logic<64> r17: logic<2> + r18: bit<2> b0: r0 = Load(addr=sel (region=0), offset=0, bits=1) r1 = Load(addr=v (region=0), offset=0, bits=1) @@ -33,10 +34,10 @@ Execution Unit 0: r14 = r12 Shr r13 r2 = r14 And r13 r3 = Mux(cond=r0, then=r1, else=r2) - Store(addr=v (region=0), offset=1, bits=1, src_reg = 3) r4 = r12 And r13 r6 = Mux(cond=r0, then=r4, else=r3) - Store(addr=v (region=0), offset=0, bits=1, src_reg = 6) + r18 = Concat(r3, r6) + Store(addr=v (region=0), offset=0, bits=2, src_reg = 18) r8 = Mux(cond=r0, then=r6, else=r2) r10 = Mux(cond=r0, then=r4, else=r8) r17 = Concat(r8, r10) diff --git a/docs/internals/optimizations.md b/docs/internals/optimizations.md index 7ecea17951a..a10c48ca3b5 100644 --- a/docs/internals/optimizations.md +++ b/docs/internals/optimizations.md @@ -101,6 +101,15 @@ unnecessary: compile the clock's domain once more; the `derived_edge_units` selector (`-sir:derived_edge_units`, `SirPass::DerivedEdgeUnits`) turns them off to trade tick speed for build time. +- in the time slots a compiled scheduler runs, a combinational settle waits + until its results are read: it runs, where the reference loop last + settled, before a process kernel or domain that reads combinational outputs + or may end the run mid-slot (`$finish`, an error), and before the run + returns, so every reader sees the reference's values. A domain that only + reads combinational outputs runs its fused evaluate-and-commit units instead + where the frontend provides them (Veryl). Combinational logic that keeps state + between settles (latches, guarded processes such as `always @*`, feedback) + settles where the reference loop does. These choices preserve the ordering model defined in [Runtime Semantics](./cascade-limitations.md). They do not change signal values or diff --git a/lefthook.yml b/lefthook.yml index 74fa538bb1c..7f7af4133f7 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -18,4 +18,4 @@ pre-push: # builds, and documentation builds remain required in GitHub Actions. cargo-check: priority: 3 - run: cargo check --workspace --locked + run: cargo check --workspace --exclude lydite-celox --locked diff --git a/lydite/conformance/veryl/run_ci.sh b/lydite/conformance/veryl/run_ci.sh index 4847d8816f4..ba832516268 100755 --- a/lydite/conformance/veryl/run_ci.sh +++ b/lydite/conformance/veryl/run_ci.sh @@ -60,7 +60,7 @@ PY cd "$HERE" python3 generate.py # --locked forbids resolving newer dependencies. These are independent workspaces. -cargo build --release --locked --manifest-path "$REPO/../Cargo.toml" -p lydite-ir -p lydite -p lydite-celox -p lydite-solver -p lydite-syntax -p lydite-verify +cargo build --release --locked --manifest-path "$REPO/../Cargo.toml" -p lydite-ir -p lydite -p lydite-solver -p lydite-syntax -p lydite-verify cargo build --locked --manifest-path analyzer-probe/Cargo.toml --target-dir "$HERE/analyzer-probe/target" cargo build --locked --manifest-path Cargo.toml --target-dir "$HERE/target" -p extract-suite export LYDITE_BIN="$REPO/../target/release/lydite" diff --git a/scripts/benchmark-workflows.test.mjs b/scripts/benchmark-workflows.test.mjs index 5f58b398e90..5237aaedbb1 100644 --- a/scripts/benchmark-workflows.test.mjs +++ b/scripts/benchmark-workflows.test.mjs @@ -50,7 +50,7 @@ test("CodSpeed reports the current upload even after failure or cancellation", ( const benchmark = job(codspeed, "codspeed"); const report = job(codspeed, "report"); assert.match(benchmark, /run-id: \$\{\{ steps\.benchmarks\.outputs\.run-id \}\}/); - assert.match(benchmark, /id: benchmarks\n\s+uses: CodSpeedHQ\/action@v5/); + assert.match(benchmark, /id: benchmarks\n\s+timeout-minutes: 15\n\s+uses: CodSpeedHQ\/action@v5/); assert.match(report, /needs: codspeed/); assert.match(report, /checks: read/); assert.match(report, /issues: write/); @@ -59,9 +59,9 @@ test("CodSpeed reports the current upload even after failure or cancellation", ( assert.match(report, /run: node scripts\/report-codspeed\.mjs/); assert.doesNotMatch(codspeed, /continue-on-error:/); assert.match(codspeed, /cancel-in-progress: false/); - const condition = new Function("github", "always", `return (${expression(report, "if")});`); + const condition = new Function("github", "always", "inputs", `return (${expression(report, "if")});`); for (const branch of ["master", "develop", "feature"]) { - assert.equal(condition({ ref_name: branch }, () => true), branch !== "feature"); + assert.equal(condition({ ref_name: branch }, () => true, { runner_probe: false }), branch !== "feature"); } }); @@ -165,3 +165,34 @@ test("profiling reuse rejects pre-CLI artifacts before capture", () => { assert.match(check, /predates the celox run CLI/); assert.match(check, /exit 1/); }); + + +test("compilation scaling uses walltime consistently and has a bounded execution", () => { + const benchmark = job(codspeed, "codspeed"); + assert.match(benchmark, /runs-on: codspeed-macro-arm64-graviton-ubuntu-22-04/); + assert.match(benchmark, /timeout-minutes: 60/); + assert.match(benchmark, /cargo codspeed build --locked --measurement-mode walltime -p celox --bench compilation/); + assert.match(benchmark, /id: benchmarks\n timeout-minutes: 15\n uses: CodSpeedHQ\/action@v5/); + assert.match(benchmark, /mode: walltime/); + assert.match(benchmark, /run: cargo codspeed run --measurement-mode walltime -p celox --bench compilation/); + assert.doesNotMatch(benchmark, /simulation|continue-on-error/); +}); + + +test("runner probe cannot build or benchmark and does not report a skipped benchmark as failure", () => { + const probe = job(codspeed, "runner-probe"); + const runner = block => block.match(/runs-on: (\S+)/)[1]; + assert.equal(runner(probe), runner(job(codspeed, "codspeed"))); + assert.doesNotMatch(probe, /checkout|cargo|CodSpeedHQ\/action/); + assert.match(probe, /timeout-minutes: 2/); + const probeCondition = new Function("github", "inputs", `return (${expression(probe, "if")});`); + const benchCondition = new Function("inputs", `return (${expression(job(codspeed, "codspeed"), "if")});`); + const reportCondition = new Function("github", "inputs", "always", `return (${expression(job(codspeed, "report"), "if")});`); + for (const runner_probe of [true, false]) { + const inputs = { runner_probe }; + assert.equal(Boolean(probeCondition({ event_name: "workflow_dispatch" }, inputs)), runner_probe); + assert.equal(benchCondition(inputs), !runner_probe); + assert.equal(reportCondition({ ref_name: "master" }, inputs, () => true), !runner_probe); + } + assert.equal(benchCondition({}), true); +}); diff --git a/scripts/ci-changes.mjs b/scripts/ci-changes.mjs index 3defbd38d10..a97b9d17302 100644 --- a/scripts/ci-changes.mjs +++ b/scripts/ci-changes.mjs @@ -305,7 +305,7 @@ if ( }); } -// Lydite tests are selected independently by lydite-checks.yml, including its bridge. +// Lydite core tests run independently; bridge CI is disabled. export function celoxRustTestScope(files, packages) { return rustTestScope( files.filter((path) => !/^(?:\.\/)?(?:lydite\/|crates\/lydite(?:-|\/))/.test(path)), @@ -324,7 +324,10 @@ export function rustScopeOutputs(files) { const packages = readWorkspace(root); scope = celoxRustTestScope(files, packages); // Lydite owns its tests, but lint and API documentation still live here. - checks = rustTestScope(files, packages); + checks = rustTestScope( + files.filter((path) => !/^(?:\.\/)?crates\/lydite-celox\//.test(path)), + packages.filter((pkg) => pkg.name !== "lydite-celox"), + ); } catch (error) { console.warn(`Unable to scope the Rust tests: ${error.message}`); } diff --git a/scripts/ci-changes.test.mjs b/scripts/ci-changes.test.mjs index d00b604c03a..7d2b80e76b2 100644 --- a/scripts/ci-changes.test.mjs +++ b/scripts/ci-changes.test.mjs @@ -597,3 +597,13 @@ test("VPI test-only edits do not select the unrelated ignored cocotb end-to-end assert.equal(rustScopeOutputs([path]).rust_vpi_e2e, true); assert.equal(rustScopeOutputs(null).rust_vpi_e2e, true); }); + + +test("disabled bridge is absent from every scoped test, lint and documentation plan", () => { + for (const path of ["crates/lydite-celox/src/lib.rs", "crates/celox/src/lib.rs", "crates/lydite-ir/src/lib.rs"]) { + const scope = rustScopeOutputs([path]); + assert.equal(scope.rust_full, false, path); + for (const key of ["rust_packages", "rust_libraries", "rust_lint_packages", "rust_doc_libraries", "rust_builds", "rust_lint_builds"]) + assert.ok(!scope[key].includes("lydite-celox"), `${path}: ${key}`); + } +}); diff --git a/scripts/ci-lydite-changes.mjs b/scripts/ci-lydite-changes.mjs index 8dec327c801..bc870e24ac2 100644 --- a/scripts/ci-lydite-changes.mjs +++ b/scripts/ci-lydite-changes.mjs @@ -6,7 +6,7 @@ import { changedFilesBetween, readWorkspace } from "./ci-rust-scope.mjs"; export const isLydite = (name) => name === "lydite" || name.startsWith("lydite-"); -const all = () => ({ core: true, bridge: true }); +const all = () => ({ core: true }); // Cargo.lock's `[[package]]` entries, keyed by "name version", with the names // each one depends on. @@ -40,7 +40,7 @@ export function lockChanges(baseText, headText) { // Follow actual Cargo edges, including optional, build and dev dependencies. // Celox consumes none of the proof engine; only lydite-celox consumes Celox. -// `lock` is lockChanges() of the diff; without it a Cargo.lock edit runs both. +// `lock` is lockChanges() of the diff; without it a Cargo.lock edit runs core checks. export function lyditeScope(files, packages, lock = null) { if (files === null) return all(); const byName = new Map(packages.map((pkg) => [pkg.name, pkg])); @@ -61,8 +61,7 @@ export function lyditeScope(files, packages, lock = null) { .filter((p) => isLydite(p.name) && p.name !== "lydite-celox") .map((p) => p.name); const core = closure(coreRoots); - const bridge = closure(["lydite-celox"]); - const result = { core: false, bridge: false }; + const result = { core: false }; const owners = [...packages].sort((a, b) => b.dir.length - a.dir.length); for (const raw of files) { const path = raw.replace(/^\.\//, ""); @@ -75,7 +74,6 @@ export function lyditeScope(files, packages, lock = null) { return [...lock.changed].some((name) => seen.has(name)); }; result.core ||= reaches(coreRoots); - result.bridge ||= reaches(["lydite-celox"]); continue; } if ( @@ -111,7 +109,6 @@ export function lyditeScope(files, packages, lock = null) { ) continue; result.core ||= core.has(owner.name); - result.bridge ||= bridge.has(owner.name); } else if ( ["crates/", "vendor/", "testdata/", "conformance/"].some((prefix) => path.startsWith(prefix), @@ -125,21 +122,9 @@ export function lyditeScope(files, packages, lock = null) { return result; } -// Celox dependency changes reach the bridge, but its replay and proof corpus -// are too heavy for every Celox PR. PRs run the bridge only for Lydite-owned -// sources; daily runs cover Celox and CI changes and report failures. -const ownsBridge = (path) => - ["lydite/", "crates/lydite"].some((prefix) => - path.replace(/^\.\//, "").startsWith(prefix), - ); - export function pullRequestScope(files, packages, lock = null) { - // Release PRs and their queue drafts only bump versions. - if (files !== null && isVersionOnlyRelease(files)) - return { core: false, bridge: false }; - const scope = lyditeScope(files, packages, lock); - if (files === null) return scope; - return { ...scope, bridge: scope.bridge && files.some(ownsBridge) }; + if (files !== null && isVersionOnlyRelease(files)) return { core: false }; + return lyditeScope(files, packages, lock); } // The lockfile at the merge base and at head, as changedFilesBetween compares. diff --git a/scripts/ci-lydite-changes.test.mjs b/scripts/ci-lydite-changes.test.mjs index b745af57b4a..fac8fdc01e6 100644 --- a/scripts/ci-lydite-changes.test.mjs +++ b/scripts/ci-lydite-changes.test.mjs @@ -14,10 +14,10 @@ import { readWorkspace } from "./ci-rust-scope.mjs"; const root = fileURLToPath(new URL("../", import.meta.url)); const packages = readWorkspace(root); const scope = (...files) => lyditeScope(files, packages); -const both = { core: true, bridge: true }; -const neither = { core: false, bridge: false }; +const coreOnly = { core: true }; +const neither = { core: false }; -test("Lydite core changes and shared configuration run both lanes", () => { +test("Lydite core changes and shared configuration run core checks", () => { for (const path of [ "crates/lydite/src/main.rs", "crates/lydite-ir/src/lib.rs", @@ -31,11 +31,11 @@ test("Lydite core changes and shared configuration run both lanes", () => { "crates/new/src/lib.rs", "conformance/new/case.sv", ]) - assert.deepEqual(scope(path), both, path); - assert.deepEqual(lyditeScope(null, packages), both); + assert.deepEqual(scope(path), coreOnly, path); + assert.deepEqual(lyditeScope(null, packages), coreOnly); }); -test("Celox dependencies select the bridge, without rerunning the editor/core", () => { +test("Celox and bridge changes do not select core checks", () => { for (const name of [ "celox", "celox-design", @@ -47,7 +47,7 @@ test("Celox dependencies select the bridge, without rerunning the editor/core", ]) assert.deepEqual( scope(`crates/${name}/src/lib.rs`), - { core: false, bridge: true }, + { core: false }, name, ); }); @@ -69,31 +69,14 @@ test("unrelated consumers and upstream private tests do not select Lydite", () = assert.deepEqual(scope(), neither); assert.deepEqual( scope("packages/celox/src/index.ts", "crates/lydite/src/main.rs"), - both, + coreOnly, ); }); -test("PRs run the bridge only for Lydite-owned changes", () => { - const pr = (...files) => pullRequestScope(files, packages); - for (const path of [ - "crates/celox/src/lib.rs", - "crates/celox-test-suite/src/veryl/cases/flip_flop.vtest", - ]) - assert.deepEqual(pr(path), neither, path); - for (const path of [ - "Cargo.lock", - "rust-toolchain.toml", - ".github/workflows/lydite-checks.yml", - "scripts/ci-lydite-changes.mjs", - ]) - assert.deepEqual(pr(path), { core: true, bridge: false }, path); - for (const path of [ - "crates/lydite-celox/src/lib.rs", - "crates/lydite/src/main.rs", - "lydite/conformance/veryl-proof/case-exceptions.json", - ]) - assert.equal(pr(path).bridge, true, path); - assert.deepEqual(pullRequestScope(null, packages), both); +test("bridge-only PRs do not select core gates", () => { + assert.deepEqual(pullRequestScope(["crates/lydite-celox/src/lib.rs"], packages), neither); + assert.deepEqual(pullRequestScope(["crates/lydite/src/main.rs"], packages), coreOnly); + assert.deepEqual(pullRequestScope(null, packages), coreOnly); }); test("Celox sv-tests changes skip Lydite without masking other changes", () => { @@ -116,12 +99,12 @@ test("Celox sv-tests changes skip Lydite without masking other changes", () => { "crates/lydite/src/main.rs", "lydite/conformance/veryl/run_ci.sh", ]) { - assert.deepEqual(pullRequestScope([...files, path], packages), both, path); - assert.deepEqual(pullRequestScope([path, ...files], packages), both, path); + assert.deepEqual(pullRequestScope([...files, path], packages), coreOnly, path); + assert.deepEqual(pullRequestScope([path, ...files], packages), coreOnly, path); } assert.deepEqual( pullRequestScope([...files, "conformance/unknown/case.sv"], packages), - { core: true, bridge: false }, + { core: true }, ); }); @@ -146,14 +129,13 @@ test("Cargo.lock edits select only the lanes that reach the changed entries", () ); assert.deepEqual(pr(edit("serde_json", "dependencies = [", "dependencies = [\n \"new\",")), { core: true, - bridge: false, }); assert.deepEqual( lyditeScope(["Cargo.lock"], packages, edit("celox", "dependencies = [", "dependencies = [\n \"new\",")), - { core: false, bridge: true }, + { core: false }, ); assert.deepEqual(pr(lockChanges(lockfile, lockfile)), neither); - assert.deepEqual(pr(null), { core: true, bridge: false }); + assert.deepEqual(pr(null), { core: true }); }); test("version-only release PRs skip Lydite", () => { @@ -171,10 +153,9 @@ test("version-only release PRs skip Lydite", () => { // Without the release manifest, Cargo changes are ordinary dependency edits. assert.deepEqual(pullRequestScope(release.slice(1), packages), { core: true, - bridge: false, }); assert.equal( - pullRequestScope([...release, "crates/lydite/src/main.rs"], packages).bridge, + pullRequestScope([...release, "crates/lydite/src/main.rs"], packages).core, true, ); }); @@ -196,10 +177,9 @@ test("dependency selection follows new transitive edges automatically", () => { ]; assert.deepEqual(lyditeScope(["crates/new-runtime/src/lib.rs"], graph), { core: false, - bridge: true, }); graph[0].dependencies.push("new-runtime"); - assert.deepEqual(lyditeScope(["crates/new-runtime/src/lib.rs"], graph), both); + assert.deepEqual(lyditeScope(["crates/new-runtime/src/lib.rs"], graph), coreOnly); }); test("Celox packages do not consume the excluded Lydite packages", () => { @@ -211,7 +191,7 @@ test("Celox packages do not consume the excluded Lydite packages", () => { } }); -test("daily, manual and unknown-diff invocations run every lane", () => { +test("daily, manual and unknown-diff invocations run only core gates", () => { for (const event of ["schedule", "workflow_dispatch", "merge_group"]) { const output = execFileSync( process.execPath, @@ -222,7 +202,7 @@ test("daily, manual and unknown-diff invocations run every lane", () => { encoding: "utf8", }, ); - assert.match(output, /core=true\nbridge=true/); + assert.match(output, /^core=true\n$/); } }); @@ -245,7 +225,6 @@ test("workflows transfer Rust tests and gate each Lydite lane", () => { ["documentation", "core"], ["editor", "core"], ["veryl-fv", "core"], - ["bridge", "bridge"], ]) { assert.ok( workflow.includes( @@ -254,7 +233,8 @@ test("workflows transfer Rust tests and gate each Lydite lane", () => { job, ); } - assert.match(workflow, /cargo test --locked "\$\{args\[@\]\}"/); + assert.match(workflow, /cargo test --locked -p lydite -p lydite-ir -p lydite-solver -p lydite-syntax -p lydite-verify/); + assert.doesNotMatch(workflow, / bridge:|outputs\.bridge|-p lydite-celox|conformance\/(axi4lite|veryl-proof|veryl-symbolic)/); assert.match( workflow, / report:\n name: Report Lydite validation\n[\s\S]*REPORT_NAME: Lydite validation\n run: node scripts\/report-full-ci\.mjs/, @@ -265,19 +245,18 @@ test("workflows transfer Rust tests and gate each Lydite lane", () => { .split(" PYCODE")[0] .replace(/^ /gm, ""); for (const core of [false, true]) - for (const bridge of [false, true]) { + { const needs = { changes: { result: "success", - outputs: { core: String(core), bridge: String(bridge) }, + outputs: { core: String(core) }, }, }; for (const [job, selected] of [ - ["rust", core || bridge], + ["rust", core], ["documentation", core], ["editor", core], ["veryl-fv", core], - ["bridge", bridge], ]) needs[job] = { result: selected ? "success" : "skipped" }; const run = () => @@ -315,3 +294,16 @@ test("scoped Celox PR tests also exclude the bridge and Lydite fixtures", () => assert.deepEqual(result.packages, []); } }); + + +test("normal CI and standalone core conformance never build the bridge", () => { + for (const pkg of packages.filter(p => p.name !== "lydite-celox")) + assert.ok(!pkg.dependencies.includes("lydite-celox"), pkg.name); + for (const path of [".github/workflows/ci.yml", ".github/workflows/publish-crates.yml"]) + assert.match(readFileSync(`${root}${path}`, "utf8"), /cargo doc --locked --workspace --exclude lydite-celox --no-deps/); + assert.match(readFileSync(`${root}.github/workflows/rust-cache.yml`, "utf8"), /cargo nextest list --locked --workspace --exclude 'lydite\*'/); + assert.match(readFileSync(`${root}lefthook.yml`, "utf8"), /cargo check --workspace --exclude lydite-celox --locked/); + const coreGate = readFileSync(`${root}lydite/conformance/veryl/run_ci.sh`, "utf8"); + assert.doesNotMatch(coreGate, /lydite-celox/); + assert.match(coreGate, /-p lydite-ir -p lydite -p lydite-solver -p lydite-syntax -p lydite-verify/); +}); diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index f9122c8d15c..c42e6506de0 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -549,8 +549,8 @@ test("CI retains the normal test profile and warms each platform's cache", () => assert.match(warm, /rust-default-tests:[\s\S]*cargo test --locked -p celox --lib --no-run/); }); -test("full Clippy validation covers every workspace crate", () => { - assert.match(job("lint"), /run: cargo clippy --locked --workspace --all-targets --features/); +test("full Clippy validation excludes the disabled bridge", () => { + assert.match(job("lint"), /run: cargo clippy --locked --workspace --exclude lydite-celox --all-targets --features/); }); test("upstream SV TB runs on full CI and feeds failure reporting", () => {