Phase 5: atomics through every layer (RFC 0015)
AIR: linear atomic<T> (AtomicScalar), atomic.new/take/load/store/RMW/ cmpxchg (two results)/fence with explicit orderings; feature atomics published. Verifier: ordering tables (E4201), ordinary access (E4202), effects [atomic] / [atomic, atomic.weak], linearity, take while lent (E4101, also for mutex.take). Interpreter: timestamped message machine (src/interp/weak.zig); views travel through spawn/join, channels, mutexes, close and cancel; seq_cst reads the latest message and programs without weak reads make no extra draw (existing records unchanged). aji explore: exhaustive exploration that branches only before visible operations. Litmus: 20/20 tests give exactly the oracle's sets; differential test (1500 random programs) found no unsound outcome. .aji layer 10, Quick Reference atomics, source coverage 67/67, audit report atomic_operations. AIR bundle +5.9 %, QUICK.md +0.5k.
This commit is contained in:
1 parent
ce9ef03bc0
commit
4242132b2a
70 files changed
+2622
-72
No files matched your search
@@ -26,6 +26,8 @@ jobs:
|
||||
run: python3 tools/source_coverage.py
|
||||
- name: Memory-model oracle self-tests and litmus corpus (spec 04 §20.5)
|
||||
run: python3 -m unittest tools/litmus/test_enumerate.py && python3 tools/litmus/check.py
|
||||
- name: Interpreter litmus conformance (observed_exhaustive == allowed) and differential soundness
|
||||
run: python3 tools/litmus/run_interp.py && python3 tools/litmus/differential.py --count 150
|
||||
- name: Evaluation harness self-tests
|
||||
run: cd tools/eval && python3 -m unittest discover tests
|
||||
- name: Agent Reference Bundle tokens (non-blocking)
|
||||
|
||||
@@ -144,7 +144,7 @@ zig fmt --check build.zig build.zig.zon src tools tests/extended
|
||||
|
||||
Toolchain: Zig 0.17.0. Workflow, layout and definition of done: `CONTRIBUTING.md`. Implementation plan and current phase: `docs/plan/README.md`. Documentation layout and where new documents go: `docs/README.md`. Unresolved spec gaps: `docs/design/open-questions.md` — log new ones there instead of guessing.
|
||||
|
||||
`aji` CLI output contract: diagnostics are JSON Lines on stdout, human notes on stderr; exit codes 0 accepted/returned, 1 rejected, 2 usage/I/O error, 3 not yet implemented, 4 trapped, 5 execution limit exceeded, 6 not instantiated, 7 blocked. `aji run [--fuel N] [--grant P=KIND[:SCOPE]]… [--stdin T] [--vfs PATH=T]… [--seed N]` runs in the deterministic profile and prints one JSON run record (with captured stdout/stderr and written files); capabilities reach a program only as named `@main` parameters. `--profile hosted` runs against the real OS; its run record goes only to `--result-file PATH` (the program owns stdout/stderr). Hosted smoke tests: `python3 tests/hosted/smoke.py`. Scheduler flags: `--quantum N`, `--task-limit N`, `--schedule-seed N` (independent of `--seed`); conformance tests use `schedules: N` to run N schedule seeds. `aji run --manifest aji.toml` runs a package with the grants its manifest requests (`--grant` replaces one per parameter; spec 12 §1). `aji report FILE` prints the audit report (spec 10 §6.1: effect graph with used/unused effects, entry capabilities, runtime and proven checks, unsafe sites); `aji check --report unsafe` lists trusted boundaries and unsafe operations; unsafe code lives only in functions declaring `effects [unsafe]` or behind a `trusted "<obligation>"` boundary. `aji features` reports the supported AIR format, language version and features; query it before generating AIR. Never use wall-clock timeouts to end runs or tests; use fuel (spec 11 §7).
|
||||
`aji` CLI output contract: diagnostics are JSON Lines on stdout, human notes on stderr; exit codes 0 accepted/returned, 1 rejected, 2 usage/I/O error, 3 not yet implemented, 4 trapped, 5 execution limit exceeded, 6 not instantiated, 7 blocked. `aji run [--fuel N] [--grant P=KIND[:SCOPE]]… [--stdin T] [--vfs PATH=T]… [--seed N]` runs in the deterministic profile and prints one JSON run record (with captured stdout/stderr and written files); capabilities reach a program only as named `@main` parameters. `--profile hosted` runs against the real OS; its run record goes only to `--result-file PATH` (the program owns stdout/stderr). Hosted smoke tests: `python3 tests/hosted/smoke.py`. Scheduler flags: `--quantum N`, `--task-limit N`, `--schedule-seed N` (independent of `--seed`); conformance tests use `schedules: N` to run N schedule seeds. `aji run --manifest aji.toml` runs a package with the grants its manifest requests (`--grant` replaces one per parameter; spec 12 §1). `aji report FILE` prints the audit report (spec 10 §6.1: effect graph with used/unused effects, entry capabilities, runtime and proven checks, unsafe sites); `aji check --report unsafe` lists trusted boundaries and unsafe operations; unsafe code lives only in functions declaring `effects [unsafe]` or behind a `trusted "<obligation>"` boundary. `aji features` reports the supported AIR format, language version and features; query it before generating AIR. `aji explore [--max-runs N] FILE` runs `@main` under every schedule and weak-memory choice and prints the distinct outcomes (spec 04 §20.5); the litmus corpus runs through it (`python3 tools/litmus/run_interp.py`). Never use wall-clock timeouts to end runs or tests; use fuel (spec 11 §7).
|
||||
|
||||
## Testing policy
|
||||
|
||||
|
||||
@@ -50,6 +50,7 @@ Growth never blocks a merge automatically; a complex feature can be justified, b
|
||||
| RFC 0014 islands, frozen graphs, arc (Phase 4) | 19 | 41 | 142 918 | 22 212 | 37 785 (+7.0 %) | — | — |
|
||||
| P4-11 AIR text grammar for Phases 2–4 | 19 | 41 | 149 279 | 22 945 | 39 154 (+3.6 %) | 39 306 | 40 382 |
|
||||
| RFC 0015 spec integration (atomics reserved) | 19 | 41 | 151 929 | 23 311 | 39 904 (+1.9 %) | 40 049 | 41 186 |
|
||||
| Phase 5 atomics implemented (layer 10) | 19 | 48 | 160 428 | 24 607 | 42 275 (+5.9 %) | 42 422 | 43 644 |
|
||||
|
||||
RFC 0011 crossed the 10 % warning line (its own estimate said "below 10 %"): four new sections in spec 04 (tasks, loans, `Send`/`Share` table, scheduler). Below the 20 % review threshold. RFC 0012 (+15.8 %, estimate 12–16 %): five sections in spec 04 (waits and cancellation, channels, select, mutex, critical-section rule). Implementation-time spec corrections (mutex linearity, `mutex.take` rules): +0.6 %. Phase 3 total since the Phase 2 baseline: +29.2 %. Next measurement: after the E-S smoke test, or with the next RFC.
|
||||
|
||||
|
||||
@@ -45,6 +45,15 @@ docs/spec/04-concurrency-and-atomics.md :: ## 39. `select` in AIR
|
||||
docs/spec/04-concurrency-and-atomics.md :: ## 40. Mutex in AIR
|
||||
docs/spec/04-concurrency-and-atomics.md :: ## 41. The critical-section rule
|
||||
|
||||
# Atomics: types, orderings, effects, mixing, instructions (the formal model of §20 is not included)
|
||||
docs/spec/04-concurrency-and-atomics.md :: ## 22. DRF-SC guarantee
|
||||
docs/spec/04-concurrency-and-atomics.md :: ## 23. Atomic types
|
||||
docs/spec/04-concurrency-and-atomics.md :: ## 24. Atomic ordering
|
||||
docs/spec/04-concurrency-and-atomics.md :: ## 25. Weak atomics
|
||||
docs/spec/04-concurrency-and-atomics.md :: ## 28. Mixing atomic and ordinary access
|
||||
docs/spec/04-concurrency-and-atomics.md :: ## 42. Atomics in AIR
|
||||
docs/spec/05-effects-and-capabilities.md :: ## 13. Atomic effects
|
||||
|
||||
# Effects, capabilities, intrinsics
|
||||
docs/spec/05-effects-and-capabilities.md :: ## 9. Effects in AIR
|
||||
docs/spec/05-effects-and-capabilities.md :: ## 10. Capabilities in AIR
|
||||
|
||||
@@ -110,5 +110,21 @@
|
||||
"o200k_base": 40049,
|
||||
"qwen2.5": 41186
|
||||
}
|
||||
},
|
||||
{
|
||||
"label": "Phase 5 atomics implemented (layer 10)",
|
||||
"language": "aji",
|
||||
"air": 0,
|
||||
"phase": 3,
|
||||
"files": 19,
|
||||
"sections": 48,
|
||||
"bytes": 160428,
|
||||
"lines": 2413,
|
||||
"words": 24607,
|
||||
"tokens": {
|
||||
"cl100k_base": 42275,
|
||||
"o200k_base": 42422,
|
||||
"qwen2.5": 43644
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -262,6 +262,34 @@ scope s { // every task spawned in s must
|
||||
```
|
||||
|
||||
Inside a `lock` block no operation may wait or spawn, and no function may be called whose effects include `task.wait` or `task.spawn` (`E4304`). One lock at a time, so lock-order deadlocks cannot happen.
|
||||
- **Atomics** (the last resort, after channels and mutexes):
|
||||
|
||||
```aji
|
||||
let count = atomic.new(0u64); // atomic<T>: bool or an integer up to 64 bits; linear
|
||||
{
|
||||
ref c = count; // every operation takes `ref`; lend `c` to tasks
|
||||
let old = atomic.add.wrap(c, 1u64, relaxed); // swap, add.wrap, sub.wrap, and, or, xor return the old value
|
||||
atomic.store(c, 5u64, release);
|
||||
let v = atomic.load(c, acquire);
|
||||
let (prev, exchanged) = atomic.compare_exchange(c, 5u64, 6u64, acq_rel, acquire);
|
||||
atomic.fence(seq_cst);
|
||||
}
|
||||
let total = atomic.take(move count); // needs no live borrow of count
|
||||
```
|
||||
|
||||
- **Every operation names its ordering** (`E4201` otherwise):
|
||||
- load: `relaxed`, `acquire`, `seq_cst`;
|
||||
- store: `relaxed`, `release`, `seq_cst`;
|
||||
- read-modify-write: any of the five;
|
||||
- fence: `acquire`, `release`, `acq_rel`, `seq_cst`;
|
||||
- `compare_exchange` failure ordering, by success ordering: `relaxed` → `relaxed`; `acquire` or `acq_rel` → `relaxed`, `acquire`; `release` → `relaxed`; `seq_cst` → `relaxed`, `acquire`, `seq_cst`.
|
||||
- **Effects:**
|
||||
- `seq_cst` only: `effects [atomic]`, and every run is an interleaving;
|
||||
- any other ordering: `effects [atomic, atomic.weak]`.
|
||||
- **Publication:**
|
||||
- the writer does `atomic.store(data, v, relaxed); atomic.store(flag, true, release);`;
|
||||
- a reader whose `atomic.load(flag, acquire)` is `true` then sees `data`.
|
||||
- `*c` is `E4202`: read a cell with `atomic.load(c, …)`.
|
||||
|
||||
## 9. Common diagnostics → repair
|
||||
|
||||
@@ -283,6 +311,8 @@ scope s { // every task spawned in s must
|
||||
| E4101 | data race with a task | lend disjoint parts (`split_at`, fields) or join first |
|
||||
| E4301 | task not joined at scope end | `task.join(move t)` before the `scope` block ends |
|
||||
| E4304 | wait inside `lock` | move the wait out of the `lock` block |
|
||||
| E4201 | ordering not valid for the operation | use one listed in `allowed` |
|
||||
| E4202 | ordinary read of an atomic cell | `atomic.load(c, ordering)` |
|
||||
| E2111 | graph content not plain data | store only integers, booleans, enums, structs/arrays of them and `iref`s in a graph |
|
||||
| T0010 | `iref` of another graph | use a handle with the graph it came from |
|
||||
| T0001–T0009 | runtime trap | see `kind` and `source_location` |
|
||||
@@ -67,6 +67,10 @@ docs/agent/source-notes.md :: ## Concurrency status
|
||||
docs/spec/15-source-language.md :: ## 7. Tasks, cancellation, channels, select and mutex
|
||||
docs/spec/04-concurrency-and-atomics.md :: ## 35. Send and Share in AIR
|
||||
docs/spec/04-concurrency-and-atomics.md :: ## 36. The deterministic scheduler
|
||||
docs/spec/15-source-language.md :: ## 12. Atomics
|
||||
docs/spec/04-concurrency-and-atomics.md :: ## 22. DRF-SC guarantee
|
||||
docs/spec/04-concurrency-and-atomics.md :: ## 24. Atomic ordering
|
||||
docs/spec/04-concurrency-and-atomics.md :: ## 25. Weak atomics
|
||||
|
||||
> language/tooling.md
|
||||
docs/spec/15-source-language.md :: ## 11. Tooling
|
||||
|
||||
@@ -23,7 +23,7 @@ You write `.aji`; you never need to write AIR. Diagnostics point at your source
|
||||
|
||||
## Concurrency status
|
||||
|
||||
The source frontend implements every layer of spec 15, concurrency included: task scopes, spawn and join, channels, `select`, `lock` and mutexes, `shield`, `task.check_cancel` and `task.join_cancel`.
|
||||
The source frontend implements every layer of spec 15, concurrency included: task scopes, spawn and join, channels, `select`, `lock` and mutexes, `shield`, `task.check_cancel`, `task.join_cancel` and atomics (layer 10).
|
||||
|
||||
## The AIR reference
|
||||
|
||||
|
||||
@@ -79,15 +79,16 @@ Phase 4 commit frozen (tag p4-frozen)
|
||||
| P5-1 | done | RFC 0015: scalar atomics and the Aji memory model (supersedes RFC 0003); closes the owner's question list; resolves Q-015; scope of Q-017 | — | `docs/rfcs/0015-…` | Accepted by the owner and integrated into spec 04, 05, 07a, 11, 15 |
|
||||
| P5-1a | done (corpus normative, owner 2026-10-06) | Litmus enumerator `tools/litmus` (an executable oracle derived from spec 04 §20, not the definition) and the normative corpus: the classes MP, SB, LB, release/acquire publication, `seq_cst` ordering (IRIW, SB with `seq_cst`), relaxed counter, CAS success/failure, fence publication, forbidden non-atomic race, atomic/non-atomic mixing, plus the handoffs (mutex, channel, spawn/join). Each test has allowed and forbidden outcome sets | P5-1 | `tools/litmus/`, `reference/concurrency-litmus.md`, `tests/litmus/` | the enumerator's allowed set equals every stated set, disagreements diagnosed (spec 04 §20.5); owner review |
|
||||
| P5-2 | done | Contract tables: `atomic.new`, `atomic.take`, `atomic.load`, `atomic.store`, RMW, `atomic.cmpxchg`, `atomic.fence` | P5-1 | spec 04 §42, spec 07a | all spec 07 §4 fields present, with the ordering tables of spec 04 §24 (integrated with RFC 0015) |
|
||||
| P5-2a | todo | Publish feature `atomics` (depends on `effects`, `ownership`) | P5-3 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests |
|
||||
| P5-3 | todo | AIR parse/print, types (linear `atomic<T>`, AtomicScalar, not IslandSafe), ordering tables, `E4202` | P5-1a | `src/air/`, `src/verifier/` | `E4201` accept/reject for every operation and every cmpxchg success/failure pair; `E4202`; `E1001`, `E2111`, `E0006` cases |
|
||||
| P5-4 | todo | `atomic` / `atomic.weak` effects (spec 05 §13); weak sites in `aji report` | P5-3 | verifier + report | each non-`seq_cst` ordering without `atomic.weak` is `E3101`; `seq_cst` needs only `atomic`; weak sites listed |
|
||||
| P5-5 | todo | Interpreter: atomic cells with message histories, views, weak reads drawn from the schedule stream; atomic operations are scheduling points | P5-3 | `src/interp/` | sound on the corpus and the differential test; no extra draw without weak accesses; existing records unchanged |
|
||||
| P5-2a | done | Publish feature `atomics` (depends on `effects`, `ownership`) | P5-3 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests |
|
||||
| P5-3 | done | AIR parse/print, types (linear `atomic<T>`, AtomicScalar, not IslandSafe), ordering tables, `E4202` | P5-1a | `src/air/`, `src/verifier/` | `E4201` accept/reject for every operation and every cmpxchg success/failure pair; `E4202`; `E1001`, `E2111`, `E0006` cases |
|
||||
| P5-4 | done | `atomic` / `atomic.weak` effects (spec 05 §13); weak sites in `aji report` | P5-3 | verifier + report | each non-`seq_cst` ordering without `atomic.weak` is `E3101`; `seq_cst` needs only `atomic`; weak sites listed |
|
||||
| P5-5 | done | Interpreter: atomic cells with message histories, views, weak reads drawn from the schedule stream; atomic operations are scheduling points | P5-3 | `src/interp/` | sound on the corpus and the differential test; no extra draw without weak accesses; existing records unchanged |
|
||||
| P5-6 | todo | Happens-before tracking and dynamic race detector (validates the verifier) | P5-5 | `src/interp/` | any race the verifier missed aborts the test run with a diagnostic |
|
||||
| P5-7 | todo | Exhaustive bounded exploration of schedules and weak-read choices | P5-5 | `src/interp/` | for each litmus test, the outcome set observed equals the oracle's allowed set exactly |
|
||||
| P5-7 | done | Exhaustive bounded exploration of schedules and weak-read choices | P5-5 | `src/interp/` | for each litmus test, the outcome set observed equals the oracle's allowed set exactly |
|
||||
| P5-8 | dropped | Record and replay: moved to Phase 8 (P8-10) by RFC 0015 D13 | — | — | — |
|
||||
| P5-9 | todo | Litmus runner and differential test (random small programs; interpreter outcomes ⊆ oracle outcomes) | P5-7 | `tests/litmus/`, `zig build litmus` | all corpus tests pass with exact equality; differential test in CI |
|
||||
| P5-9a | todo | `.aji` layer 10 (spec 15 §12), Quick Reference subsection after mutexes, source coverage rows, bundle measurement | P5-4 | `src/frontend/`, `docs/agent/` | `.aji` run/reject tests for every row; Quick Reference excerpts checked; growth recorded against RFC 0015's estimate |
|
||||
| P5-9 | done | Litmus runner and differential test (random small programs; interpreter outcomes ⊆ oracle outcomes) | P5-7 | `tests/litmus/`, `zig build litmus` | all corpus tests pass with exact equality; differential test in CI |
|
||||
| P5-9a | done | `.aji` layer 10 (spec 15 §12), Quick Reference subsection after mutexes, source coverage rows, bundle measurement | P5-4 | `src/frontend/`, `docs/agent/` | `.aji` run/reject tests for every row; Quick Reference excerpts checked; growth recorded against RFC 0015's estimate |
|
||||
| P5-9b | todo | Reference program with atomics in AIR (written by an independent author from the spec) and `.aji`, with `equivalent:` | P5-9a | `tests/conformance/` | passes under all stress modes and under `aji explore` with no forbidden outcome |
|
||||
| P5-10 | todo | Phase exit review | all | plan status | exit criterion passes |
|
||||
|
||||
## Regression gate (P5-0)
|
||||
|
||||
@@ -32,7 +32,7 @@ Declaring `features [capabilities, effects, ownership]` grants no authority. It
|
||||
|---|---|---|---|---|
|
||||
| `arc` | published | 4 | `capabilities`, `effects`, `heap`, `islands`, `ownership`, `resources` | `arc<T>`, `arc.*`, `ArcSafe` (spec 03 §24) |
|
||||
| `arrays` | published | 1 | `ownership` | `array<T, N>`, `slice<T>`, `slice_mut<T>`, `array.splat`, `borrow.index[.proven]`, `slice.*`, `guard`, bounds facts (spec 07a, spec 08 §12) |
|
||||
| `atomics` | reserved | 5 | `effects`, `ownership` | linear `atomic<T>` for AtomicScalar `T`, `atomic.new`, `atomic.take`, `atomic.load`/`store`/RMW/`cmpxchg`/`fence` with explicit orderings, effects `atomic`/`atomic.weak`, `E4201`, `E4202` (spec 04 §20–§30, §42); specified by RFC 0015, published with its implementation (P5-2a) |
|
||||
| `atomics` | published | 5 | `effects`, `ownership` | linear `atomic<T>` for AtomicScalar `T`, `atomic.new`, `atomic.take`, `atomic.load`/`store`/RMW/`cmpxchg`/`fence` with explicit orderings, effects `atomic`/`atomic.weak`, `E4201`, `E4202` (spec 04 §20–§30, §42) |
|
||||
| `borrow_joins` | reserved | — | `ownership` | borrow-typed block parameters (spec 08 §11.6); unscheduled |
|
||||
| `cancellation` | published | 3 | `effects`, `ownership`, `tasks` | effect `task.wait` (required by suspending operations, `task.join` included), waiting-operation rule, `shield`, `task.shield.*`, `task.check_cancel`, `task.join.cancel` (spec 04 §37) |
|
||||
| `capabilities` | published | 2 | `effects`, `ownership` | `cap<K>`, built-in `cap_error`, `cap.narrow`, `intrinsic`, instantiation of `@main` (spec 05 §10–§12) |
|
||||
|
||||
@@ -119,7 +119,8 @@ The toolchain should emit an audit artifact containing:
|
||||
"allocations": 0,
|
||||
"runtime_checks": {"overflow": 0, "division": 0, "shift": 0, "cast": 0, "bounds": 0, "assert": 0, "guard": 0},
|
||||
"proven_checks": {"bounds": 0},
|
||||
"unsafe_operations": [{"block": "entry", "inst": 0, "op": "borrow.index.unchecked"}]
|
||||
"unsafe_operations": [{"block": "entry", "inst": 0, "op": "borrow.index.unchecked"}],
|
||||
"atomic_operations": [{"block": "entry", "inst": 3, "op": "atomic.load", "ordering": "acquire", "weak": true}]
|
||||
}
|
||||
],
|
||||
"capability_kinds": ["…"],
|
||||
@@ -134,7 +135,8 @@ Fields:
|
||||
- `calls`, `intrinsics`: distinct callees and intrinsic names in order of first occurrence; together with `effects_*` this is the effect graph.
|
||||
- `runtime_checks`: instructions whose safety condition is checked at runtime and may trap — `overflow` (checked `add`/`sub`/`mul`, and `div`/`rem` for signed `MIN / -1`), `division` (`div`/`rem` by zero), `shift` (`shl`/`shr`), `cast` (`cast.checked`), `bounds` (`borrow.index`, `slice.sub`, `slice.split`, `slice.copy`), `assert`, `guard`.
|
||||
- `proven_checks.bounds`: `borrow.index.proven` instructions, whose check the verifier eliminated.
|
||||
- `atomic_operations` (feature `atomics`, spec 04 §25): every atomic memory operation in order. `ordering` is the operation's ordering, or `success.failure` for `atomic.cmpxchg`. `weak` is true for a non-`seq_cst` access: a site where interleaving reasoning is not enough. `effects_used` contains `atomic` for every such operation and `atomic.weak` for every weak one.
|
||||
- `capability_kinds`: distinct capability kinds appearing in any type of the module, sorted.
|
||||
- All lists of names are in order of first occurrence in the module unless stated otherwise; effect lists are sorted.
|
||||
|
||||
Ownership/borrow proof summaries, weak atomic sites, lock-order findings and contract status are added to this document by the phases that introduce them, as new fields; existing fields keep their meaning.
|
||||
Ownership/borrow proof summaries, lock-order findings and contract status are added to this document by the phases that introduce them, as new fields; existing fields keep their meaning.
|
||||
@@ -435,7 +435,7 @@ Lowering is deterministic: the same source and compiler give byte-identical AIR,
|
||||
|
||||
## 12. Atomics
|
||||
|
||||
Spec 04 §20–§30, §42; layer 10, RFC 0015. This layer is specified now and implemented in Phase 5, together with the publication of feature `atomics`. Until then the frontend rejects it as an unknown construct. The section enters the Source Reference Bundle with the implementation (P5-9a).
|
||||
Spec 04 §20–§30, §42; layer 10, RFC 0015. Implemented with the publication of feature `atomics` (Phase 5).
|
||||
|
||||
| Source | AIR |
|
||||
|---|---|
|
||||
|
||||
@@ -25,6 +25,8 @@ pub const ArithMode = module.ArithMode;
|
||||
pub const BitOp = module.BitOp;
|
||||
pub const CmpOp = module.CmpOp;
|
||||
pub const CastMode = module.CastMode;
|
||||
pub const Ordering = module.Ordering;
|
||||
pub const RmwOp = module.RmwOp;
|
||||
pub const forEachUse = module.forEachUse;
|
||||
pub const successors = module.successors;
|
||||
pub const allocTargets = module.allocTargets;
|
||||
|
||||
@@ -24,7 +24,7 @@ pub const Feature = struct {
|
||||
pub const registry = [_]Feature{
|
||||
.{ .name = "arc", .depends = &.{ "capabilities", "effects", "heap", "islands", "ownership", "resources" }, .status = .published, .phase = 4 },
|
||||
.{ .name = "arrays", .depends = &.{"ownership"}, .status = .published, .phase = 1 },
|
||||
.{ .name = "atomics", .depends = &.{ "effects", "ownership" }, .status = .reserved, .phase = 5 },
|
||||
.{ .name = "atomics", .depends = &.{ "effects", "ownership" }, .status = .published, .phase = 5 },
|
||||
.{ .name = "borrow_joins", .depends = &.{"ownership"}, .status = .reserved, .phase = null },
|
||||
.{ .name = "cancellation", .depends = &.{ "effects", "ownership", "tasks" }, .status = .published, .phase = 3 },
|
||||
.{ .name = "capabilities", .depends = &.{ "effects", "ownership" }, .status = .published, .phase = 2 },
|
||||
@@ -49,7 +49,7 @@ pub const registry = [_]Feature{
|
||||
};
|
||||
|
||||
/// Features implemented by this toolchain, sorted.
|
||||
pub const supported = [_][]const u8{ "arc", "arrays", "cancellation", "capabilities", "channels", "effects", "heap", "islands", "ownership", "regions", "resources", "sync", "tasks", "unsafe" };
|
||||
pub const supported = [_][]const u8{ "arc", "arrays", "atomics", "cancellation", "capabilities", "channels", "effects", "heap", "islands", "ownership", "regions", "resources", "sync", "tasks", "unsafe" };
|
||||
|
||||
pub const Reason = enum {
|
||||
unknown_feature,
|
||||
|
||||
+67
-5
@@ -99,6 +99,8 @@ pub const Type = union(enum) {
|
||||
frozen: *const Type,
|
||||
arc: *const Type,
|
||||
iref: *const Type,
|
||||
// Feature `atomics` (spec 04 §23, §42): a linear atomic cell.
|
||||
atomic: *const Type,
|
||||
|
||||
pub const Array = struct { elem: Type, len: u64 };
|
||||
|
||||
@@ -107,7 +109,7 @@ pub const Type = union(enum) {
|
||||
return switch (a) {
|
||||
.int => |x| b.int == x,
|
||||
.named => |x| b.named == x,
|
||||
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.eql(b.inner().?),
|
||||
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.eql(b.inner().?),
|
||||
.region, .scope, .shield => true,
|
||||
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
|
||||
.cap => |k| b.cap == k,
|
||||
@@ -120,7 +122,7 @@ pub const Type = union(enum) {
|
||||
/// Element or pointee type of storage, borrow and slice types.
|
||||
pub fn inner(t: Type) ?Type {
|
||||
return switch (t) {
|
||||
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.*,
|
||||
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.*,
|
||||
.array => |a| a.elem,
|
||||
else => null,
|
||||
};
|
||||
@@ -137,7 +139,7 @@ pub const Type = union(enum) {
|
||||
/// Linear values: consumed exactly once (spec 06 §6.2–§6.3).
|
||||
pub fn isLinear(t: Type) bool {
|
||||
return switch (t) {
|
||||
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc => true,
|
||||
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
@@ -171,7 +173,7 @@ pub const Type = union(enum) {
|
||||
/// Linear resources are neither values nor borrows: they are moved.
|
||||
pub fn isValue(t: Type) bool {
|
||||
return switch (t) {
|
||||
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc => false,
|
||||
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => false,
|
||||
else => true,
|
||||
};
|
||||
}
|
||||
@@ -239,6 +241,41 @@ pub const BitOp = enum { @"and", @"or", xor, shl, shr };
|
||||
pub const CmpOp = enum { eq, ne, lt, le, gt, ge };
|
||||
pub const CastMode = enum { checked, wrap, widen };
|
||||
|
||||
/// Memory orderings (spec 04 §24). There is no default and no `consume`.
|
||||
pub const Ordering = enum {
|
||||
relaxed,
|
||||
acquire,
|
||||
release,
|
||||
acq_rel,
|
||||
seq_cst,
|
||||
|
||||
pub fn hasAcquire(o: Ordering) bool {
|
||||
return o == .acquire or o == .acq_rel or o == .seq_cst;
|
||||
}
|
||||
|
||||
pub fn hasRelease(o: Ordering) bool {
|
||||
return o == .release or o == .acq_rel or o == .seq_cst;
|
||||
}
|
||||
};
|
||||
|
||||
/// Atomic read-modify-write operations (spec 04 §24.2).
|
||||
pub const RmwOp = enum {
|
||||
xchg,
|
||||
add_wrap,
|
||||
sub_wrap,
|
||||
@"and",
|
||||
@"or",
|
||||
xor,
|
||||
|
||||
pub fn text(op: RmwOp) []const u8 {
|
||||
return switch (op) {
|
||||
.add_wrap => "add.wrap",
|
||||
.sub_wrap => "sub.wrap",
|
||||
inline else => |o| @tagName(o),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
pub const Op = union(enum) {
|
||||
// Feature `ownership` (spec 07a).
|
||||
local_alloc: Type,
|
||||
@@ -341,6 +378,15 @@ pub const Op = union(enum) {
|
||||
arc_root: ValueId,
|
||||
arc_borrow: struct { owner: ValueId, iref: ValueId },
|
||||
iref_eq: struct { a: ValueId, b: ValueId },
|
||||
// Feature `atomics` (spec 04 §42).
|
||||
atomic_new: ValueId,
|
||||
atomic_take: ValueId,
|
||||
atomic_load: struct { cell: ValueId, ord: Ordering },
|
||||
atomic_store: struct { cell: ValueId, value: ValueId, ord: Ordering },
|
||||
atomic_rmw: struct { op: RmwOp, cell: ValueId, value: ValueId, ord: Ordering },
|
||||
/// Two results: `Inst.result` (old value) and `Inst.result2` (exchanged).
|
||||
atomic_cmpxchg: struct { cell: ValueId, expected: ValueId, desired: ValueId, success: Ordering, failure: Ordering },
|
||||
atomic_fence: Ordering,
|
||||
ret: ?ValueId,
|
||||
trap,
|
||||
|
||||
@@ -375,7 +421,7 @@ pub const Op = union(enum) {
|
||||
|
||||
pub const Inst = struct {
|
||||
result: ?ValueId,
|
||||
/// Second result of `slice.split`.
|
||||
/// Second result of `slice.split` and `atomic.cmpxchg`.
|
||||
result2: ?ValueId = null,
|
||||
op: Op,
|
||||
span: Span,
|
||||
@@ -525,6 +571,22 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
|
||||
f(ctx, x.a);
|
||||
f(ctx, x.b);
|
||||
},
|
||||
.atomic_new, .atomic_take => |v| f(ctx, v),
|
||||
.atomic_load => |x| f(ctx, x.cell),
|
||||
.atomic_store => |x| {
|
||||
f(ctx, x.cell);
|
||||
f(ctx, x.value);
|
||||
},
|
||||
.atomic_rmw => |x| {
|
||||
f(ctx, x.cell);
|
||||
f(ctx, x.value);
|
||||
},
|
||||
.atomic_cmpxchg => |x| {
|
||||
f(ctx, x.cell);
|
||||
f(ctx, x.expected);
|
||||
f(ctx, x.desired);
|
||||
},
|
||||
.atomic_fence => {},
|
||||
.task_join_cancel => |x| f(ctx, x.task),
|
||||
.channel_make => |x| {
|
||||
f(ctx, x.cap);
|
||||
|
||||
+80
-3
@@ -560,7 +560,7 @@ const Parser = struct {
|
||||
boxed.* = inner;
|
||||
return if (eql(t.text, "own")) .{ .own = boxed } else .{ .own_array = boxed };
|
||||
}
|
||||
const Wrapper = enum { task, sender, receiver, mutex, guard, island, frozen, arc, iref };
|
||||
const Wrapper = enum { task, sender, receiver, mutex, guard, island, frozen, arc, iref, atomic };
|
||||
if (std.meta.stringToEnum(Wrapper, t.text)) |which| {
|
||||
try p.requireFeature(switch (which) {
|
||||
.task => "tasks",
|
||||
@@ -568,6 +568,7 @@ const Parser = struct {
|
||||
.mutex, .guard => "sync",
|
||||
.island, .frozen, .iref => "islands",
|
||||
.arc => "arc",
|
||||
.atomic => "atomics",
|
||||
}, t.span, t.text);
|
||||
_ = try p.expect(.lt, "`<`");
|
||||
// Element rules (spec 04 §38.1) are checked by the type stage.
|
||||
@@ -585,6 +586,7 @@ const Parser = struct {
|
||||
.frozen => .{ .frozen = boxed },
|
||||
.arc => .{ .arc = boxed },
|
||||
.iref => .{ .iref = boxed },
|
||||
.atomic => .{ .atomic = boxed },
|
||||
};
|
||||
}
|
||||
if (eql(t.text, "cap")) {
|
||||
@@ -1015,6 +1017,10 @@ const Parser = struct {
|
||||
}
|
||||
if (try p.parseAllocOp(op_tok)) |aop| break :op aop;
|
||||
if (try p.parseGraphOp(op_tok)) |gop| break :op gop;
|
||||
if (std.mem.startsWith(u8, op_tok.text, "atomic.")) {
|
||||
if (try p.parseAtomicOp(op_tok)) |aop| break :op aop;
|
||||
return p.unknownOpcode(op_tok);
|
||||
}
|
||||
if (try p.parseTaskOp(op_tok)) |top| break :op top;
|
||||
if (try p.parseCoordinationOp(op_tok)) |cop| break :op cop;
|
||||
if (eql(op_tok.text, "intrinsic")) {
|
||||
@@ -1046,6 +1052,7 @@ const Parser = struct {
|
||||
.own_take, .task_scope_begin, .task_spawn, .task_cancelled => true,
|
||||
.task_shield_begin, .channel_dup, .mutex_make, .mutex_take, .mutex_borrow => true,
|
||||
.island_root, .island_borrow, .island_freeze, .frozen_root, .frozen_borrow, .arc_from_frozen, .arc_clone, .arc_root, .arc_borrow, .iref_eq => true,
|
||||
.atomic_new, .atomic_take, .atomic_load, .atomic_rmw, .atomic_cmpxchg => true,
|
||||
.@"const", .copy, .arith, .bit, .cmp, .cast, .struct_make, .struct_get, .enum_make => true,
|
||||
.local_alloc, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .load => true,
|
||||
.array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true,
|
||||
@@ -1057,8 +1064,9 @@ const Parser = struct {
|
||||
} else if (produces_value) {
|
||||
return p.fail(op_tok, "result binding `%name =`");
|
||||
}
|
||||
if ((op == .slice_split) != (result2_tok != null)) {
|
||||
return p.fail(result_tok orelse op_tok, if (op == .slice_split) "two results `%left, %right =`" else "a single result");
|
||||
const two_results = op == .slice_split or op == .atomic_cmpxchg;
|
||||
if (two_results != (result2_tok != null)) {
|
||||
return p.fail(result_tok orelse op_tok, if (op == .slice_split) "two results `%left, %right =`" else if (op == .atomic_cmpxchg) "two results `%old, %exchanged =`" else "a single result");
|
||||
}
|
||||
const def: air.ValueInfo.Def = .{ .inst = .{ .block = block, .index = index } };
|
||||
const result = if (result_tok) |rt| try p.defineValue(rt, def) else null;
|
||||
@@ -1254,6 +1262,75 @@ const Parser = struct {
|
||||
}
|
||||
}
|
||||
|
||||
/// Instructions of the feature `atomics` (spec 04 §42). The orderings are
|
||||
/// part of the opcode; which are valid for an operation is the type
|
||||
/// stage's (`E4201`). Returns null for an opcode that is not one of them.
|
||||
fn parseAtomicOp(p: *Parser, op_tok: Token) Error!?air.Op {
|
||||
var buf: [5][]const u8 = undefined;
|
||||
var n: usize = 0;
|
||||
var it = std.mem.splitScalar(u8, op_tok.text, '.');
|
||||
while (it.next()) |part| {
|
||||
if (n == buf.len) return null;
|
||||
buf[n] = part;
|
||||
n += 1;
|
||||
}
|
||||
const parts = buf[0..n];
|
||||
const ord = struct {
|
||||
fn of(t: []const u8) ?air.Ordering {
|
||||
return std.meta.stringToEnum(air.Ordering, t);
|
||||
}
|
||||
}.of;
|
||||
const Name = enum { new, take, load, store, xchg, add, sub, @"and", @"or", xor, cmpxchg, fence };
|
||||
const name = std.meta.stringToEnum(Name, parts[1]) orelse return null;
|
||||
try p.requireFeature("atomics", op_tok.span, op_tok.text);
|
||||
switch (name) {
|
||||
.new, .take => {
|
||||
if (n != 2) return null;
|
||||
const v = try p.useValue();
|
||||
return if (name == .new) .{ .atomic_new = v } else .{ .atomic_take = v };
|
||||
},
|
||||
.load => {
|
||||
if (n != 3) return null;
|
||||
const o = ord(parts[2]) orelse return null;
|
||||
return .{ .atomic_load = .{ .cell = try p.useValue(), .ord = o } };
|
||||
},
|
||||
.store => {
|
||||
if (n != 3) return null;
|
||||
const o = ord(parts[2]) orelse return null;
|
||||
const c, const v = try p.twoOperands();
|
||||
return .{ .atomic_store = .{ .cell = c, .value = v, .ord = o } };
|
||||
},
|
||||
.xchg, .@"and", .@"or", .xor, .add, .sub => {
|
||||
const wraps = name == .add or name == .sub;
|
||||
if (n != (if (wraps) @as(usize, 4) else 3)) return null;
|
||||
if (wraps and !std.mem.eql(u8, parts[2], "wrap")) return null;
|
||||
const o = ord(parts[n - 1]) orelse return null;
|
||||
const op: air.RmwOp = switch (name) {
|
||||
.xchg => .xchg,
|
||||
.add => .add_wrap,
|
||||
.sub => .sub_wrap,
|
||||
.@"and" => .@"and",
|
||||
.@"or" => .@"or",
|
||||
else => .xor,
|
||||
};
|
||||
const c, const v = try p.twoOperands();
|
||||
return .{ .atomic_rmw = .{ .op = op, .cell = c, .value = v, .ord = o } };
|
||||
},
|
||||
.cmpxchg => {
|
||||
if (n != 4) return null;
|
||||
const sc = ord(parts[2]) orelse return null;
|
||||
const fl = ord(parts[3]) orelse return null;
|
||||
const c, const e = try p.twoOperands();
|
||||
_ = try p.expect(.comma, "`,`");
|
||||
return .{ .atomic_cmpxchg = .{ .cell = c, .expected = e, .desired = try p.useValue(), .success = sc, .failure = fl } };
|
||||
},
|
||||
.fence => {
|
||||
if (n != 3) return null;
|
||||
return .{ .atomic_fence = ord(parts[2]) orelse return null };
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Instructions of the features `heap` and `regions` (spec 03 §19–§20).
|
||||
fn parseAllocOp(p: *Parser, op_tok: Token) Error!?air.Op {
|
||||
const Name = enum { @"own.new", @"own.array", @"own.take", @"own.free", @"region.create", @"region.new", @"region.array", @"region.reset", @"region.destroy" };
|
||||
|
||||
+28
-1
@@ -122,7 +122,7 @@ pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void {
|
||||
},
|
||||
.region => try w.writeAll("region"),
|
||||
.scope => try w.writeAll("scope"),
|
||||
.task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |inner| {
|
||||
.task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |inner| {
|
||||
try w.print("{s}<", .{@tagName(t)});
|
||||
try printType(m, inner.*, w);
|
||||
try w.writeByte('>');
|
||||
@@ -422,6 +422,33 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
|
||||
.frozen_borrow => |x| try two(f, w, "frozen.borrow", x.owner, x.iref),
|
||||
.arc_borrow => |x| try two(f, w, "arc.borrow", x.owner, x.iref),
|
||||
.iref_eq => |x| try two(f, w, "iref.eq", x.a, x.b),
|
||||
.atomic_new => |v| try one(f, w, "atomic.new", v),
|
||||
.atomic_take => |v| try one(f, w, "atomic.take", v),
|
||||
.atomic_load => |x| {
|
||||
try w.print("atomic.load.{s} ", .{@tagName(x.ord)});
|
||||
try value(f, x.cell, w);
|
||||
},
|
||||
.atomic_store => |x| {
|
||||
try w.print("atomic.store.{s} ", .{@tagName(x.ord)});
|
||||
try value(f, x.cell, w);
|
||||
try w.writeAll(", ");
|
||||
try value(f, x.value, w);
|
||||
},
|
||||
.atomic_rmw => |x| {
|
||||
try w.print("atomic.{s}.{s} ", .{ x.op.text(), @tagName(x.ord) });
|
||||
try value(f, x.cell, w);
|
||||
try w.writeAll(", ");
|
||||
try value(f, x.value, w);
|
||||
},
|
||||
.atomic_cmpxchg => |x| {
|
||||
try w.print("atomic.cmpxchg.{s}.{s} ", .{ @tagName(x.success), @tagName(x.failure) });
|
||||
try value(f, x.cell, w);
|
||||
try w.writeAll(", ");
|
||||
try value(f, x.expected, w);
|
||||
try w.writeAll(", ");
|
||||
try value(f, x.desired, w);
|
||||
},
|
||||
.atomic_fence => |o| try w.print("atomic.fence.{s}", .{@tagName(o)}),
|
||||
.cap_narrow => |x| {
|
||||
try w.print("cap.narrow.{s} ", .{x.form});
|
||||
try value(f, x.cap, w);
|
||||
|
||||
+131
-7
@@ -73,13 +73,15 @@ pub const Ty = union(enum) {
|
||||
frozen: *const Ty,
|
||||
arc: *const Ty,
|
||||
iref: *const Ty,
|
||||
/// `atomic<T>` (spec 04 §23; layer 10): a linear cell.
|
||||
atomic: *const Ty,
|
||||
|
||||
pub const Arr = struct { elem: Ty, len: u64 };
|
||||
|
||||
/// Linear: consumed exactly once, by `move` (spec 15 §5).
|
||||
fn isLinear(t: Ty) bool {
|
||||
return switch (t) {
|
||||
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield, .island, .frozen, .arc => true,
|
||||
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield, .island, .frozen, .arc, .atomic => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
@@ -90,7 +92,7 @@ pub const Ty = union(enum) {
|
||||
.int => |x| std.mem.eql(u8, x, b.int),
|
||||
.named => |i| i == b.named,
|
||||
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.eql(inner(b).?),
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.eql(inner(b).?),
|
||||
.cap => |k| std.mem.eql(u8, k, b.cap),
|
||||
.builtin => |e| e == b.builtin,
|
||||
.resource => |r| r == b.resource,
|
||||
@@ -100,7 +102,7 @@ pub const Ty = union(enum) {
|
||||
|
||||
fn inner(t: Ty) ?Ty {
|
||||
return switch (t) {
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.*,
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.*,
|
||||
.array => |a| a.elem,
|
||||
else => null,
|
||||
};
|
||||
@@ -117,6 +119,11 @@ pub const Ty = union(enum) {
|
||||
|
||||
const int_types = [_][]const u8{ "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize" };
|
||||
|
||||
/// AtomicScalar (spec 04 §23): `bool` and integers of at most 64 bits.
|
||||
fn atomicScalar(t: Ty) bool {
|
||||
return t == .bool or (t == .int and intBits(t.int) <= 64);
|
||||
}
|
||||
|
||||
fn isIntName(n: []const u8) bool {
|
||||
for (int_types) |t| if (std.mem.eql(u8, t, n)) return true;
|
||||
return false;
|
||||
@@ -327,7 +334,7 @@ const Lowerer = struct {
|
||||
.never => "never",
|
||||
.named => |i| l.typeNames[i],
|
||||
.array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.tyText(a.elem), a.len }) catch "array",
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
|
||||
.scope => "scope",
|
||||
.shield => "shield",
|
||||
.region => "region",
|
||||
@@ -449,6 +456,9 @@ const Lowerer = struct {
|
||||
.{ "cancellation", &.{ "task.shield", "task.check_cancel", "task.join.cancel" } },
|
||||
.{ "islands", &.{ "island.", "island<", "frozen.", "frozen<", "iref.", "iref<" } },
|
||||
.{ "arc", &.{ "arc.", "arc<" } },
|
||||
// Instructions only: the effect names `atomic` and `atomic.weak`
|
||||
// in a function header are not uses of the feature.
|
||||
.{ "atomics", &.{ "= atomic.", "atomic.store.", "atomic.fence.", "atomic<" } },
|
||||
};
|
||||
for (rules) |r| {
|
||||
const used = for (texts.items) |t| {
|
||||
@@ -519,7 +529,7 @@ const Lowerer = struct {
|
||||
},
|
||||
.array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len),
|
||||
.wrapped => |w| {
|
||||
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver, mutex, island, frozen, arc, iref };
|
||||
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver, mutex, island, frozen, arc, iref, atomic };
|
||||
const which = std.meta.stringToEnum(Wr, w.wrapper) orelse return l.notYet(t.span, "this type (later layers)");
|
||||
const in = try l.typeOf(w.inner.*);
|
||||
return switch (which) {
|
||||
@@ -537,6 +547,7 @@ const Lowerer = struct {
|
||||
.frozen => l.wrap(.frozen, in),
|
||||
.arc => l.wrap(.arc, in),
|
||||
.iref => l.wrap(.iref, in),
|
||||
.atomic => if (atomicScalar(in)) l.wrap(.atomic, in) else l.fail("E7005", t.span, "atomic<T> needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = l.tyText(in) }}),
|
||||
};
|
||||
},
|
||||
.cap => |k| {
|
||||
@@ -856,7 +867,10 @@ const Lowerer = struct {
|
||||
fn stmt(l: *Lowerer, s: ast.Stmt) Error!void {
|
||||
switch (s.kind) {
|
||||
.let => |x| {
|
||||
if (x.names.len == 2) return l.splitLet(s, x.names, x.e);
|
||||
if (x.names.len == 2) {
|
||||
if (pathOf(x.e.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "atomic.compare_exchange")) return l.compareExchangeLet(s, x.names, x.e);
|
||||
return l.splitLet(s, x.names, x.e);
|
||||
}
|
||||
if (x.e.kind == .borrow) return l.fail("E7006", x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{});
|
||||
if (x.e.kind == .bytes) {
|
||||
const st = try l.materializeBytes(x.e.kind.bytes, x.e.span);
|
||||
@@ -1239,6 +1253,8 @@ const Lowerer = struct {
|
||||
const r = try l.expr(x.*, null);
|
||||
const in = r.ty.inner() orelse return l.fail("E7005", e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = l.tyText(r.ty) }});
|
||||
if (r.ty == .slice or r.ty == .slice_mut or in == .array) return l.fail("E7006", e.span, "read slice and array elements with `s[i]`, not `*`", &.{});
|
||||
// The verifier's code (spec 15 §1 rule 2, spec 04 §28).
|
||||
if (in == .atomic) return l.fail("E4202", e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{});
|
||||
return l.def("v", in, try l.fmt("load %{s}", .{r.name}), e.span);
|
||||
},
|
||||
.index => |x| {
|
||||
@@ -1421,6 +1437,7 @@ const Lowerer = struct {
|
||||
return .{ .name = "", .ty = .void };
|
||||
}
|
||||
if (try l.concurrencyCall(e, p, args)) |v| return v;
|
||||
if (std.mem.startsWith(u8, p, "atomic.")) return l.atomicCall(e, p, args);
|
||||
if (authority.intrinsicIndex(p)) |ix| {
|
||||
const x = authority.intrinsics[ix];
|
||||
var temps: std.ArrayList([]const u8) = .empty;
|
||||
@@ -1725,6 +1742,14 @@ const Lowerer = struct {
|
||||
const eq = std.mem.eql;
|
||||
if ((eq(u8, p, "own.take") or eq(u8, p, "task.join")) and args.len == 1) return if (l.peekType(args[0])) |t| t.inner() else null;
|
||||
if (eq(u8, p, "task.cancelled")) return .bool;
|
||||
if (std.mem.startsWith(u8, p, "atomic.") and args.len >= 1) {
|
||||
if (eq(u8, p, "atomic.new")) return if (l.peekType(args[0])) |t| (l.wrap(.atomic, t) catch null) else null;
|
||||
if (eq(u8, p, "atomic.take")) return if (l.peekType(args[0])) |t| t.inner() else null;
|
||||
if (eq(u8, p, "atomic.store") or eq(u8, p, "atomic.fence") or eq(u8, p, "atomic.compare_exchange")) return null;
|
||||
// A `ref a` argument, or a `ref<atomic<T>>` binding: the cell's T.
|
||||
const cell: ?Ty = if (args[0].kind == .borrow) l.peekType(args[0].kind.borrow.place.*) else if (l.peekType(args[0])) |t| t.inner() else null;
|
||||
return if (cell) |c| (if (c == .atomic) c.inner() else null) else null;
|
||||
}
|
||||
if ((eq(u8, p, "island.root") or eq(u8, p, "frozen.root") or eq(u8, p, "arc.root")) and args.len == 1)
|
||||
return if (l.peekType(args[0])) |t| (if (t.inner()) |o| (if (o.inner()) |root| l.wrap(.iref, root) catch null else null) else null) else null;
|
||||
if (eq(u8, p, "island.freeze") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .island) l.wrap(.frozen, t.inner().?) catch null else null) else null;
|
||||
@@ -1900,6 +1925,8 @@ const Lowerer = struct {
|
||||
.region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region),
|
||||
.resource, .mutex, .sender, .receiver, .task, .island => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
|
||||
.frozen, .arc => if (mutable) return l.fail("E7005", place.span, "frozen graphs and arcs are immutable: borrow them with `ref`", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
|
||||
// Atomic operations go through a shared borrow (spec 04 §23).
|
||||
.atomic => if (mutable) return l.fail("E7005", place.span, "an atomic cell is borrowed with `ref`: every atomic operation goes through a shared borrow", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
|
||||
else => null,
|
||||
};
|
||||
const t = bt orelse return l.fail("E7006", place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }});
|
||||
@@ -2164,6 +2191,101 @@ const Lowerer = struct {
|
||||
|
||||
// ------------------------------------------------------------ tasks and channels (layer 7)
|
||||
|
||||
// ------------------------------------------------------------ atomics (spec 15 §12, spec 04 §42)
|
||||
|
||||
/// An ordering, written as a bare word (spec 15 §12).
|
||||
fn ordering(l: *Lowerer, a: ast.Expr) Error![]const u8 {
|
||||
const words = [_][]const u8{ "relaxed", "acquire", "release", "acq_rel", "seq_cst" };
|
||||
if (a.kind == .name) for (words) |w| if (std.mem.eql(u8, a.kind.name, w)) return w;
|
||||
return l.fail("E7006", a.span, "an ordering is one of the words relaxed, acquire, release, acq_rel, seq_cst, written in place", &.{});
|
||||
}
|
||||
|
||||
/// The cell operand of an atomic operation: a `ref<atomic<T>>` binding or
|
||||
/// parameter, or `ref a` of an atomic, borrowed for the operation.
|
||||
fn cellOperand(l: *Lowerer, a: ast.Expr, temps: *std.ArrayList([]const u8)) Error!Value {
|
||||
if (a.kind == .borrow) {
|
||||
const br = a.kind.borrow;
|
||||
if (br.mutable) return l.fail("E7005", a.span, "atomic operations take `ref` of the cell, never `mut`", &.{});
|
||||
const b = try l.bindingOf(br.place.*, "an atomic cell");
|
||||
if (b.ty != .atomic) return l.fail("E7005", a.span, "an atomic operation takes `ref` of an `atomic<T>`", &.{.{ .name = "found", .value = l.tyText(b.ty) }});
|
||||
const r = try l.def(br.place.kind.name, try l.wrap(.ref, b.ty), try l.fmt("borrow.ref %{s}", .{b.value}), a.span);
|
||||
try temps.append(l.arena, r.name);
|
||||
return r;
|
||||
}
|
||||
const b = try l.bindingOf(a, "an atomic cell");
|
||||
if (b.ty == .atomic) return l.fail("E7005", a.span, "pass the cell as `ref a` (or a `ref` binding of it): atomic operations go through a shared borrow", &.{.{ .name = "suggestion", .value = try l.fmt("ref {s}", .{a.kind.name}) }});
|
||||
if (b.ty == .ref and b.ty.inner().? == .atomic) return .{ .name = b.value, .ty = b.ty };
|
||||
return l.fail("E7005", a.span, "an atomic operation takes a `ref<atomic<T>>`", &.{.{ .name = "found", .value = l.tyText(b.ty) }});
|
||||
}
|
||||
|
||||
fn atomicCall(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!Value {
|
||||
const eq = std.mem.eql;
|
||||
if (eq(u8, p, "atomic.new")) {
|
||||
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.new` takes the initial value", &.{});
|
||||
const v = try l.expr(args[0], null);
|
||||
if (!atomicScalar(v.ty)) return l.fail("E7005", args[0].span, "atomic<T> needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = l.tyText(v.ty) }});
|
||||
return l.def("atomic", try l.wrap(.atomic, v.ty), try l.fmt("atomic.new %{s}", .{v.name}), e.span);
|
||||
}
|
||||
if (eq(u8, p, "atomic.take")) {
|
||||
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.take` takes one cell", &.{});
|
||||
const c = try l.consuming(args[0], null);
|
||||
if (c.ty != .atomic) return l.fail("E7005", args[0].span, "`atomic.take` takes an `atomic<T>`", &.{.{ .name = "found", .value = l.tyText(c.ty) }});
|
||||
return l.def("v", c.ty.inner().?, try l.fmt("atomic.take %{s}", .{c.name}), e.span);
|
||||
}
|
||||
if (eq(u8, p, "atomic.fence")) {
|
||||
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.fence` takes one ordering", &.{});
|
||||
try l.emit(try l.fmt("atomic.fence.{s}", .{try l.ordering(args[0])}), e.span);
|
||||
return .{ .name = "", .ty = .void };
|
||||
}
|
||||
if (eq(u8, p, "atomic.compare_exchange"))
|
||||
return l.fail("E7006", e.span, "`atomic.compare_exchange` has two results: `let (old, exchanged) = atomic.compare_exchange(c, expected, desired, success, failure);`", &.{});
|
||||
var temps: std.ArrayList([]const u8) = .empty;
|
||||
const want: usize = if (eq(u8, p, "atomic.load")) 2 else 3;
|
||||
if (args.len != want) return l.fail("E7005", e.span, "wrong number of operands", &.{ .{ .name = "operation", .value = p }, .{ .name = "expected", .value = try l.fmt("{d}", .{want}) } });
|
||||
const c = try l.cellOperand(args[0], &temps);
|
||||
const t = c.ty.inner().?.inner().?;
|
||||
const ord = try l.ordering(args[want - 1]);
|
||||
if (eq(u8, p, "atomic.load")) {
|
||||
const v = try l.def("v", t, try l.fmt("atomic.load.{s} %{s}", .{ ord, c.name }), e.span);
|
||||
try l.endNow(temps.items, e.span);
|
||||
return v;
|
||||
}
|
||||
const operand = try l.expr(args[1], t);
|
||||
try l.checkTy(args[1].span, operand.ty, t);
|
||||
if (eq(u8, p, "atomic.store")) {
|
||||
try l.emit(try l.fmt("atomic.store.{s} %{s}, %{s}", .{ ord, c.name, operand.name }), e.span);
|
||||
try l.endNow(temps.items, e.span);
|
||||
return .{ .name = "", .ty = .void };
|
||||
}
|
||||
const op: []const u8 = if (eq(u8, p, "atomic.swap")) "xchg" else p["atomic.".len..];
|
||||
if ((eq(u8, op, "add.wrap") or eq(u8, op, "sub.wrap")) and t != .int) return l.fail("E7005", args[1].span, "`atomic.add.wrap` and `atomic.sub.wrap` need an integer cell", &.{.{ .name = "found", .value = l.tyText(t) }});
|
||||
const v = try l.def("old", t, try l.fmt("atomic.{s}.{s} %{s}, %{s}", .{ op, ord, c.name, operand.name }), e.span);
|
||||
try l.endNow(temps.items, e.span);
|
||||
return v;
|
||||
}
|
||||
|
||||
/// `let (old, exchanged) = atomic.compare_exchange(c, expected, desired,
|
||||
/// success, failure);` (spec 15 §12): the second multi-result binding.
|
||||
fn compareExchangeLet(l: *Lowerer, s: ast.Stmt, names: []const []const u8, e: ast.Expr) Error!void {
|
||||
const args = e.kind.call.args;
|
||||
if (args.len != 5) return l.fail("E7005", e.span, "`atomic.compare_exchange` takes a cell, the expected and the desired value, and two orderings", &.{});
|
||||
var temps: std.ArrayList([]const u8) = .empty;
|
||||
const c = try l.cellOperand(args[0], &temps);
|
||||
const t = c.ty.inner().?.inner().?;
|
||||
const expected = try l.expr(args[1], t);
|
||||
try l.checkTy(args[1].span, expected.ty, t);
|
||||
const desired = try l.expr(args[2], t);
|
||||
try l.checkTy(args[2].span, desired.ty, t);
|
||||
const succ = try l.ordering(args[3]);
|
||||
const failure = try l.ordering(args[4]);
|
||||
const old = try l.freshName(names[0]);
|
||||
const ok = try l.freshName(names[1]);
|
||||
try l.emit(try l.fmt("%{s}, %{s} = atomic.cmpxchg.{s}.{s} %{s}, %{s}, %{s}", .{ old, ok, succ, failure, c.name, expected.name, desired.name }), s.span);
|
||||
try l.endNow(temps.items, s.span);
|
||||
try l.bindings.append(l.arena, .{ .name = names[0], .mutable = false, .value = old, .ty = t, .kind = .ssa });
|
||||
try l.bindings.append(l.arena, .{ .name = names[1], .mutable = false, .value = ok, .ty = .bool, .kind = .ssa });
|
||||
}
|
||||
|
||||
fn bindingOf(l: *Lowerer, a: ast.Expr, what: []const u8) Error!*Binding {
|
||||
if (a.kind != .name) return l.fail("E7005", a.span, try l.fmt("{s} is expected here, by name", .{what}), &.{});
|
||||
return l.lookup(a.kind.name) orelse l.unknown(a.span, a.kind.name);
|
||||
@@ -2934,7 +3056,9 @@ fn pathOf(e: ast.Expr) ?[]const u8 {
|
||||
"task.join_cancel", "island.create", "island.alloc", "island.root", "island.at",
|
||||
"island.freeze", "island.destroy", "frozen.root", "frozen.at", "frozen.release",
|
||||
"arc.from_frozen", "arc.new", "arc.clone", "arc.release", "arc.root",
|
||||
"arc.at",
|
||||
"arc.at", "atomic.new", "atomic.take", "atomic.load", "atomic.store",
|
||||
"atomic.swap", "atomic.add.wrap", "atomic.sub.wrap", "atomic.and", "atomic.or",
|
||||
"atomic.xor", "atomic.compare_exchange", "atomic.fence",
|
||||
};
|
||||
var buf: [64]u8 = undefined;
|
||||
const text = dotted(e, &buf) orelse return null;
|
||||
|
||||
@@ -17,6 +17,8 @@ pub const MemoryStats = machine.MemoryStats;
|
||||
|
||||
/// For `tests/extended/memory.zig`: the loop shapes of the memory invariant
|
||||
/// test and the function that measures one.
|
||||
pub const Explore = machine.Explore;
|
||||
|
||||
pub const memory_test = struct {
|
||||
pub const loop_shapes = machine.loop_shapes;
|
||||
pub const memoryOf = machine.memoryOf;
|
||||
@@ -25,4 +27,5 @@ pub const memory_test = struct {
|
||||
|
||||
test {
|
||||
_ = machine;
|
||||
_ = @import("interp/weak.zig");
|
||||
}
|
||||
+312
-34
@@ -27,6 +27,7 @@ const diag = @import("../diag.zig");
|
||||
const world_mod = @import("world.zig");
|
||||
const host_mod = @import("host.zig");
|
||||
const budget = @import("../verifier/budget.zig");
|
||||
const weak = @import("weak.zig");
|
||||
|
||||
pub const WorldOptions = world_mod.Options;
|
||||
|
||||
@@ -72,10 +73,17 @@ pub const Value = union(enum) {
|
||||
graph: *Graph,
|
||||
/// `iref<T>`: graph identity and slot; opaque to programs.
|
||||
iref: struct { id: u64, slot: u32 },
|
||||
/// `atomic<T>`: index into the machine's atomic cells (spec 04 §42).
|
||||
atomic: u32,
|
||||
|
||||
/// The guarded value is a separate cell, so a place borrowed through a
|
||||
/// guard points at an ordinary cell.
|
||||
pub const MutexCell = struct { locked: bool, cell: *Cell };
|
||||
pub const MutexCell = struct {
|
||||
locked: bool,
|
||||
cell: *Cell,
|
||||
/// The view of the last unlock (spec 04 §20.3: unlock → next lock).
|
||||
view: weak.View = .{},
|
||||
};
|
||||
|
||||
/// A graph: object cells addressed by slot, an identity never reused in
|
||||
/// the execution, the authority it charges and the bytes it holds.
|
||||
@@ -197,6 +205,9 @@ pub const Options = struct {
|
||||
quantum: u64 = 1000,
|
||||
task_limit: u64 = 1024,
|
||||
schedule_seed: ?u64 = null,
|
||||
/// Exhaustive exploration: choices come from `Explore` instead of the
|
||||
/// schedule generator (spec 04 §20.5).
|
||||
explore: ?*Explore = null,
|
||||
};
|
||||
|
||||
/// Observable output of a run in the deterministic profile.
|
||||
@@ -262,6 +273,8 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
|
||||
|
||||
m.exec_heap.every_step = options.collect_every_step;
|
||||
m.arc_events = options.arc_events;
|
||||
m.explore = options.explore;
|
||||
m.mem.weak_reads = hasWeakReads(module);
|
||||
if (options.collect_threshold) |t| {
|
||||
m.exec_heap.floor = t;
|
||||
m.exec_heap.threshold = t;
|
||||
@@ -282,6 +295,31 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Operations whose order between tasks can change an outcome: atomic
|
||||
/// memory operations and the synchronization of channels, mutexes and
|
||||
/// cancellation. `task.spawn` and `task.join` commute with them.
|
||||
fn isVisibleOp(op: air.Op) bool {
|
||||
return switch (op) {
|
||||
.atomic_load, .atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => true,
|
||||
.channel_send, .channel_recv, .channel_close_sender, .channel_close_receiver, .select => true,
|
||||
.mutex_lock, .mutex_unlock => true,
|
||||
.task_cancel, .task_cancelled, .task_check_cancel, .task_join_cancel => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Whether a read may read an older message: a non-`seq_cst` load or
|
||||
/// compare-exchange failure (spec 04 §42). Without one, cells keep only their
|
||||
/// latest message.
|
||||
fn hasWeakReads(module: air.Module) bool {
|
||||
for (module.functions) |f| for (f.blocks) |b| for (b.insts) |inst| switch (inst.op) {
|
||||
.atomic_load => |x| if (x.ord != .seq_cst) return true,
|
||||
.atomic_cmpxchg => |x| if (x.failure != .seq_cst) return true,
|
||||
else => {},
|
||||
};
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Copies values into another heap, preserving sharing: a cell, a mutex or
|
||||
/// a payload reached twice is copied once.
|
||||
const Copier = struct {
|
||||
@@ -303,7 +341,7 @@ const Copier = struct {
|
||||
.mutex => |mc| .{ .mutex = try c.mutex(mc) },
|
||||
.guard => |mc| .{ .guard = try c.mutex(mc) },
|
||||
.graph => |g| .{ .graph = try c.graph(g) },
|
||||
.int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver, .iref => v,
|
||||
.int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver, .iref, .atomic => v,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -332,7 +370,7 @@ const Copier = struct {
|
||||
if (c.mutexes.get(old)) |n| return n;
|
||||
const n = try c.to.create(Value.MutexCell);
|
||||
try c.mutexes.put(c.tmp, old, n);
|
||||
n.* = .{ .locked = old.locked, .cell = try c.cell(old.cell) };
|
||||
n.* = .{ .locked = old.locked, .cell = try c.cell(old.cell), .view = try old.view.copy(c.to) };
|
||||
return n;
|
||||
}
|
||||
|
||||
@@ -403,13 +441,18 @@ pub const Wait = union(enum) {
|
||||
|
||||
/// A rendezvous offer: a task waiting to send or receive on a capacity-0
|
||||
/// channel, in arm `arm` of its instruction (0 outside `select`).
|
||||
const Offer = struct { task: u32, arm: u32, value: Value = .void };
|
||||
const Offer = struct { task: u32, arm: u32, value: Value = .void, view: weak.View = .{} };
|
||||
|
||||
/// A channel (spec 04 §38.3).
|
||||
const Channel = struct {
|
||||
capacity: u64,
|
||||
buf: std.ArrayList(Value) = .empty,
|
||||
/// The sender's view of each buffered value (spec 04 §20.3: send → the
|
||||
/// receive that obtains the value). Parallel to `buf`.
|
||||
views: std.ArrayList(weak.View) = .empty,
|
||||
head: usize = 0,
|
||||
/// Joined views of the senders' closes (close → the `closed` outcome).
|
||||
close_view: weak.View = .{},
|
||||
senders: u64 = 1,
|
||||
receiver: enum { open, closing, closed } = .open,
|
||||
authority: u32,
|
||||
@@ -445,7 +488,21 @@ const Task = struct {
|
||||
/// Shield depth (spec 04 §37.3).
|
||||
shield: u32 = 0,
|
||||
/// Set by a peer that completed a rendezvous against this waiting task.
|
||||
delivered: ?struct { arm: u32, value: Value } = null,
|
||||
delivered: ?struct { arm: u32, value: Value, view: weak.View = .{} } = null,
|
||||
/// Weak-memory views (spec 04 §42).
|
||||
views: weak.TaskViews = .{},
|
||||
/// Joined views of the cancellers (cancel → the `cancelled` outcome).
|
||||
cancel_view: weak.View = .{},
|
||||
/// Exploration: the scheduler already chose this task to perform the
|
||||
/// atomic operation it is at.
|
||||
chosen: bool = false,
|
||||
};
|
||||
|
||||
/// Exhaustive exploration (spec 04 §20.5): replays a prefix of choices,
|
||||
/// then takes choice 0, and records the number of options at every choice.
|
||||
pub const Explore = struct {
|
||||
prefix: []const u32 = &.{},
|
||||
widths: std.ArrayList(u32) = .empty,
|
||||
};
|
||||
|
||||
/// Execution heap: collected between instructions (see the file comment).
|
||||
@@ -490,6 +547,9 @@ const Machine = struct {
|
||||
drew: bool = false,
|
||||
/// Instructions executed so far.
|
||||
steps: u64 = 0,
|
||||
/// Atomic cells and the `seq_cst` view (spec 04 §42).
|
||||
mem: weak.Memory = .{},
|
||||
explore: ?*Explore = null,
|
||||
|
||||
// ------------------------------------------------------------ tasks and the scheduler (spec 04 §36)
|
||||
|
||||
@@ -511,6 +571,16 @@ const Machine = struct {
|
||||
const b = f.blocks[frame.block];
|
||||
const inst = b.insts[frame.inst];
|
||||
const here: Location = .{ .function = f.name, .block = b.name, .inst = frame.inst };
|
||||
// Exploration branches only before visible operations: what a
|
||||
// task does between two of them is local to it and commutes with
|
||||
// every other task (spec 04 §20.5). The task parks there; the
|
||||
// scheduler chooses once every runnable task is parked.
|
||||
if (m.explore != null and isVisibleOp(inst.op) and !t.chosen) {
|
||||
t.chosen = true;
|
||||
if (try m.schedule()) |o| return o;
|
||||
continue;
|
||||
}
|
||||
t.chosen = false;
|
||||
// Fuel is consumed when an instruction begins (spec 11 §7.1); a
|
||||
// blocked instruction paid when it first began (spec 04 §36.3).
|
||||
if (!t.fuel_paid) {
|
||||
@@ -588,20 +658,40 @@ const Machine = struct {
|
||||
for (m.tasks.items) |*t| {
|
||||
for (t.frames.items) |*fr| fr.vals = try c.items(fr.vals);
|
||||
t.result = try c.value(t.result);
|
||||
if (t.delivered) |*d| d.value = try c.value(d.value);
|
||||
if (t.delivered) |*d| {
|
||||
d.value = try c.value(d.value);
|
||||
d.view = try d.view.copy(c.to);
|
||||
}
|
||||
t.views = try t.views.copy(c.to);
|
||||
t.cancel_view = try t.cancel_view.copy(c.to);
|
||||
}
|
||||
for (m.channels.items) |*ch| {
|
||||
var buf: std.ArrayList(Value) = .empty;
|
||||
try buf.ensureTotalCapacity(c.to, ch.buf.items.len - ch.head);
|
||||
for (ch.buf.items[ch.head..]) |v| buf.appendAssumeCapacity(try c.value(v));
|
||||
var views: std.ArrayList(weak.View) = .empty;
|
||||
try views.ensureTotalCapacity(c.to, ch.views.items.len - ch.head);
|
||||
for (ch.views.items[ch.head..]) |v| views.appendAssumeCapacity(try v.copy(c.to));
|
||||
ch.buf = buf;
|
||||
ch.views = views;
|
||||
ch.head = 0;
|
||||
ch.close_view = try ch.close_view.copy(c.to);
|
||||
var offers: std.ArrayList(Offer) = .empty;
|
||||
try offers.ensureTotalCapacity(c.to, ch.send_offers.items.len);
|
||||
for (ch.send_offers.items) |o| offers.appendAssumeCapacity(.{ .task = o.task, .arm = o.arm, .value = try c.value(o.value) });
|
||||
for (ch.send_offers.items) |o| offers.appendAssumeCapacity(.{ .task = o.task, .arm = o.arm, .value = try c.value(o.value), .view = try o.view.copy(c.to) });
|
||||
ch.send_offers = offers;
|
||||
if (ch.recv_offer) |*o| o.value = try c.value(o.value);
|
||||
if (ch.recv_offer) |*o| {
|
||||
o.value = try c.value(o.value);
|
||||
o.view = try o.view.copy(c.to);
|
||||
}
|
||||
}
|
||||
// Atomic messages no live task can read any more are dropped.
|
||||
const floor = try tmp.allocator().alloc(u64, m.mem.cells.items.len);
|
||||
@memset(floor, std.math.maxInt(u64));
|
||||
for (m.tasks.items) |t| if (t.state != .done) for (floor, 0..) |*fl, i| {
|
||||
fl.* = @min(fl.*, t.views.cur.get(@intCast(i)));
|
||||
};
|
||||
try m.mem.compact(c.to, floor);
|
||||
var owners: std.AutoHashMapUnmanaged(*Value.Cell, OwnInfo) = .empty;
|
||||
try owners.ensureTotalCapacity(c.to, m.owners.count());
|
||||
var it = m.owners.iterator();
|
||||
@@ -660,10 +750,33 @@ const Machine = struct {
|
||||
m.current = runnable.items[0]; // no choice to make: no draw
|
||||
return null;
|
||||
}
|
||||
const x = m.sched.next();
|
||||
m.choices += 1;
|
||||
m.current = runnable.items[x % runnable.items.len];
|
||||
// Exploration: tasks with local work run first, without a choice.
|
||||
if (m.explore != null) for (runnable.items) |id| if (!m.tasks.items[id].chosen) {
|
||||
m.current = id;
|
||||
return null;
|
||||
};
|
||||
m.current = runnable.items[try m.choose(runnable.items.len)];
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Exhaustive exploration does not branch after `task.spawn` and a
|
||||
/// completed `task.join`: they commute with every operation of every
|
||||
/// other task, so branching there would only repeat outcomes. Ordinary
|
||||
/// runs keep them as scheduling points (spec 04 §36.1).
|
||||
fn yieldUnlessExploring(m: *Machine) Step {
|
||||
return if (m.explore != null) .next else .yield;
|
||||
}
|
||||
|
||||
/// One choice among `n > 1` options (spec 04 §36.2): a draw from the
|
||||
/// schedule generator, or the next choice of an exhaustive exploration.
|
||||
fn choose(m: *Machine, n: usize) !usize {
|
||||
m.choices += 1;
|
||||
if (m.explore) |e| {
|
||||
const i = e.widths.items.len;
|
||||
try e.widths.append(m.arena, @intCast(n));
|
||||
return if (i < e.prefix.len) e.prefix[i] else 0;
|
||||
}
|
||||
return m.sched.next() % n;
|
||||
}
|
||||
|
||||
const Step = union(enum) {
|
||||
@@ -769,25 +882,33 @@ const Machine = struct {
|
||||
m.live_tasks += 1;
|
||||
m.spawned = true;
|
||||
const id: u32 = @intCast(m.tasks.items.len);
|
||||
try m.tasks.append(m.arena, .{});
|
||||
// spawn → the child's first event (spec 04 §20.3).
|
||||
const parent = m.tasks.items[m.current].views.cur;
|
||||
try m.tasks.append(m.arena, .{ .views = .{ .cur = parent, .acq = parent } });
|
||||
try m.pushFrame(id, x.callee, try m.gather(vals, x.args));
|
||||
vals[inst.result.?] = .{ .task = id };
|
||||
return .yield;
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.task_join => |v| {
|
||||
const id = vals[v].task;
|
||||
const t = m.tasks.items[id];
|
||||
if (t.state != .done) return .{ .wait = .{ .join = id } };
|
||||
m.live_tasks -= 1;
|
||||
// The child's last event → join (spec 04 §20.3).
|
||||
try m.tasks.items[m.current].views.acquire(t.views.cur, m.heap());
|
||||
if (inst.result) |r| vals[r] = t.result;
|
||||
return .yield;
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.task_cancel => |v| {
|
||||
m.tasks.items[vals[v].task].cancel = true;
|
||||
const target = &m.tasks.items[vals[v].task];
|
||||
target.cancel = true;
|
||||
target.cancel_view = try target.cancel_view.join(m.tasks.items[m.current].views.cur, m.heap());
|
||||
return .yield;
|
||||
},
|
||||
.task_cancelled => {
|
||||
vals[inst.result.?] = .{ .boolean = m.tasks.items[m.current].cancel };
|
||||
const cancelled = m.tasks.items[m.current].cancel;
|
||||
if (cancelled) try m.observeCancel();
|
||||
vals[inst.result.?] = .{ .boolean = cancelled };
|
||||
return .yield;
|
||||
},
|
||||
.task_check_cancel, .task_join_cancel, .task_shield_begin, .task_shield_end => return m.execCancellation(f, vals, inst),
|
||||
@@ -795,6 +916,7 @@ const Machine = struct {
|
||||
.mutex_make, .mutex_take, .mutex_lock, .mutex_borrow, .mutex_unlock => return m.execMutex(f, vals, inst),
|
||||
.own_new, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst),
|
||||
.island_create, .island_alloc, .island_root, .island_borrow, .island_freeze, .island_destroy, .frozen_root, .frozen_borrow, .frozen_release, .arc_from_frozen, .arc_new, .arc_clone, .arc_release, .arc_root, .arc_borrow, .iref_eq => return m.execGraph(f, vals, inst),
|
||||
.atomic_new, .atomic_take, .atomic_load, .atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => return m.execAtomic(vals, inst),
|
||||
.intrinsic => |x| return m.intrinsic(f, vals, inst, x),
|
||||
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
|
||||
.trap => return .{ .trap = .explicit },
|
||||
@@ -869,33 +991,52 @@ const Machine = struct {
|
||||
}
|
||||
|
||||
/// Completes the peer of a rendezvous: it resumes on arm `arm`.
|
||||
fn deliver(m: *Machine, o: Offer, value: Value) void {
|
||||
fn deliver(m: *Machine, o: Offer, value: Value, view: weak.View) void {
|
||||
m.removeOffers(o.task);
|
||||
const t = &m.tasks.items[o.task];
|
||||
t.delivered = .{ .arm = o.arm, .value = value };
|
||||
t.delivered = .{ .arm = o.arm, .value = value, .view = view };
|
||||
if (t.state == .waiting) t.state = .runnable;
|
||||
}
|
||||
|
||||
/// Performs an `ok`-ready send.
|
||||
/// The sender's view travels with the value (spec 04 §20.3).
|
||||
fn doSend(m: *Machine, id: u32, v: Value) !void {
|
||||
const c = &m.channels.items[id];
|
||||
if (c.capacity > 0) return c.buf.append(m.heap(), try m.deepCopy(v));
|
||||
const view = m.tasks.items[m.current].views.cur;
|
||||
if (c.capacity > 0) {
|
||||
try c.views.append(m.heap(), view);
|
||||
return c.buf.append(m.heap(), try m.deepCopy(v));
|
||||
}
|
||||
const o = c.recv_offer.?;
|
||||
m.deliver(o, try m.deepCopy(v));
|
||||
m.deliver(o, try m.deepCopy(v), view);
|
||||
}
|
||||
|
||||
/// Performs an `ok`-ready receive.
|
||||
fn doRecv(m: *Machine, id: u32) Value {
|
||||
fn doRecv(m: *Machine, id: u32) !Value {
|
||||
const c = &m.channels.items[id];
|
||||
const views = &m.tasks.items[m.current].views;
|
||||
if (c.buffered() > 0) {
|
||||
c.head += 1;
|
||||
try views.acquire(c.views.items[c.head - 1], m.heap());
|
||||
return c.buf.items[c.head - 1];
|
||||
}
|
||||
const o = c.send_offers.orderedRemove(0);
|
||||
m.deliver(o, .void);
|
||||
m.deliver(o, .void, .{});
|
||||
try views.acquire(o.view, m.heap());
|
||||
return o.value;
|
||||
}
|
||||
|
||||
/// The `cancelled` outcome synchronizes with the cancels (spec 04 §20.3).
|
||||
fn observeCancel(m: *Machine) !void {
|
||||
const t = &m.tasks.items[m.current];
|
||||
try t.views.acquire(t.cancel_view, m.heap());
|
||||
}
|
||||
|
||||
/// The `closed` outcome of a receive synchronizes with the closes.
|
||||
fn observeClose(m: *Machine, id: u32) !void {
|
||||
try m.tasks.items[m.current].views.acquire(m.channels.items[id].close_view, m.heap());
|
||||
}
|
||||
|
||||
/// Returns the channel's bytes once it is `CLOSED` with no sender.
|
||||
fn maybeRelease(m: *Machine, id: u32) void {
|
||||
const c = &m.channels.items[id];
|
||||
@@ -911,15 +1052,21 @@ const Machine = struct {
|
||||
fn execCancellation(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step {
|
||||
const t = &m.tasks.items[m.current];
|
||||
switch (inst.op) {
|
||||
.task_check_cancel => |x| return .{ .jump_yield = if (cancelObservable(t)) x.cancelled else x.ok },
|
||||
.task_check_cancel => |x| {
|
||||
if (!cancelObservable(t)) return .{ .jump_yield = x.ok };
|
||||
try m.observeCancel();
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
},
|
||||
.task_join_cancel => |x| {
|
||||
const child = vals[x.task].task;
|
||||
if (m.tasks.items[child].state == .done) {
|
||||
m.live_tasks -= 1;
|
||||
try t.views.acquire(m.tasks.items[child].views.cur, m.heap());
|
||||
setParams(f, vals, x.ok, &.{m.tasks.items[child].result});
|
||||
return .{ .jump_yield = x.ok };
|
||||
}
|
||||
if (cancelObservable(t)) {
|
||||
try m.observeCancel();
|
||||
setParams(f, vals, x.cancelled, &.{vals[x.task]});
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
@@ -958,7 +1105,9 @@ const Machine = struct {
|
||||
},
|
||||
.channel_close_sender => |v| {
|
||||
const id = vals[v].sender;
|
||||
m.channels.items[id].senders -= 1;
|
||||
const ch = &m.channels.items[id];
|
||||
ch.close_view = try ch.close_view.join(m.tasks.items[self].views.cur, m.heap());
|
||||
ch.senders -= 1;
|
||||
m.maybeRelease(id);
|
||||
return .yield;
|
||||
},
|
||||
@@ -994,11 +1143,12 @@ const Machine = struct {
|
||||
},
|
||||
.none => {
|
||||
if (cancelObservable(t)) {
|
||||
try m.observeCancel();
|
||||
setParams(f, vals, x.cancelled, &.{v});
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
const c = &m.channels.items[id];
|
||||
if (c.capacity == 0) try c.send_offers.append(m.heap(), .{ .task = self, .arm = 0, .value = v });
|
||||
if (c.capacity == 0) try c.send_offers.append(m.heap(), .{ .task = self, .arm = 0, .value = v, .view = t.views.cur });
|
||||
return .{ .wait = .op };
|
||||
},
|
||||
}
|
||||
@@ -1007,6 +1157,7 @@ const Machine = struct {
|
||||
const t = &m.tasks.items[self];
|
||||
if (t.delivered) |d| {
|
||||
t.delivered = null;
|
||||
try t.views.acquire(d.view, m.heap());
|
||||
setParams(f, vals, x.ok, &.{d.value});
|
||||
return .{ .jump_yield = x.ok };
|
||||
}
|
||||
@@ -1014,12 +1165,18 @@ const Machine = struct {
|
||||
const id = endpointOf(vals[x.receiver]);
|
||||
switch (m.recvState(id)) {
|
||||
.ok => {
|
||||
setParams(f, vals, x.ok, &.{m.doRecv(id)});
|
||||
setParams(f, vals, x.ok, &.{try m.doRecv(id)});
|
||||
return .{ .jump_yield = x.ok };
|
||||
},
|
||||
.closed => return .{ .jump_yield = x.closed },
|
||||
.closed => {
|
||||
try m.observeClose(id);
|
||||
return .{ .jump_yield = x.closed };
|
||||
},
|
||||
.none => {
|
||||
if (cancelObservable(t)) return .{ .jump_yield = x.cancelled };
|
||||
if (cancelObservable(t)) {
|
||||
try m.observeCancel();
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
const c = &m.channels.items[id];
|
||||
if (c.capacity == 0) c.recv_offer = .{ .task = self, .arm = 0 };
|
||||
return .{ .wait = .op };
|
||||
@@ -1041,6 +1198,7 @@ const Machine = struct {
|
||||
for (vs, v_vals) |v, *o| o.* = vals[v];
|
||||
if (t.delivered) |d| {
|
||||
t.delivered = null;
|
||||
try t.views.acquire(d.view, m.heap());
|
||||
return m.selectOk(f, vals, x, d.arm, d.value, vs, v_vals);
|
||||
}
|
||||
m.removeOffers(self);
|
||||
@@ -1052,6 +1210,7 @@ const Machine = struct {
|
||||
}
|
||||
if (ready_arms.items.len == 0) {
|
||||
if (cancelObservable(t)) {
|
||||
try m.observeCancel();
|
||||
setParams(f, vals, x.cancelled, v_vals);
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
@@ -1059,21 +1218,21 @@ const Machine = struct {
|
||||
const c = &m.channels.items[endpointOf(vals[arm.endpoint])];
|
||||
if (c.capacity != 0) continue;
|
||||
if (arm.value) |v| {
|
||||
try c.send_offers.append(m.heap(), .{ .task = self, .arm = @intCast(i), .value = vals[v] });
|
||||
try c.send_offers.append(m.heap(), .{ .task = self, .arm = @intCast(i), .value = vals[v], .view = t.views.cur });
|
||||
} else c.recv_offer = .{ .task = self, .arm = @intCast(i) };
|
||||
}
|
||||
return .{ .wait = .op };
|
||||
}
|
||||
var pick: usize = 0;
|
||||
if (ready_arms.items.len > 1) {
|
||||
pick = m.sched.next() % ready_arms.items.len;
|
||||
m.choices += 1;
|
||||
pick = try m.choose(ready_arms.items.len);
|
||||
m.drew = true;
|
||||
}
|
||||
const arm_i, const st = ready_arms.items[pick];
|
||||
const arm = x.arms[arm_i];
|
||||
const ch = endpointOf(vals[arm.endpoint]);
|
||||
if (st == .closed) {
|
||||
if (arm.value == null) try m.observeClose(ch);
|
||||
setParams(f, vals, arm.closed, v_vals);
|
||||
return .{ .jump_yield = arm.closed };
|
||||
}
|
||||
@@ -1081,7 +1240,7 @@ const Machine = struct {
|
||||
try m.doSend(ch, vals[v]);
|
||||
return m.selectOk(f, vals, x, arm_i, .void, vs, v_vals);
|
||||
}
|
||||
return m.selectOk(f, vals, x, arm_i, m.doRecv(ch), vs, v_vals);
|
||||
return m.selectOk(f, vals, x, arm_i, try m.doRecv(ch), vs, v_vals);
|
||||
}
|
||||
|
||||
/// Continues at the `ok` target of arm `i`: the received value (for a
|
||||
@@ -1109,21 +1268,140 @@ const Machine = struct {
|
||||
const mc = mutexOf(vals[x.mutex]);
|
||||
if (!mc.locked) {
|
||||
mc.locked = true;
|
||||
// unlock → the next lock (spec 04 §20.3).
|
||||
try m.tasks.items[m.current].views.acquire(mc.view, m.heap());
|
||||
setParams(f, vals, x.ok, &.{.{ .guard = mc }});
|
||||
return .{ .jump_yield = x.ok };
|
||||
}
|
||||
if (cancelObservable(&m.tasks.items[m.current])) return .{ .jump_yield = x.cancelled };
|
||||
if (cancelObservable(&m.tasks.items[m.current])) {
|
||||
try m.observeCancel();
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
return .{ .wait = .op };
|
||||
},
|
||||
.mutex_borrow => |g| return bind(vals, inst.result, .{ .place = .{ .cell = vals[g].guard.cell, .path = &.{} } }),
|
||||
.mutex_unlock => |g| {
|
||||
vals[g].guard.locked = false;
|
||||
vals[g].guard.view = m.tasks.items[m.current].views.cur;
|
||||
return .yield;
|
||||
},
|
||||
else => unreachable,
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ atomics (spec 04 §20–§30, §42)
|
||||
|
||||
fn cellOf(v: Value) u32 {
|
||||
return switch (v) {
|
||||
.atomic => |id| id,
|
||||
.place => |p| cellOf(placePtr(p).*),
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
fn scalarBits(v: Value) u128 {
|
||||
return switch (v) {
|
||||
.int => |x| x.bits,
|
||||
.boolean => |b| @intFromBool(b),
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
fn scalarValue(ty: air.Type, bits: u128) Value {
|
||||
return switch (ty) {
|
||||
.int => |it| .{ .int = .{ .ty = it, .bits = bits } },
|
||||
.bool => .{ .boolean = bits != 0 },
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
/// A weak-memory choice among `n` readable messages (spec 04 §42).
|
||||
fn weakChoice(m: *Machine, n: u64) !u64 {
|
||||
if (n == 1) return 0;
|
||||
m.drew = true;
|
||||
return try m.choose(@intCast(n));
|
||||
}
|
||||
|
||||
fn execAtomic(m: *Machine, vals: []Value, inst: air.Inst) !Step {
|
||||
const gpa = m.heap();
|
||||
const views = &m.tasks.items[m.current].views;
|
||||
switch (inst.op) {
|
||||
.atomic_new => |v| {
|
||||
const ty: air.Type = switch (vals[v]) {
|
||||
.int => |x| .{ .int = x.ty },
|
||||
else => .bool,
|
||||
};
|
||||
return bind(vals, inst.result, .{ .atomic = try m.mem.create(gpa, m.arena, ty, scalarBits(vals[v])) });
|
||||
},
|
||||
.atomic_take => |v| {
|
||||
const c = &m.mem.cells.items[vals[v].atomic];
|
||||
const value = scalarValue(c.ty, c.at(c.latest()).bits);
|
||||
c.taken = true;
|
||||
return bind(vals, inst.result, value);
|
||||
},
|
||||
.atomic_load => |x| {
|
||||
const id = cellOf(vals[x.cell]);
|
||||
const first, const last = m.mem.readRange(views, id, x.ord);
|
||||
const ts = first + try m.weakChoice(last - first + 1);
|
||||
const bits = try m.mem.read(gpa, views, id, ts, x.ord);
|
||||
vals[inst.result.?] = scalarValue(m.mem.cells.items[id].ty, bits);
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.atomic_store => |x| {
|
||||
try m.mem.write(gpa, views, cellOf(vals[x.cell]), scalarBits(vals[x.value]), x.ord, .{});
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.atomic_rmw => |x| {
|
||||
const id = cellOf(vals[x.cell]);
|
||||
const ty = m.mem.cells.items[id].ty;
|
||||
const old, const carried = try m.mem.rmwRead(gpa, views, id, x.ord);
|
||||
const operand = scalarBits(vals[x.value]);
|
||||
const new: u128 = switch (x.op) {
|
||||
.xchg => operand,
|
||||
.add_wrap => arith(.add, .wrap, ty.int, old, operand) catch unreachable,
|
||||
.sub_wrap => arith(.sub, .wrap, ty.int, old, operand) catch unreachable,
|
||||
.@"and" => old & operand,
|
||||
.@"or" => old | operand,
|
||||
.xor => old ^ operand,
|
||||
};
|
||||
try m.mem.write(gpa, views, id, new, x.ord, carried);
|
||||
vals[inst.result.?] = scalarValue(ty, old);
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.atomic_cmpxchg => |x| {
|
||||
const id = cellOf(vals[x.cell]);
|
||||
const c = &m.mem.cells.items[id];
|
||||
const expected = scalarBits(vals[x.expected]);
|
||||
// Readable messages: the latest (a success when it equals
|
||||
// the expected value), and older ones that differ from it
|
||||
// (failures; a strong CAS cannot fail on an equal value).
|
||||
const first, const last = m.mem.readRange(views, id, x.failure);
|
||||
var options: std.ArrayList(u64) = .empty;
|
||||
var ts = first;
|
||||
while (ts < last) : (ts += 1) if (c.at(ts).bits != expected) try options.append(gpa, ts);
|
||||
try options.append(gpa, c.latest());
|
||||
const pick = options.items[@intCast(try m.weakChoice(options.items.len))];
|
||||
const ty = c.ty;
|
||||
if (pick == c.latest() and c.at(pick).bits == expected) {
|
||||
const old, const carried = try m.mem.rmwRead(gpa, views, id, x.success);
|
||||
try m.mem.write(gpa, views, id, scalarBits(vals[x.desired]), x.success, carried);
|
||||
vals[inst.result.?] = scalarValue(ty, old);
|
||||
vals[inst.result2.?] = .{ .boolean = true };
|
||||
} else {
|
||||
const bits = try m.mem.read(gpa, views, id, pick, x.failure);
|
||||
vals[inst.result.?] = scalarValue(ty, bits);
|
||||
vals[inst.result2.?] = .{ .boolean = false };
|
||||
}
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.atomic_fence => |o| {
|
||||
try m.mem.fence(gpa, views, o);
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
else => unreachable,
|
||||
}
|
||||
}
|
||||
|
||||
fn mutexOf(v: Value) *Value.MutexCell {
|
||||
return switch (v) {
|
||||
.mutex => |mc| mc,
|
||||
@@ -1857,7 +2135,7 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
|
||||
},
|
||||
// Storage and borrows cannot be returned from `@main` (spec 08 §11.3).
|
||||
.local, .place, .slice => try s.write(null),
|
||||
.resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref => try s.write(null),
|
||||
.resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref, .atomic => try s.write(null),
|
||||
// A capability is opaque: only its kind is shown, never its identity.
|
||||
.cap => {
|
||||
try s.beginObject();
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
//! The weak-memory machine of the deterministic interpreter (spec 04 §20,
|
||||
//! §42; RFC 0015 D10). Not normative: the normative model is the axioms of
|
||||
//! spec 04 §20. This machine must be sound for every program
|
||||
//! (`observed ⊆ allowed`) and exact on the litmus corpus
|
||||
//! (`observed_exhaustive = allowed`), which `tools/litmus` checks against the
|
||||
//! independent oracle.
|
||||
//!
|
||||
//! Design: a timestamped message machine without promises.
|
||||
//!
|
||||
//! - Every atomic cell keeps its writes in modification order. A message has
|
||||
//! the value written and the view a reader acquires from it.
|
||||
//! - Every task keeps three views (cell → timestamp): `cur` (it may not read
|
||||
//! below), `acq` (what an acquire fence would add) and `rel` (the view of
|
||||
//! its last release fence, carried by its relaxed writes).
|
||||
//! - A non-`seq_cst` read may read any message at or above `cur`; which one is
|
||||
//! a choice of the schedule stream. A `seq_cst` read and every RMW read the
|
||||
//! latest message.
|
||||
//! - Writes append, so modification order is execution order and no read
|
||||
//! reads a write that does not exist yet: `sb ∪ rf` stays acyclic
|
||||
//! (NO-THIN-AIR).
|
||||
//! - `seq_cst` accesses and fences synchronize through one global view `sc`.
|
||||
//!
|
||||
//! Without non-`seq_cst` accesses every read takes the latest message, so the
|
||||
//! machine is the interleaving machine and makes no extra choice.
|
||||
|
||||
const std = @import("std");
|
||||
const air = @import("../air.zig");
|
||||
|
||||
/// For each atomic cell observed, the oldest timestamp that may still be read.
|
||||
/// Immutable: operations return new views and share unchanged ones.
|
||||
pub const View = struct {
|
||||
/// Sorted by cell.
|
||||
entries: []const Entry = &.{},
|
||||
|
||||
pub const Entry = struct { cell: u32, ts: u64 };
|
||||
|
||||
pub fn get(v: View, cell: u32) u64 {
|
||||
for (v.entries) |e| {
|
||||
if (e.cell == cell) return e.ts;
|
||||
if (e.cell > cell) break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
fn below(a: View, b: View) bool {
|
||||
for (a.entries) |e| if (b.get(e.cell) < e.ts) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// The pointwise maximum.
|
||||
pub fn join(a: View, b: View, gpa: std.mem.Allocator) !View {
|
||||
if (below(b, a)) return a;
|
||||
if (below(a, b)) return b;
|
||||
var out: std.ArrayList(Entry) = .empty;
|
||||
var i: usize = 0;
|
||||
var j: usize = 0;
|
||||
while (i < a.entries.len or j < b.entries.len) {
|
||||
if (j == b.entries.len or (i < a.entries.len and a.entries[i].cell < b.entries[j].cell)) {
|
||||
try out.append(gpa, a.entries[i]);
|
||||
i += 1;
|
||||
} else if (i == a.entries.len or b.entries[j].cell < a.entries[i].cell) {
|
||||
try out.append(gpa, b.entries[j]);
|
||||
j += 1;
|
||||
} else {
|
||||
try out.append(gpa, .{ .cell = a.entries[i].cell, .ts = @max(a.entries[i].ts, b.entries[j].ts) });
|
||||
i += 1;
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
return .{ .entries = out.items };
|
||||
}
|
||||
|
||||
pub fn with(v: View, cell: u32, ts: u64, gpa: std.mem.Allocator) !View {
|
||||
if (v.get(cell) >= ts) return v;
|
||||
// The single entry must outlive this call: `join` may return it.
|
||||
const one = try gpa.alloc(Entry, 1);
|
||||
one[0] = .{ .cell = cell, .ts = ts };
|
||||
return v.join(.{ .entries = one }, gpa);
|
||||
}
|
||||
|
||||
pub fn copy(v: View, gpa: std.mem.Allocator) !View {
|
||||
if (v.entries.len == 0) return v;
|
||||
return .{ .entries = try gpa.dupe(Entry, v.entries) };
|
||||
}
|
||||
};
|
||||
|
||||
/// The views of one task.
|
||||
pub const TaskViews = struct {
|
||||
cur: View = .{},
|
||||
acq: View = .{},
|
||||
rel: View = .{},
|
||||
|
||||
/// Synchronizes with `v` (an `sw` edge into this task).
|
||||
pub fn acquire(t: *TaskViews, v: View, gpa: std.mem.Allocator) !void {
|
||||
t.cur = try t.cur.join(v, gpa);
|
||||
t.acq = try t.acq.join(v, gpa);
|
||||
}
|
||||
|
||||
pub fn copy(t: TaskViews, gpa: std.mem.Allocator) !TaskViews {
|
||||
return .{ .cur = try t.cur.copy(gpa), .acq = try t.acq.copy(gpa), .rel = try t.rel.copy(gpa) };
|
||||
}
|
||||
};
|
||||
|
||||
/// One write: the value (an AtomicScalar bit pattern) and the view a reader
|
||||
/// acquires from it.
|
||||
pub const Msg = struct { bits: u128, view: View };
|
||||
|
||||
/// An atomic cell: its writes in modification order. `msgs[i]` has timestamp
|
||||
/// `base + i`; older messages no task can read any more are dropped.
|
||||
pub const Cell = struct {
|
||||
ty: air.Type,
|
||||
msgs: std.ArrayList(Msg) = .empty,
|
||||
base: u64 = 0,
|
||||
taken: bool = false,
|
||||
|
||||
pub fn latest(c: *const Cell) u64 {
|
||||
return c.base + c.msgs.items.len - 1;
|
||||
}
|
||||
|
||||
pub fn at(c: *const Cell, ts: u64) Msg {
|
||||
return c.msgs.items[@intCast(ts - c.base)];
|
||||
}
|
||||
|
||||
/// The oldest timestamp a read by a task with view `cur` may read.
|
||||
pub fn oldest(c: *const Cell, id: u32, cur: View) u64 {
|
||||
return @max(c.base, cur.get(id));
|
||||
}
|
||||
};
|
||||
|
||||
/// The global state of the machine.
|
||||
pub const Memory = struct {
|
||||
cells: std.ArrayList(Cell) = .empty,
|
||||
/// The view of the `seq_cst` order.
|
||||
sc: View = .{},
|
||||
/// The program may read older messages (it has a non-`seq_cst` load or
|
||||
/// compare-exchange). Otherwise only the latest message is kept.
|
||||
weak_reads: bool = false,
|
||||
|
||||
pub fn create(mem: *Memory, gpa: std.mem.Allocator, arena: std.mem.Allocator, ty: air.Type, bits: u128) !u32 {
|
||||
try mem.cells.append(arena, .{ .ty = ty });
|
||||
const id: u32 = @intCast(mem.cells.items.len - 1);
|
||||
// The distinguished initialization write (spec 04 §20.1): first in
|
||||
// `mo`, starts no `sw`.
|
||||
try mem.cells.items[id].msgs.append(gpa, .{ .bits = bits, .view = .{} });
|
||||
return id;
|
||||
}
|
||||
|
||||
/// Before a `seq_cst` access or fence: synchronize with the SC view.
|
||||
fn scBefore(mem: *Memory, t: *TaskViews, gpa: std.mem.Allocator) !void {
|
||||
try t.acquire(mem.sc, gpa);
|
||||
}
|
||||
|
||||
fn scAfter(mem: *Memory, t: *TaskViews, gpa: std.mem.Allocator) !void {
|
||||
mem.sc = try mem.sc.join(t.cur, gpa);
|
||||
}
|
||||
|
||||
/// The timestamps a read with ordering `ord` may read: `[first, last]`.
|
||||
pub fn readRange(mem: *Memory, t: *const TaskViews, id: u32, ord: air.Ordering) struct { u64, u64 } {
|
||||
const c = &mem.cells.items[id];
|
||||
const last = c.latest();
|
||||
if (ord == .seq_cst) return .{ last, last };
|
||||
return .{ c.oldest(id, t.cur), last };
|
||||
}
|
||||
|
||||
/// Reads message `ts` (one of `readRange`) with ordering `ord`.
|
||||
pub fn read(mem: *Memory, gpa: std.mem.Allocator, t: *TaskViews, id: u32, ts: u64, ord: air.Ordering) !u128 {
|
||||
if (ord == .seq_cst) try mem.scBefore(t, gpa);
|
||||
const msg = mem.cells.items[id].at(ts);
|
||||
const seen = try msg.view.with(id, ts, gpa);
|
||||
if (ord.hasAcquire()) {
|
||||
t.cur = try t.cur.join(seen, gpa);
|
||||
} else {
|
||||
t.cur = try t.cur.with(id, ts, gpa);
|
||||
}
|
||||
t.acq = try t.acq.join(seen, gpa);
|
||||
if (ord == .seq_cst) try mem.scAfter(t, gpa);
|
||||
return msg.bits;
|
||||
}
|
||||
|
||||
/// Appends a write with ordering `ord`. `carried` is the view of the
|
||||
/// message an RMW read, which continues its release sequence.
|
||||
pub fn write(mem: *Memory, gpa: std.mem.Allocator, t: *TaskViews, id: u32, bits: u128, ord: air.Ordering, carried: View) !void {
|
||||
if (ord == .seq_cst) try mem.scBefore(t, gpa);
|
||||
const c = &mem.cells.items[id];
|
||||
const ts = c.latest() + 1;
|
||||
t.cur = try t.cur.with(id, ts, gpa);
|
||||
t.acq = try t.acq.with(id, ts, gpa);
|
||||
var view = if (ord.hasRelease()) t.cur else try t.rel.with(id, ts, gpa);
|
||||
view = try view.join(carried, gpa);
|
||||
if (mem.weak_reads) {
|
||||
try c.msgs.append(gpa, .{ .bits = bits, .view = view });
|
||||
} else {
|
||||
// No read can read an older message: keep only the latest.
|
||||
c.msgs.clearRetainingCapacity();
|
||||
c.msgs.appendAssumeCapacity(.{ .bits = bits, .view = view });
|
||||
c.base = ts;
|
||||
}
|
||||
if (ord == .seq_cst) try mem.scAfter(t, gpa);
|
||||
}
|
||||
|
||||
/// A read-modify-write: reads the latest message (atomicity), then writes
|
||||
/// `bits` computed from it. Returns the value read.
|
||||
pub fn rmwRead(mem: *Memory, gpa: std.mem.Allocator, t: *TaskViews, id: u32, ord: air.Ordering) !struct { u128, View } {
|
||||
const c = &mem.cells.items[id];
|
||||
const ts = c.latest();
|
||||
const msg = c.at(ts);
|
||||
// The read part: acquire as the ordering says; its write part
|
||||
// follows with `write`.
|
||||
if (ord == .seq_cst) try mem.scBefore(t, gpa);
|
||||
const seen = try msg.view.with(id, ts, gpa);
|
||||
if (ord.hasAcquire()) t.cur = try t.cur.join(seen, gpa) else t.cur = try t.cur.with(id, ts, gpa);
|
||||
t.acq = try t.acq.join(seen, gpa);
|
||||
return .{ msg.bits, msg.view };
|
||||
}
|
||||
|
||||
pub fn fence(mem: *Memory, gpa: std.mem.Allocator, t: *TaskViews, ord: air.Ordering) !void {
|
||||
if (ord.hasAcquire()) t.cur = try t.cur.join(t.acq, gpa);
|
||||
if (ord == .seq_cst) {
|
||||
try mem.scBefore(t, gpa);
|
||||
try mem.scAfter(t, gpa);
|
||||
}
|
||||
if (ord.hasRelease()) t.rel = t.cur;
|
||||
}
|
||||
|
||||
/// Drops messages below `floor[id]`, the oldest timestamp any live task
|
||||
/// may still read, and copies the rest into `gpa` (the collector).
|
||||
pub fn compact(mem: *Memory, gpa: std.mem.Allocator, floor: []const u64) !void {
|
||||
mem.sc = try mem.sc.copy(gpa);
|
||||
for (mem.cells.items, 0..) |*c, i| {
|
||||
var next: std.ArrayList(Msg) = .empty;
|
||||
if (c.taken) {
|
||||
c.msgs = next;
|
||||
continue;
|
||||
}
|
||||
const keep_from = @min(@max(c.base, floor[i]), c.latest());
|
||||
try next.ensureTotalCapacity(gpa, @intCast(c.latest() + 1 - keep_from));
|
||||
var ts = keep_from;
|
||||
while (ts <= c.latest()) : (ts += 1) {
|
||||
const m = c.at(ts);
|
||||
next.appendAssumeCapacity(.{ .bits = m.bits, .view = try m.view.copy(gpa) });
|
||||
}
|
||||
c.msgs = next;
|
||||
c.base = keep_from;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
test "views join pointwise and share when one contains the other" {
|
||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
const v1: View = .{ .entries = &.{ .{ .cell = 0, .ts = 2 }, .{ .cell = 2, .ts = 1 } } };
|
||||
const v2: View = .{ .entries = &.{ .{ .cell = 1, .ts = 3 }, .{ .cell = 2, .ts = 4 } } };
|
||||
const j = try v1.join(v2, a);
|
||||
try std.testing.expectEqual(@as(u64, 2), j.get(0));
|
||||
try std.testing.expectEqual(@as(u64, 3), j.get(1));
|
||||
try std.testing.expectEqual(@as(u64, 4), j.get(2));
|
||||
try std.testing.expectEqual(v1.entries.ptr, (try v1.join(.{}, a)).entries.ptr);
|
||||
}
|
||||
|
||||
test "message passing: an acquire read of a release write sees the earlier relaxed write" {
|
||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
var mem: Memory = .{ .weak_reads = true };
|
||||
const x = try mem.create(a, a, .{ .int = .u64 }, 0);
|
||||
const y = try mem.create(a, a, .{ .int = .u64 }, 0);
|
||||
var w: TaskViews = .{};
|
||||
var r: TaskViews = .{};
|
||||
try mem.write(a, &w, x, 1, .relaxed, .{});
|
||||
try mem.write(a, &w, y, 1, .release, .{});
|
||||
// Reading y=1 with acquire forbids x=0 afterwards.
|
||||
_ = try mem.read(a, &r, y, 1, .acquire);
|
||||
const first, const last = mem.readRange(&r, x, .relaxed);
|
||||
try std.testing.expectEqual(@as(u64, 1), first);
|
||||
try std.testing.expectEqual(@as(u64, 1), last);
|
||||
}
|
||||
|
||||
test "store buffering: relaxed reads may read the initial write" {
|
||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
var mem: Memory = .{ .weak_reads = true };
|
||||
const x = try mem.create(a, a, .{ .int = .u64 }, 0);
|
||||
const y = try mem.create(a, a, .{ .int = .u64 }, 0);
|
||||
var t0: TaskViews = .{};
|
||||
var t1: TaskViews = .{};
|
||||
try mem.write(a, &t0, x, 1, .relaxed, .{});
|
||||
try mem.write(a, &t1, y, 1, .relaxed, .{});
|
||||
try std.testing.expectEqual(@as(u64, 0), mem.readRange(&t0, y, .relaxed)[0]);
|
||||
try std.testing.expectEqual(@as(u64, 0), mem.readRange(&t1, x, .relaxed)[0]);
|
||||
// With seq_cst only the latest message is readable.
|
||||
try std.testing.expectEqual(@as(u64, 1), mem.readRange(&t0, y, .seq_cst)[0]);
|
||||
}
|
||||
@@ -33,6 +33,11 @@ const usage =
|
||||
\\ print the canonical AIR a source module lowers to;
|
||||
\\ --annotate adds source spans as comments (not canonical);
|
||||
\\ --stats prints source/AIR size and expansion ratio
|
||||
\\ explore [--max-runs N] [--grant P=KIND[:SCOPE]]... <file.air | file.aji>
|
||||
\\ run @main under every schedule and weak-memory choice
|
||||
\\ (depth first, up to N runs, default 100000) and print the
|
||||
\\ distinct outcomes; "complete" is true when the whole
|
||||
\\ choice tree was explored (spec 04 §20.5)
|
||||
\\ report <file.air> verify, then print the audit report (spec 10 §6.1)
|
||||
\\ codes list diagnostic codes as JSON Lines
|
||||
\\ features print supported AIR format, language version and features
|
||||
@@ -177,6 +182,7 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
try writeCode(out, c.*);
|
||||
return .accepted;
|
||||
}
|
||||
if (std.mem.eql(u8, cmd, "explore")) return explore(arena, io, args[2..], out);
|
||||
if (std.mem.eql(u8, cmd, "check") or std.mem.eql(u8, cmd, "run")) {
|
||||
var options: aji.interp.Options = .{};
|
||||
var grants: std.ArrayList(aji.interp.Grant) = .empty;
|
||||
@@ -319,6 +325,97 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
return usageError("unknown command");
|
||||
}
|
||||
|
||||
/// `aji explore`: exhaustive depth-first exploration of the choice tree
|
||||
/// (scheduler, `select` and weak-memory choices). Instructions other than
|
||||
/// scheduling points are not interleaved: the quantum is unbounded, so the
|
||||
/// tree branches only at synchronization and atomic operations.
|
||||
fn explore(arena: std.mem.Allocator, io: std.Io, argv: []const []const u8, out: *std.Io.Writer) !ExitCode {
|
||||
var max_runs: u64 = 100_000;
|
||||
var grants: std.ArrayList(aji.interp.Grant) = .empty;
|
||||
var rest = argv;
|
||||
while (rest.len >= 2) {
|
||||
if (std.mem.eql(u8, rest[0], "--max-runs")) {
|
||||
max_runs = std.fmt.parseInt(u64, rest[1], 10) catch return usageError("--max-runs takes a positive integer");
|
||||
} else if (std.mem.eql(u8, rest[0], "--grant")) {
|
||||
try grants.append(arena, parseGrant(rest[1]) orelse return usageError("--grant takes <parameter>=<kind>[:<scope>]"));
|
||||
} else break;
|
||||
rest = rest[2..];
|
||||
}
|
||||
if (rest.len != 1) return usageError("explore takes exactly one file");
|
||||
const path = rest[0];
|
||||
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
|
||||
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
|
||||
return .usage;
|
||||
};
|
||||
const report = try aji.check.checkFile(arena, path, source);
|
||||
for (report.diagnostics) |d| {
|
||||
try d.writeJson(out);
|
||||
try out.writeByte('\n');
|
||||
}
|
||||
if (report.status != .accepted) return .rejected;
|
||||
const module = report.module.?;
|
||||
|
||||
var counts: std.StringArrayHashMapUnmanaged(u64) = .empty;
|
||||
var prefix: std.ArrayList(u32) = .empty;
|
||||
var runs: u64 = 0;
|
||||
var complete = false;
|
||||
while (runs < max_runs) {
|
||||
var run_arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
|
||||
defer run_arena.deinit();
|
||||
var ex: aji.interp.Explore = .{ .prefix = prefix.items };
|
||||
const outcome = aji.interp.run(run_arena.allocator(), module, "main", .{
|
||||
.grants = grants.items,
|
||||
.quantum = std.math.maxInt(u64),
|
||||
.explore = &ex,
|
||||
}) catch |err| switch (err) {
|
||||
error.EntryNotFound => return usageError("module has no @main whose parameters are all capabilities"),
|
||||
error.DuplicateGrant => return usageError("a parameter is granted more than once"),
|
||||
else => |e| return e,
|
||||
};
|
||||
runs += 1;
|
||||
var rec: std.Io.Writer.Allocating = .init(run_arena.allocator());
|
||||
try aji.interp.writeOutcome(module, outcome, null, &rec.writer);
|
||||
const gop = try counts.getOrPut(arena, rec.written());
|
||||
if (!gop.found_existing) {
|
||||
gop.key_ptr.* = try arena.dupe(u8, rec.written());
|
||||
gop.value_ptr.* = 0;
|
||||
}
|
||||
gop.value_ptr.* += 1;
|
||||
// The next path: increment the deepest choice that has an untried
|
||||
// option, and drop everything after it.
|
||||
const widths = ex.widths.items;
|
||||
var i = widths.len;
|
||||
const next = while (i > 0) {
|
||||
i -= 1;
|
||||
const taken: u32 = if (i < prefix.items.len) prefix.items[i] else 0;
|
||||
if (taken + 1 < widths[i]) break i;
|
||||
} else null;
|
||||
const at = next orelse {
|
||||
complete = true;
|
||||
break;
|
||||
};
|
||||
var np: std.ArrayList(u32) = .empty;
|
||||
for (0..at) |k| try np.append(arena, if (k < prefix.items.len) prefix.items[k] else 0);
|
||||
try np.append(arena, (if (at < prefix.items.len) prefix.items[at] else 0) + 1);
|
||||
prefix = np;
|
||||
}
|
||||
const keys = counts.keys();
|
||||
const order = try arena.alloc(usize, keys.len);
|
||||
for (order, 0..) |*o, k| o.* = k;
|
||||
std.mem.sort(usize, order, keys, struct {
|
||||
fn lt(ks: []const []const u8, a: usize, b: usize) bool {
|
||||
return std.mem.lessThan(u8, ks[a], ks[b]);
|
||||
}
|
||||
}.lt);
|
||||
try out.print("{{\"runs\":{d},\"complete\":{},\"outcomes\":[", .{ runs, complete });
|
||||
for (order, 0..) |k, n| {
|
||||
if (n != 0) try out.writeByte(',');
|
||||
try out.print("{{\"outcome\":{s},\"count\":{d}}}", .{ keys[k], counts.values()[k] });
|
||||
}
|
||||
try out.writeAll("]}\n");
|
||||
return if (complete) .accepted else .limit_exceeded;
|
||||
}
|
||||
|
||||
/// The run record; for a `.aji` module a trap also carries its
|
||||
/// `source_location` (spec 15 §10).
|
||||
fn writeRecord(arena: std.mem.Allocator, module: aji.air.Module, outcome: aji.interp.Outcome, captured: ?aji.interp.Output, report: aji.check.Report, path: []const u8, out: *std.Io.Writer) !void {
|
||||
|
||||
+19
-1
@@ -24,6 +24,9 @@ const FnInfo = struct {
|
||||
checks: Checks = .{},
|
||||
proven_bounds: u32 = 0,
|
||||
unsafe_ops: std.ArrayList(struct { block: []const u8, inst: u32, op: []const u8 }) = .empty,
|
||||
/// Atomic memory operations (spec 04 §25): `weak` marks the sites that
|
||||
/// need `atomic.weak`, where interleaving reasoning is not enough.
|
||||
atomic_ops: std.ArrayList(struct { block: []const u8, inst: u32, op: []const u8, ordering: []const u8, weak: bool }) = .empty,
|
||||
/// Effects performed directly (intrinsics, allocation, unsafe operations).
|
||||
direct: std.ArrayList([]const u8) = .empty,
|
||||
/// Fixed point of `direct` over callees.
|
||||
@@ -90,6 +93,19 @@ fn analyze(arena: std.mem.Allocator, m: air.Module, f: air.Function) !FnInfo {
|
||||
if (x.unchecked) {} else if (x.proven) info.proven_bounds += 1 else info.checks.bounds += 1;
|
||||
},
|
||||
.slice_sub, .slice_split, .slice_copy => info.checks.bounds += 1,
|
||||
.atomic_load, .atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => {
|
||||
const op: []const u8, const ord: []const u8, const weak = switch (inst.op) {
|
||||
.atomic_load => |x| .{ "atomic.load", @tagName(x.ord), x.ord != .seq_cst },
|
||||
.atomic_store => |x| .{ "atomic.store", @tagName(x.ord), x.ord != .seq_cst },
|
||||
.atomic_rmw => |x| .{ try std.fmt.allocPrint(arena, "atomic.{s}", .{x.op.text()}), @tagName(x.ord), x.ord != .seq_cst },
|
||||
.atomic_cmpxchg => |x| .{ "atomic.cmpxchg", try std.fmt.allocPrint(arena, "{s}.{s}", .{ @tagName(x.success), @tagName(x.failure) }), x.success != .seq_cst or x.failure != .seq_cst },
|
||||
.atomic_fence => |o| .{ "atomic.fence", @tagName(o), false },
|
||||
else => unreachable,
|
||||
};
|
||||
try info.atomic_ops.append(arena, .{ .block = b.name, .inst = @intCast(ii), .op = op, .ordering = ord, .weak = weak });
|
||||
_ = try addOnce(arena, &info.direct, "atomic");
|
||||
if (weak) _ = try addOnce(arena, &info.direct, "atomic.weak");
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
if (unsafe_.unsafeOp(m, inst.op)) |what| {
|
||||
@@ -181,6 +197,8 @@ pub fn write(arena: std.mem.Allocator, m: air.Module, w: *Writer) !void {
|
||||
try s.write(.{ .bounds = i.proven_bounds });
|
||||
try s.objectField("unsafe_operations");
|
||||
try s.write(i.unsafe_ops.items);
|
||||
try s.objectField("atomic_operations");
|
||||
try s.write(i.atomic_ops.items);
|
||||
try s.endObject();
|
||||
}
|
||||
try s.endArray();
|
||||
@@ -248,6 +266,6 @@ test "audit report" {
|
||||
var out: Writer.Allocating = .init(arena);
|
||||
try write(arena, parsed.module.?, &out.writer);
|
||||
try std.testing.expectEqualStrings(
|
||||
\\{"report":"audit","air":0,"module":"demo","features":["arrays","capabilities","effects","ownership","resources","unsafe"],"entry":{"function":"main","capabilities":[{"parameter":"out","kind":"io.write"},{"parameter":"fs","kind":"fs.read"}]},"functions":[{"name":"main","trusted":null,"effects_declared":["fs.read","io.write"],"effects_used":[],"effects_unused":["fs.read","io.write"],"calls":["peek"],"intrinsics":[],"allocations":0,"runtime_checks":{"overflow":1,"division":0,"shift":0,"cast":0,"bounds":0,"assert":0,"guard":0},"proven_checks":{"bounds":0},"unsafe_operations":[]},{"name":"peek","trusted":"only reads","effects_declared":[],"effects_used":["unsafe"],"effects_unused":[],"calls":[],"intrinsics":[],"allocations":0,"runtime_checks":{"overflow":0,"division":0,"shift":0,"cast":0,"bounds":0,"assert":0,"guard":0},"proven_checks":{"bounds":0},"unsafe_operations":[{"block":"entry","inst":1,"op":"assume"}]}],"capability_kinds":["fs.read","io.write"],"unsafe":{"trusted_functions":["peek"],"unsafe_functions":[],"operations":1}}
|
||||
\\{"report":"audit","air":0,"module":"demo","features":["arrays","capabilities","effects","ownership","resources","unsafe"],"entry":{"function":"main","capabilities":[{"parameter":"out","kind":"io.write"},{"parameter":"fs","kind":"fs.read"}]},"functions":[{"name":"main","trusted":null,"effects_declared":["fs.read","io.write"],"effects_used":[],"effects_unused":["fs.read","io.write"],"calls":["peek"],"intrinsics":[],"allocations":0,"runtime_checks":{"overflow":1,"division":0,"shift":0,"cast":0,"bounds":0,"assert":0,"guard":0},"proven_checks":{"bounds":0},"unsafe_operations":[],"atomic_operations":[]},{"name":"peek","trusted":"only reads","effects_declared":[],"effects_used":["unsafe"],"effects_unused":[],"calls":[],"intrinsics":[],"allocations":0,"runtime_checks":{"overflow":0,"division":0,"shift":0,"cast":0,"bounds":0,"assert":0,"guard":0},"proven_checks":{"bounds":0},"unsafe_operations":[{"block":"entry","inst":1,"op":"assume"}],"atomic_operations":[]}],"capability_kinds":["fs.read","io.write"],"unsafe":{"trusted_functions":["peek"],"unsafe_functions":[],"operations":1}}
|
||||
, out.written());
|
||||
}
|
||||
@@ -559,6 +559,7 @@ fn step(w: *Walker, inst: air.Inst) !void {
|
||||
w.live[inst.result.?] = true;
|
||||
},
|
||||
.mutex_take => |m| {
|
||||
if (try takeLent(w, m)) return;
|
||||
try w.consume(m, .closed);
|
||||
if (w.isResource(inst.result.?)) w.live[inst.result.?] = true;
|
||||
},
|
||||
@@ -599,6 +600,14 @@ fn step(w: *Walker, inst: air.Inst) !void {
|
||||
try lendArgs(w, &.{v});
|
||||
w.live[inst.result.?] = true;
|
||||
},
|
||||
// Atomics (spec 04 §23, §28): a cell is a linear value; operations go
|
||||
// through a shared borrow of it (interior mutability), `take` consumes
|
||||
// it and needs every borrow ended.
|
||||
.atomic_new => w.live[inst.result.?] = true,
|
||||
.atomic_take => |v| if (!try takeLent(w, v)) try w.consume(v, .closed),
|
||||
.atomic_load => |x| try w.useThrough(x.cell, .shared),
|
||||
inline .atomic_store, .atomic_rmw => |x| try w.useThrough(x.cell, .shared),
|
||||
.atomic_cmpxchg => |x| try w.useThrough(x.cell, .shared),
|
||||
// Values of these instructions are not borrows; any borrow operand
|
||||
// here was already rejected by the type stage.
|
||||
else => {},
|
||||
@@ -606,6 +615,19 @@ fn step(w: *Walker, inst: air.Inst) !void {
|
||||
_ = f;
|
||||
}
|
||||
|
||||
/// Taking a mutex or an atomic cell while a borrow of it is lent to a live
|
||||
/// task races with that task: `E4101` rather than `E2101` (spec 04 §28, §40).
|
||||
fn takeLent(w: *Walker, v: ValueId) !bool {
|
||||
for (w.loans.items) |l| if (w.live[l.task] and l.root == v) {
|
||||
try w.report("E4101", "taken while a borrow of it is lent to a live task", v, .{ "task", l.task });
|
||||
// Consumed all the same, so the mistake is not reported again as a leak.
|
||||
w.live[v] = false;
|
||||
w.dead[v] = .closed;
|
||||
return true;
|
||||
};
|
||||
return false;
|
||||
}
|
||||
|
||||
/// The critical-section rule (spec 04 §41): no operation that may wait or
|
||||
/// spawn while a lock guard is live.
|
||||
fn noWaitUnderLock(w: *Walker, op: []const u8) !void {
|
||||
|
||||
@@ -30,6 +30,7 @@ pub fn accountedSize(m: air.Module, t: air.Type, depth: usize) ?u64 {
|
||||
.bool => 1,
|
||||
.ref, .mut, .cap, .resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .guard, .island, .frozen, .arc => 8,
|
||||
.iref => 16,
|
||||
.atomic => |inner| accountedSize(m, inner.*, depth + 1),
|
||||
.mutex => |inner| std.math.add(u64, 8, accountedSize(m, inner.*, depth + 1) orelse return null) catch null,
|
||||
.own_array => 16,
|
||||
.slice, .slice_mut => 16,
|
||||
|
||||
@@ -50,6 +50,13 @@ pub fn check(c: *Context) !void {
|
||||
.task_join => if (m.declares("cancellation")) try need(c, f, inst, "task.wait"),
|
||||
.task_join_cancel, .channel_send, .channel_recv, .select, .mutex_lock => try need(c, f, inst, "task.wait"),
|
||||
.channel_make => try need(c, f, inst, "mem.alloc"),
|
||||
// Atomics (spec 04 §25, spec 05 §13): every memory operation needs
|
||||
// `atomic`; a non-`seq_cst` access also needs `atomic.weak`.
|
||||
.atomic_fence => try need(c, f, inst, "atomic"),
|
||||
.atomic_load => |x| try needAtomic(c, f, inst, x.ord != .seq_cst),
|
||||
.atomic_store => |x| try needAtomic(c, f, inst, x.ord != .seq_cst),
|
||||
.atomic_rmw => |x| try needAtomic(c, f, inst, x.ord != .seq_cst),
|
||||
.atomic_cmpxchg => |x| try needAtomic(c, f, inst, x.success != .seq_cst or x.failure != .seq_cst),
|
||||
.own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => if (!contains(f.effects, "mem.alloc")) {
|
||||
try c.report("E3101", inst.span, "allocation requires the effect mem.alloc", &.{
|
||||
.{ .name = "function", .value = .{ .str = f.name } },
|
||||
@@ -68,6 +75,11 @@ pub fn check(c: *Context) !void {
|
||||
}
|
||||
}
|
||||
|
||||
fn needAtomic(c: *Context, f: air.Function, inst: air.Inst, weak: bool) !void {
|
||||
try need(c, f, inst, "atomic");
|
||||
if (weak) try need(c, f, inst, "atomic.weak");
|
||||
}
|
||||
|
||||
/// Adds `suggested_effects` to every E3101 reported for `f` since diagnostic
|
||||
/// `first`: the complete, sorted effect list the function needs (its declared
|
||||
/// effects plus every missing one). Effects stay declared by the programmer;
|
||||
|
||||
+97
-5
@@ -85,9 +85,14 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons
|
||||
.void, .never => pos == .ret,
|
||||
.local => false,
|
||||
.ref, .mut, .slice, .slice_mut => pos != .member and pos != .borrowed,
|
||||
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc => pos != .member,
|
||||
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => pos != .member,
|
||||
else => true,
|
||||
};
|
||||
// An atomic cell holds an AtomicScalar (spec 04 §23).
|
||||
if (t == .atomic and !isAtomicScalar(t.atomic.*)) try c.report("E1001", span, "atomic<T> needs bool or an integer of at most 64 bits", &.{
|
||||
.{ .name = "in", .value = .{ .str = owner } },
|
||||
.{ .name = "found", .value = .{ .str = try c.typeName(t.atomic.*) } },
|
||||
});
|
||||
if (!ok) try c.report("E1001", span, "type not allowed in this position", &.{
|
||||
.{ .name = "in", .value = .{ .str = owner } },
|
||||
.{ .name = "position", .value = .{ .str = @tagName(pos) } },
|
||||
@@ -339,6 +344,8 @@ pub fn isSend(m: air.Module, t: Type) bool {
|
||||
.int, .bool, .builtin, .cap, .resource, .region, .sender, .receiver => true,
|
||||
// Graph contents are IslandSafe plain data (spec 03 §22–§24).
|
||||
.island, .frozen, .arc, .iref => true,
|
||||
// Every access to a cell is an atomic operation (spec 04 §23).
|
||||
.atomic => true,
|
||||
.own, .own_array, .mutex => |inner| isSend(m, inner.*),
|
||||
.ref, .slice => |inner| isShare(m, inner.*),
|
||||
.mut, .slice_mut => |inner| isSend(m, inner.*),
|
||||
@@ -352,7 +359,7 @@ pub fn isSend(m: air.Module, t: Type) bool {
|
||||
pub fn isShare(m: air.Module, t: Type) bool {
|
||||
return switch (t) {
|
||||
.int, .bool, .builtin, .cap => true,
|
||||
.frozen, .arc, .iref => true,
|
||||
.frozen, .arc, .iref, .atomic => true,
|
||||
// Its owner may mutate it: freeze to share (spec 04 §35).
|
||||
.island => false,
|
||||
.resource, .region, .mut, .slice_mut, .scope, .task, .shield, .guard, .sender, .receiver, .local, .void, .never => false,
|
||||
@@ -364,6 +371,43 @@ pub fn isShare(m: air.Module, t: Type) bool {
|
||||
};
|
||||
}
|
||||
|
||||
/// A borrow whose pointee is an atomic cell: reached only atomically.
|
||||
fn atomicPointee(t: Type) bool {
|
||||
return (t == .ref or t == .mut) and t.inner().? == .atomic;
|
||||
}
|
||||
|
||||
/// `E4202`: an ordinary load or store of an atomic cell (spec 04 §28).
|
||||
fn ordinaryAtomicAccess(fc: *FnCtx, span: air.Span, v: air.ValueId, use: []const u8) !void {
|
||||
try fc.c.report("E4202", span, "an atomic cell is read and written only by atomic operations", &.{
|
||||
.{ .name = "function", .value = .{ .str = fc.f.name } },
|
||||
.{ .name = "operand", .value = .{ .str = try fc.c.valueName(fc.f, v) } },
|
||||
.{ .name = "found", .value = .{ .str = try fc.c.typeName(fc.typeOf(v)) } },
|
||||
.{ .name = "use", .value = .{ .str = use } },
|
||||
});
|
||||
}
|
||||
|
||||
/// `E4201`: an ordering outside the operation's row (spec 04 §24).
|
||||
fn checkOrdering(fc: *FnCtx, span: air.Span, operation: []const u8, ord: air.Ordering, allowed: []const air.Ordering) !void {
|
||||
if (std.mem.indexOfScalar(air.Ordering, allowed, ord) != null) return;
|
||||
var text: std.Io.Writer.Allocating = .init(fc.c.arena);
|
||||
for (allowed, 0..) |o, i| text.writer.print("{s}{s}", .{ if (i == 0) "" else ", ", @tagName(o) }) catch return error.OutOfMemory;
|
||||
try fc.c.report("E4201", span, "memory ordering not valid for this atomic operation", &.{
|
||||
.{ .name = "function", .value = .{ .str = fc.f.name } },
|
||||
.{ .name = "operation", .value = .{ .str = operation } },
|
||||
.{ .name = "ordering", .value = .{ .str = @tagName(ord) } },
|
||||
.{ .name = "allowed", .value = .{ .str = text.written() } },
|
||||
});
|
||||
}
|
||||
|
||||
/// AtomicScalar (spec 04 §23): `bool` and integers of at most 64 bits.
|
||||
pub fn isAtomicScalar(t: Type) bool {
|
||||
return switch (t) {
|
||||
.bool => true,
|
||||
.int => |it| it.bits() <= 64,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// `IslandSafe` (spec 02 §6): plain data and `iref` handles, at any depth.
|
||||
/// `ArcSafe` is the same set in format 0.
|
||||
pub fn isIslandSafe(m: air.Module, t: Type) bool {
|
||||
@@ -527,6 +571,11 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
|
||||
.slice_split => |x| fc.ty[x.slice] orelse return null,
|
||||
.island_root, .frozen_root, .arc_root, .island_freeze, .arc_from_frozen, .arc_clone => |v| fc.ty[v] orelse return null,
|
||||
inline .island_borrow, .frozen_borrow, .arc_borrow => |x| fc.ty[x.owner] orelse return null,
|
||||
.atomic_new => |v| return .{ .atomic = try boxed(a, fc.ty[v] orelse return null) },
|
||||
.atomic_take => |v| fc.ty[v] orelse return null,
|
||||
.atomic_load => |x| fc.ty[x.cell] orelse return null,
|
||||
.atomic_rmw => |x| fc.ty[x.cell] orelse return null,
|
||||
.atomic_cmpxchg => |x| fc.ty[x.cell] orelse return null,
|
||||
else => return null,
|
||||
};
|
||||
const invalid: Type = .void;
|
||||
@@ -534,7 +583,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
|
||||
.local_load => if (t == .local) t.local.* else invalid,
|
||||
.borrow_ref => switch (t) {
|
||||
.local, .ref, .mut => .{ .ref = try boxed(a, t.inner().?) },
|
||||
.resource, .region, .task, .scope, .sender, .receiver, .mutex, .island, .frozen, .arc => .{ .ref = try boxed(a, t) },
|
||||
.resource, .region, .task, .scope, .sender, .receiver, .mutex, .island, .frozen, .arc, .atomic => .{ .ref = try boxed(a, t) },
|
||||
.own => |inner| .{ .ref = inner },
|
||||
.own_array => |inner| .{ .slice = inner },
|
||||
.slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) },
|
||||
@@ -598,6 +647,9 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
|
||||
if (owner == .island and t == .mut and t.mut.* == .island) break :blk Type{ .mut = target };
|
||||
break :blk invalid;
|
||||
},
|
||||
.atomic_take => if (t == .atomic) t.atomic.* else invalid,
|
||||
// Every atomic operation takes `ref<atomic<T>>` (spec 04 §23).
|
||||
.atomic_load, .atomic_rmw, .atomic_cmpxchg => if (t == .ref and t.ref.* == .atomic) t.ref.atomic.* else invalid,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
@@ -638,7 +690,7 @@ fn checkFunction(c: *Context, f: air.Function) ![]const Type {
|
||||
if (fc.ty[r] != null) continue;
|
||||
if (try derivedType(&fc, inst.op)) |t| {
|
||||
fc.ty[r] = t;
|
||||
if (inst.result2) |r2| fc.ty[r2] = t;
|
||||
if (inst.result2) |r2| fc.ty[r2] = if (inst.op == .atomic_cmpxchg) .bool else t;
|
||||
progress = true;
|
||||
}
|
||||
};
|
||||
@@ -690,9 +742,13 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
|
||||
.borrow_mut => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, a resource, mut<T> or slice_mut<T>"),
|
||||
.borrow_field => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.borrow, "ref or mut of the named struct"),
|
||||
.borrow_end => |v| if (!fc.typeOf(v).isBorrow()) try fc.kindError(span, v, "a borrow"),
|
||||
.load => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<T> or mut<T>"),
|
||||
.load => |v| {
|
||||
if (atomicPointee(fc.typeOf(v))) return ordinaryAtomicAccess(fc, span, v, "atomic.load");
|
||||
if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<T> or mut<T>");
|
||||
},
|
||||
.store => |x| {
|
||||
const t = fc.typeOf(x.borrow);
|
||||
if (atomicPointee(t)) return ordinaryAtomicAccess(fc, span, x.borrow, "atomic.store");
|
||||
if (t != .mut) return fc.kindError(span, x.borrow, "mut<T>");
|
||||
try fc.expectValue(span, x.value, t.mut.*);
|
||||
},
|
||||
@@ -912,6 +968,42 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
|
||||
if (a != .iref) return fc.kindError(span, x.a, "iref<T>");
|
||||
try fc.expectValue(span, x.b, a);
|
||||
},
|
||||
// Atomics (spec 04 §23–§25, §42).
|
||||
.atomic_new => |v| if (!isAtomicScalar(fc.typeOf(v))) try fc.kindError(span, v, "bool or an integer of at most 64 bits"),
|
||||
.atomic_take => |v| if (fc.typeOf(v) != .atomic) try fc.kindError(span, v, "atomic<T>"),
|
||||
.atomic_load => |x| {
|
||||
if (resultOf(fc, inst) == .void) return fc.kindError(span, x.cell, "ref<atomic<T>>");
|
||||
try checkOrdering(fc, span, "atomic.load", x.ord, &.{ .relaxed, .acquire, .seq_cst });
|
||||
},
|
||||
.atomic_store => |x| {
|
||||
const t = fc.typeOf(x.cell);
|
||||
if (t != .ref or t.ref.* != .atomic) return fc.kindError(span, x.cell, "ref<atomic<T>>");
|
||||
try fc.expectValue(span, x.value, t.ref.atomic.*);
|
||||
try checkOrdering(fc, span, "atomic.store", x.ord, &.{ .relaxed, .release, .seq_cst });
|
||||
},
|
||||
.atomic_rmw => |x| {
|
||||
const r = resultOf(fc, inst);
|
||||
if (r == .void) return fc.kindError(span, x.cell, "ref<atomic<T>>");
|
||||
if (r == .bool and (x.op == .add_wrap or x.op == .sub_wrap)) return fc.kindError(span, x.cell, "ref<atomic<T>> with an integer T");
|
||||
try fc.expectValue(span, x.value, r);
|
||||
try checkOrdering(fc, span, try std.fmt.allocPrint(fc.c.arena, "atomic.{s}", .{x.op.text()}), x.ord, &.{ .relaxed, .acquire, .release, .acq_rel, .seq_cst });
|
||||
},
|
||||
.atomic_cmpxchg => |x| {
|
||||
const r = resultOf(fc, inst);
|
||||
if (r == .void) return fc.kindError(span, x.cell, "ref<atomic<T>>");
|
||||
try fc.expectValue(span, x.expected, r);
|
||||
try fc.expectValue(span, x.desired, r);
|
||||
try checkOrdering(fc, span, "atomic.cmpxchg", x.success, &.{ .relaxed, .acquire, .release, .acq_rel, .seq_cst });
|
||||
// A failed compare-exchange is a read, never stronger than the
|
||||
// success ordering (spec 04 §24.1).
|
||||
const failure: []const air.Ordering = switch (x.success) {
|
||||
.relaxed, .release => &.{.relaxed},
|
||||
.acquire, .acq_rel => &.{ .relaxed, .acquire },
|
||||
.seq_cst => &.{ .relaxed, .acquire, .seq_cst },
|
||||
};
|
||||
try checkOrdering(fc, span, "atomic.cmpxchg failure", x.failure, failure);
|
||||
},
|
||||
.atomic_fence => |o| try checkOrdering(fc, span, "atomic.fence", o, &.{ .acquire, .release, .acq_rel, .seq_cst }),
|
||||
.cap_narrow => |x| {
|
||||
const t = fc.typeOf(x.cap);
|
||||
if (t != .cap) return fc.kindError(span, x.cap, "cap<K>");
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
; add.wrap is defined for integers only (spec 04 §24.2).
|
||||
; expect: reject E1001
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.add_bool
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @main() -> bool
|
||||
effects [atomic]
|
||||
entry:
|
||||
%t = const.bool true
|
||||
%c = atomic.new %t
|
||||
%r = borrow.ref %c
|
||||
%x = atomic.add.wrap.seq_cst %r, %t
|
||||
borrow.end %r
|
||||
%v = atomic.take %c
|
||||
ret %v
|
||||
@@ -0,0 +1,21 @@
|
||||
; A failed compare-exchange is a read: no release part (spec 04 §24.1).
|
||||
; expect: reject E4201
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.cmpxchg_failure_release
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @main() -> u64
|
||||
effects [atomic, atomic.weak]
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%c = atomic.new %z
|
||||
%r = borrow.ref %c
|
||||
%one = const.u64 1
|
||||
%o, %ok = atomic.cmpxchg.acq_rel.acq_rel %r, %z, %one
|
||||
borrow.end %r
|
||||
%v = atomic.take %c
|
||||
%k = const.u64 0
|
||||
ret %k
|
||||
@@ -0,0 +1,21 @@
|
||||
; A compare-exchange failure ordering is never stronger than its success ordering (spec 04 §24.1).
|
||||
; expect: reject E4201
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.cmpxchg_failure_stronger
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @main() -> u64
|
||||
effects [atomic, atomic.weak]
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%c = atomic.new %z
|
||||
%r = borrow.ref %c
|
||||
%one = const.u64 1
|
||||
%o, %ok = atomic.cmpxchg.relaxed.acquire %r, %z, %one
|
||||
borrow.end %r
|
||||
%v = atomic.take %c
|
||||
%k = const.u64 0
|
||||
ret %k
|
||||
@@ -0,0 +1,20 @@
|
||||
; There is no relaxed fence (spec 04 §27).
|
||||
; expect: reject E4201
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.fence_relaxed
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @main() -> u64
|
||||
effects [atomic, atomic.weak]
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%c = atomic.new %z
|
||||
%r = borrow.ref %c
|
||||
atomic.fence.relaxed
|
||||
borrow.end %r
|
||||
%v = atomic.take %c
|
||||
%k = const.u64 0
|
||||
ret %k
|
||||
@@ -0,0 +1,20 @@
|
||||
; An atomic cell is not IslandSafe: a frozen graph is deeply immutable (spec 02 §6).
|
||||
; expect: reject E2111
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.island_content
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, capabilities, effects, heap, islands, ownership, resources]
|
||||
|
||||
fn @main(%heap: cap<mem.alloc>) -> u64
|
||||
effects [mem.alloc]
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%c = atomic.new %z
|
||||
island.create %c, %heap, ok -> @made, err -> @oom
|
||||
made(%i: island<atomic<u64>>):
|
||||
island.destroy %i
|
||||
ret %z
|
||||
oom(%e: alloc_error):
|
||||
trap
|
||||
@@ -0,0 +1,15 @@
|
||||
; An atomic cell is linear: it is taken, moved or returned (spec 04 §23).
|
||||
; expect: reject E3002
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.leak
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @main() -> u64
|
||||
effects []
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%c = atomic.new %z
|
||||
ret %z
|
||||
@@ -0,0 +1,20 @@
|
||||
; A load cannot be release (spec 04 §24).
|
||||
; expect: reject E4201
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.load_release
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @main() -> u64
|
||||
effects [atomic, atomic.weak]
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%c = atomic.new %z
|
||||
%r = borrow.ref %c
|
||||
%x = atomic.load.release %r
|
||||
borrow.end %r
|
||||
%v = atomic.take %c
|
||||
%k = const.u64 0
|
||||
ret %k
|
||||
@@ -0,0 +1,20 @@
|
||||
; Every atomic memory operation needs the effect atomic (spec 04 §25).
|
||||
; expect: reject E3101
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.missing_atomic_effect
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @main() -> u64
|
||||
effects []
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%c = atomic.new %z
|
||||
%r = borrow.ref %c
|
||||
%x = atomic.load.seq_cst %r
|
||||
borrow.end %r
|
||||
%v = atomic.take %c
|
||||
%k = const.u64 0
|
||||
ret %k
|
||||
@@ -0,0 +1,20 @@
|
||||
; A non-seq_cst access needs atomic.weak besides atomic (spec 04 §25).
|
||||
; expect: reject E3101
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.missing_weak_effect
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @main() -> u64
|
||||
effects [atomic]
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%c = atomic.new %z
|
||||
%r = borrow.ref %c
|
||||
%x = atomic.load.acquire %r
|
||||
borrow.end %r
|
||||
%v = atomic.take %c
|
||||
%k = const.u64 0
|
||||
ret %k
|
||||
@@ -0,0 +1,21 @@
|
||||
; Atomic operations take ref<atomic<T>>, never mut (spec 04 §23).
|
||||
; expect: reject E1001
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.mut_operand
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @peek(%c: mut<atomic<u64>>) -> u64
|
||||
effects [atomic]
|
||||
entry:
|
||||
%x = atomic.load.seq_cst %c
|
||||
%k = const.u64 0
|
||||
ret %k
|
||||
|
||||
fn @main() -> u64
|
||||
effects []
|
||||
entry:
|
||||
%k = const.u64 0
|
||||
ret %k
|
||||
@@ -0,0 +1,20 @@
|
||||
; atomic<T> needs the feature atomics in the header (spec 07 §8.1).
|
||||
; expect: reject E0006
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.not_declared
|
||||
air 0
|
||||
lang 0.1
|
||||
features [effects, ownership]
|
||||
|
||||
fn @peek(%c: ref<atomic<u64>>) -> u64
|
||||
effects []
|
||||
entry:
|
||||
%k = const.u64 0
|
||||
ret %k
|
||||
|
||||
fn @main() -> u64
|
||||
effects []
|
||||
entry:
|
||||
%k = const.u64 0
|
||||
ret %k
|
||||
@@ -0,0 +1,20 @@
|
||||
; An atomic cell is read only by atomic operations (spec 04 §28).
|
||||
; expect: reject E4202
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.ordinary_load
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @main() -> u64
|
||||
effects [atomic, atomic.weak]
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%c = atomic.new %z
|
||||
%r = borrow.ref %c
|
||||
%x = load %r
|
||||
borrow.end %r
|
||||
%v = atomic.take %c
|
||||
%k = const.u64 0
|
||||
ret %k
|
||||
@@ -0,0 +1,21 @@
|
||||
; A store cannot be acquire (spec 04 §24).
|
||||
; expect: reject E4201
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.store_acquire
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @main() -> u64
|
||||
effects [atomic, atomic.weak]
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%c = atomic.new %z
|
||||
%r = borrow.ref %c
|
||||
%one = const.u64 1
|
||||
atomic.store.acquire %r, %one
|
||||
borrow.end %r
|
||||
%v = atomic.take %c
|
||||
%k = const.u64 0
|
||||
ret %k
|
||||
@@ -0,0 +1,16 @@
|
||||
; atomic<T> is linear: as a struct field it needs linear_aggregates (spec 04 §23).
|
||||
; expect: reject E0006
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.struct_field
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
type @S = struct { n: atomic<u64> }
|
||||
|
||||
fn @main() -> u64
|
||||
effects []
|
||||
entry:
|
||||
%k = const.u64 0
|
||||
ret %k
|
||||
@@ -0,0 +1,19 @@
|
||||
; atomic.take needs every borrow of the cell ended (spec 04 §28).
|
||||
; expect: reject E2101
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.take_while_borrowed
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @main() -> u64
|
||||
effects [atomic]
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%c = atomic.new %z
|
||||
%r = borrow.ref %c
|
||||
%v = atomic.take %c
|
||||
%x = atomic.load.seq_cst %r
|
||||
borrow.end %r
|
||||
ret %v
|
||||
@@ -0,0 +1,28 @@
|
||||
; atomic.take while the cell is lent to a live task is a race (spec 04 §28).
|
||||
; expect: reject E4101
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.take_while_lent
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, cancellation, effects, ownership, tasks]
|
||||
|
||||
fn @reader(%c: ref<atomic<u64>>) -> u64
|
||||
effects [atomic]
|
||||
entry:
|
||||
%x = atomic.load.seq_cst %c
|
||||
ret %x
|
||||
|
||||
fn @main() -> u64
|
||||
effects [atomic, task.spawn, task.wait]
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%c = atomic.new %z
|
||||
%r = borrow.ref %c
|
||||
%s = task.scope.begin
|
||||
%t = task.spawn %s, @reader(%r)
|
||||
%v = atomic.take %c
|
||||
%x = task.join %t
|
||||
task.scope.end %s
|
||||
borrow.end %r
|
||||
ret %v
|
||||
@@ -0,0 +1,20 @@
|
||||
; atomic<T> holds bool or an integer of at most 64 bits (spec 04 §23).
|
||||
; expect: reject E1001
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.u128_cell
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @main() -> u64
|
||||
effects [atomic]
|
||||
entry:
|
||||
%z = const.u128 0
|
||||
%c = atomic.new %z
|
||||
%r = borrow.ref %c
|
||||
%x = atomic.load.seq_cst %r
|
||||
borrow.end %r
|
||||
%v = atomic.take %c
|
||||
%k = const.u64 0
|
||||
ret %k
|
||||
@@ -0,0 +1,27 @@
|
||||
; A strong compare-exchange returns the old value and whether it exchanged; a non-seq_cst one needs atomic.weak.
|
||||
; expect: run
|
||||
; result: 14
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.atomic_cmpxchg
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @main() -> u64
|
||||
effects [atomic, atomic.weak]
|
||||
entry:
|
||||
%five = const.u64 5
|
||||
%c = atomic.new %five
|
||||
%r = borrow.ref %c
|
||||
%seven = const.u64 7
|
||||
%old1, %ok1 = atomic.cmpxchg.seq_cst.seq_cst %r, %five, %seven
|
||||
assert %ok1
|
||||
%old2, %ok2 = atomic.cmpxchg.acq_rel.acquire %r, %five, %five
|
||||
%no = const.bool true
|
||||
%failed = xor.bool %ok2, %no
|
||||
assert %failed
|
||||
borrow.end %r
|
||||
%v = atomic.take %c
|
||||
%sum = add.checked.u64 %v, %old2
|
||||
ret %sum
|
||||
@@ -0,0 +1,36 @@
|
||||
; Two tasks add to one cell with relaxed add.wrap: atomicity makes the total exact on every schedule.
|
||||
; expect: run
|
||||
; schedules: 30
|
||||
; quantum: 1
|
||||
; result: 6
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.atomic_counter
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, cancellation, effects, ownership, tasks]
|
||||
|
||||
fn @bump(%c: ref<atomic<u64>>) -> u64
|
||||
effects [atomic, atomic.weak]
|
||||
entry:
|
||||
%one = const.u64 1
|
||||
%a = atomic.add.wrap.relaxed %c, %one
|
||||
%b = atomic.add.wrap.relaxed %c, %one
|
||||
%d = atomic.add.wrap.relaxed %c, %one
|
||||
ret %d
|
||||
|
||||
fn @main() -> u64
|
||||
effects [atomic, atomic.weak, task.spawn, task.wait]
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%cell = atomic.new %z
|
||||
%r = borrow.ref %cell
|
||||
%s = task.scope.begin
|
||||
%t1 = task.spawn %s, @bump(%r)
|
||||
%t2 = task.spawn %s, @bump(%r)
|
||||
%x1 = task.join %t1
|
||||
%x2 = task.join %t2
|
||||
task.scope.end %s
|
||||
borrow.end %r
|
||||
%total = atomic.take %cell
|
||||
ret %total
|
||||
@@ -0,0 +1,48 @@
|
||||
; Release/acquire publication: whenever the reader sees the flag, it sees the data (never 1 with 0).
|
||||
; expect: run
|
||||
; schedules: 30
|
||||
; quantum: 1
|
||||
; result: 1
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.atomic_publication
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, cancellation, effects, ownership, tasks]
|
||||
|
||||
fn @writer(%d: ref<atomic<u64>>, %f: ref<atomic<bool>>) -> u64
|
||||
effects [atomic, atomic.weak]
|
||||
entry:
|
||||
%v = const.u64 42
|
||||
atomic.store.relaxed %d, %v
|
||||
%t = const.bool true
|
||||
atomic.store.release %f, %t
|
||||
ret %v
|
||||
|
||||
fn @main() -> u64
|
||||
effects [atomic, atomic.weak, task.spawn, task.wait]
|
||||
entry:
|
||||
%z = const.u64 0
|
||||
%no = const.bool false
|
||||
%data = atomic.new %z
|
||||
%flag = atomic.new %no
|
||||
%rd = borrow.ref %data
|
||||
%rf = borrow.ref %flag
|
||||
%s = task.scope.begin
|
||||
%t = task.spawn %s, @writer(%rd, %rf)
|
||||
%seen = atomic.load.acquire %rf
|
||||
%val = atomic.load.relaxed %rd
|
||||
%w = task.join %t
|
||||
task.scope.end %s
|
||||
borrow.end %rd
|
||||
borrow.end %rf
|
||||
%dv = atomic.take %data
|
||||
%fv = atomic.take %flag
|
||||
cbr %seen, @published(), @done()
|
||||
published:
|
||||
%ok = eq.u64 %val, %w
|
||||
assert %ok
|
||||
br @done()
|
||||
done:
|
||||
%one = const.u64 1
|
||||
ret %one
|
||||
@@ -0,0 +1,44 @@
|
||||
; Every read-modify-write returns the old value; add.wrap and sub.wrap are modular; bool cells take xchg, and, or, xor.
|
||||
; expect: run
|
||||
; result: 10
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.atomic_rmw_ops
|
||||
air 0
|
||||
lang 0.1
|
||||
features [atomics, effects, ownership]
|
||||
|
||||
fn @main() -> u8
|
||||
effects [atomic]
|
||||
entry:
|
||||
%z = const.u8 0
|
||||
%c = atomic.new %z
|
||||
%r = borrow.ref %c
|
||||
%one = const.u8 1
|
||||
%o1 = atomic.sub.wrap.seq_cst %r, %one
|
||||
%v6 = const.u8 6
|
||||
%o2 = atomic.xchg.seq_cst %r, %v6
|
||||
%v3 = const.u8 3
|
||||
%o3 = atomic.and.seq_cst %r, %v3
|
||||
%v8 = const.u8 8
|
||||
%o4 = atomic.or.seq_cst %r, %v8
|
||||
%o5 = atomic.xor.seq_cst %r, %v3
|
||||
%o6 = atomic.add.wrap.seq_cst %r, %one
|
||||
borrow.end %r
|
||||
%final = atomic.take %c
|
||||
%e1 = const.u8 255
|
||||
%k1 = eq.u8 %o2, %e1
|
||||
assert %k1
|
||||
%e2 = const.u8 2
|
||||
%k2 = eq.u8 %o4, %e2
|
||||
assert %k2
|
||||
%t = const.bool true
|
||||
%b = atomic.new %t
|
||||
%rb = borrow.ref %b
|
||||
%ob = atomic.xor.seq_cst %rb, %t
|
||||
borrow.end %rb
|
||||
%fb = atomic.take %b
|
||||
assert %ob
|
||||
%nf = xor.bool %fb, %t
|
||||
assert %nf
|
||||
ret %final
|
||||
@@ -0,0 +1,23 @@
|
||||
// compare_exchange binds the old value and whether it exchanged; the other operations return the old value.
|
||||
// expect: run
|
||||
// result: 28
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.compare_exchange
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic, atomic.weak]
|
||||
{
|
||||
let c = atomic.new(5u64);
|
||||
let (old, exchanged) = atomic.compare_exchange(ref c, 5u64, 9u64, acq_rel, acquire);
|
||||
let (old2, again) = atomic.compare_exchange(ref c, 5u64, 1u64, seq_cst, relaxed);
|
||||
let before = atomic.swap(ref c, 3u64, seq_cst);
|
||||
let x = atomic.or(ref c, 4u64, seq_cst);
|
||||
let y = atomic.and(ref c, 6u64, seq_cst);
|
||||
let z = atomic.xor(ref c, 1u64, seq_cst);
|
||||
let w = atomic.sub.wrap(ref c, 2u64, seq_cst);
|
||||
atomic.fence(acq_rel);
|
||||
let last = atomic.load(ref c, seq_cst);
|
||||
let v = atomic.take(move c);
|
||||
if exchanged and not again { old + old2 + before + v } else { 0 }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Two tasks add to one cell with relaxed add.wrap; the total is exact on every schedule.
|
||||
// expect: run
|
||||
// schedules: 30
|
||||
// quantum: 7
|
||||
// result: 100
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.counter
|
||||
|
||||
fn bump(c: ref<atomic<u64>>) -> u8
|
||||
effects [atomic, atomic.weak]
|
||||
{
|
||||
var i: u64 = 0;
|
||||
while i < 50 {
|
||||
let prev = atomic.add.wrap(c, 1u64, relaxed);
|
||||
i = i + 1;
|
||||
}
|
||||
0u8
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic, atomic.weak, task.spawn, task.wait]
|
||||
{
|
||||
let count = atomic.new(0u64);
|
||||
{
|
||||
ref c = count;
|
||||
scope s {
|
||||
let a = task.spawn(s, bump, c);
|
||||
let b = task.spawn(s, bump, c);
|
||||
let ra = task.join(move a);
|
||||
let rb = task.join(move b);
|
||||
}
|
||||
}
|
||||
atomic.take(move count)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// Release/acquire publication: a reader that sees the flag sees the data.
|
||||
// expect: run
|
||||
// schedules: 30
|
||||
// quantum: 1
|
||||
// result: 1
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.publication
|
||||
|
||||
fn publish(data: ref<atomic<u64>>, ready: ref<atomic<bool>>) -> u8
|
||||
effects [atomic, atomic.weak]
|
||||
{
|
||||
atomic.store(data, 42u64, relaxed);
|
||||
atomic.store(ready, true, release);
|
||||
0u8
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic, atomic.weak, task.spawn, task.wait]
|
||||
{
|
||||
let data = atomic.new(0u64);
|
||||
let ready = atomic.new(false);
|
||||
var ok: u64 = 1;
|
||||
{
|
||||
ref d = data;
|
||||
ref r = ready;
|
||||
scope s {
|
||||
let p = task.spawn(s, publish, d, r);
|
||||
if atomic.load(r, acquire) {
|
||||
if atomic.load(d, relaxed) != 42 {
|
||||
ok = 0;
|
||||
}
|
||||
}
|
||||
let rp = task.join(move p);
|
||||
}
|
||||
}
|
||||
let v = atomic.take(move data);
|
||||
let f = atomic.take(move ready);
|
||||
ok
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// An atomic cell is not copied: `let b = a;` would be ambiguous, so the move is written.
|
||||
// expect: reject E7003
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.copy_cell
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic]
|
||||
{
|
||||
let a = atomic.new(1u64);
|
||||
let b = a;
|
||||
atomic.take(move b)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// compare_exchange has two results and is bound with `let (old, exchanged) = …`.
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.exchange_as_value
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic]
|
||||
{
|
||||
let c = atomic.new(1u64);
|
||||
let v = atomic.compare_exchange(ref c, 1u64, 2u64, seq_cst, seq_cst);
|
||||
atomic.take(move c)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// The failure ordering of compare_exchange is never stronger than its success ordering.
|
||||
// expect: reject E4201
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.exchange_failure_order
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic, atomic.weak]
|
||||
{
|
||||
let c = atomic.new(1u64);
|
||||
let (old, exchanged) = atomic.compare_exchange(ref c, 1u64, 2u64, relaxed, acquire);
|
||||
let v = atomic.take(move c);
|
||||
old + v
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// A load cannot be release.
|
||||
// expect: reject E4201
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.invalid_order
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic, atomic.weak]
|
||||
{
|
||||
let c = atomic.new(1u64);
|
||||
let v = atomic.load(ref c, release);
|
||||
let t = atomic.take(move c);
|
||||
v
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// An atomic cell is linear: it is taken, moved or returned.
|
||||
// expect: reject E3002
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.leak
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic]
|
||||
{
|
||||
let c = atomic.new(1u64);
|
||||
atomic.load(ref c, seq_cst)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// An atomic cell is borrowed with `ref`, never `mut`.
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.mut_borrow
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic]
|
||||
{
|
||||
let c = atomic.new(1u64);
|
||||
{
|
||||
mut m = c;
|
||||
}
|
||||
atomic.take(move c)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Orderings are words written in place, not values.
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.ordering_value
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic]
|
||||
{
|
||||
let c = atomic.new(1u64);
|
||||
let o = 1u64;
|
||||
let v = atomic.load(ref c, o);
|
||||
let t = atomic.take(move c);
|
||||
v
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// A cell is read only by atomic operations: `*r` is not one.
|
||||
// expect: reject E4202
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.ordinary_read
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic]
|
||||
{
|
||||
let c = atomic.new(1u64);
|
||||
var v: u64 = 0;
|
||||
{
|
||||
ref r = c;
|
||||
v = *r;
|
||||
}
|
||||
let t = atomic.take(move c);
|
||||
v
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Taking a cell while its borrow is lent to a live task is a race.
|
||||
// expect: reject E4101
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.take_while_lent
|
||||
|
||||
fn read(c: ref<atomic<u64>>) -> u64
|
||||
effects [atomic]
|
||||
{
|
||||
atomic.load(c, seq_cst)
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic, task.spawn, task.wait]
|
||||
{
|
||||
let c = atomic.new(1u64);
|
||||
var v: u64 = 0;
|
||||
{
|
||||
ref r = c;
|
||||
scope s {
|
||||
let t = task.spawn(s, read, r);
|
||||
v = atomic.take(move c);
|
||||
let x = task.join(move t);
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// A relaxed access needs atomic.weak besides atomic.
|
||||
// expect: reject E3101
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.weak_effect
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic]
|
||||
{
|
||||
let c = atomic.new(1u64);
|
||||
let v = atomic.load(ref c, relaxed);
|
||||
let t = atomic.take(move c);
|
||||
v
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// atomic<T> holds bool or an integer of at most 64 bits.
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.wide_cell
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic]
|
||||
{
|
||||
let c = atomic.new(1u128);
|
||||
let t = atomic.take(move c);
|
||||
0
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Atomic operations take the cell through `ref`.
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.without_ref
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic]
|
||||
{
|
||||
let c = atomic.new(1u64);
|
||||
let v = atomic.load(c, seq_cst);
|
||||
let t = atomic.take(move c);
|
||||
v
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// With seq_cst only, a function declares atomic and not atomic.weak: interleaving reasoning is exact.
|
||||
// expect: run
|
||||
// schedules: 30
|
||||
// quantum: 1
|
||||
// result: 1
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.sc_only
|
||||
|
||||
fn flip(x: ref<atomic<u64>>, y: ref<atomic<u64>>) -> u64
|
||||
effects [atomic]
|
||||
{
|
||||
atomic.store(x, 1u64, seq_cst);
|
||||
atomic.load(y, seq_cst)
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic, task.spawn, task.wait]
|
||||
{
|
||||
let x = atomic.new(0u64);
|
||||
let y = atomic.new(0u64);
|
||||
var both: u64 = 0;
|
||||
{
|
||||
ref rx = x;
|
||||
ref ry = y;
|
||||
scope s {
|
||||
let a = task.spawn(s, flip, rx, ry);
|
||||
let b = task.spawn(s, flip, ry, rx);
|
||||
let r0 = task.join(move a);
|
||||
let r1 = task.join(move b);
|
||||
both = r0 + r1;
|
||||
}
|
||||
}
|
||||
let vx = atomic.take(move x);
|
||||
let vy = atomic.take(move y);
|
||||
if both == 0 { 0 } else { 1 }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Quick Reference: atomics.
|
||||
// expect: run
|
||||
// result: 6
|
||||
// phase: 6
|
||||
// spec: docs/agent/quick-reference.md
|
||||
module demo.qratomics
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic, atomic.weak]
|
||||
{
|
||||
let count = atomic.new(0u64); // atomic<T>: bool or an integer up to 64 bits; linear
|
||||
{
|
||||
ref c = count; // every operation takes `ref`; lend `c` to tasks
|
||||
let old = atomic.add.wrap(c, 1u64, relaxed); // swap, add.wrap, sub.wrap, and, or, xor return the old value
|
||||
atomic.store(c, 5u64, release);
|
||||
let v = atomic.load(c, acquire);
|
||||
let (prev, exchanged) = atomic.compare_exchange(c, 5u64, 6u64, acq_rel, acquire);
|
||||
atomic.fence(seq_cst);
|
||||
}
|
||||
let total = atomic.take(move count); // needs no live borrow of count
|
||||
total
|
||||
}
|
||||
@@ -4,7 +4,8 @@ The normative litmus corpus of the memory model (spec 04 §20, §20.5; `docs/ref
|
||||
|
||||
- `tools/litmus/enumerate.py` is the axiomatic oracle. It computes the allowed outcomes of a program from the axioms of spec 04 §20 alone.
|
||||
- `tools/litmus/check.py` compares the oracle's result with the stated sets. They MUST be equal.
|
||||
- From Phase 5 on, the interpreter's exhaustive exploration of each test MUST give exactly the allowed set.
|
||||
- `tools/litmus/run_interp.py` translates each test to AIR (`tools/litmus/to_air.py`), explores it exhaustively with `aji explore`, and requires the interpreter's outcomes to equal the allowed set exactly.
|
||||
- `tools/litmus/differential.py` generates small random programs and requires the interpreter's outcomes to be a subset of the oracle's (soundness on programs outside the corpus).
|
||||
|
||||
## File format
|
||||
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Differential soundness test of the interpreter against the oracle
|
||||
(spec 04 §20.5: for every program, observed ⊆ allowed).
|
||||
|
||||
Generates small random litmus programs (2–3 tasks, 1–3 operations each, valid
|
||||
orderings only), computes the allowed outcomes with the independent oracle
|
||||
(tools/litmus/enumerate.py) and the interpreter's outcomes with
|
||||
`aji explore`, and fails if the interpreter produces an outcome the oracle
|
||||
does not allow. Exact equality is reported, not required: the interpreter is
|
||||
only required to be complete on the normative corpus.
|
||||
|
||||
Usage: python3 tools/litmus/differential.py [--seed N] [--count N] [--aji PATH]
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(os.path.dirname(HERE))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
import enumerate as oracle # noqa: E402
|
||||
import to_air # noqa: E402
|
||||
|
||||
LOADS = ["rlx", "acq", "sc"]
|
||||
STORES = ["rlx", "rel", "sc"]
|
||||
RMWS = ["rlx", "acq", "rel", "ar", "sc"]
|
||||
FENCES = ["acq", "rel", "ar", "sc"]
|
||||
CAS = {"rlx": ["rlx"], "acq": ["rlx", "acq"], "rel": ["rlx"], "ar": ["rlx", "acq"], "sc": ["rlx", "acq", "sc"]}
|
||||
|
||||
|
||||
def program(rng, n):
|
||||
locs = ["x", "y"][: rng.choice([1, 2, 2])]
|
||||
tasks = []
|
||||
reg = 0
|
||||
observe = []
|
||||
for t in range(rng.choice([2, 2, 3])):
|
||||
ops = []
|
||||
for _ in range(rng.randint(1, 3)):
|
||||
kind = rng.choice(["store", "store", "load", "load", "rmw", "cas", "fence"])
|
||||
loc = rng.choice(locs)
|
||||
if kind == "store":
|
||||
ops.append(f"store {loc} {rng.randint(1, 2)} {rng.choice(STORES)}")
|
||||
elif kind == "fence":
|
||||
ops.append(f"fence {rng.choice(FENCES)}")
|
||||
else:
|
||||
r = f"r{reg}"
|
||||
reg += 1
|
||||
observe.append(f"T{t}.{r}")
|
||||
if kind == "load":
|
||||
ops.append(f"{r} = load {loc} {rng.choice(LOADS)}")
|
||||
elif kind == "rmw":
|
||||
ops.append(f"{r} = rmw {rng.choice(['add', 'xchg'])} {loc} {rng.randint(1, 2)} {rng.choice(RMWS)}")
|
||||
else:
|
||||
s = rng.choice(list(CAS))
|
||||
ops.append(f"{r} = cas {loc} {rng.randint(0, 2)} {rng.randint(1, 3)} {s} {rng.choice(CAS[s])}")
|
||||
tasks.append(ops)
|
||||
# Keep the oracle's brute force small: at most six operations in all and
|
||||
# four writes per location (it enumerates every modification order).
|
||||
if sum(len(ops) for ops in tasks) > 6 or any(
|
||||
sum(1 for ops in tasks for o in ops if (o.startswith(f"store {l}") or f" {l} " in o and ("rmw" in o or "cas" in o))) > 4 for l in locs
|
||||
):
|
||||
return program(rng, n)
|
||||
observe += [f"final {l}" for l in locs]
|
||||
lines = [f"name: diff{n}", "init: " + " ".join(f"{l}=0" for l in locs)]
|
||||
for t, ops in enumerate(tasks):
|
||||
lines.append(f"T{t}:")
|
||||
lines += [f" {o}" for o in ops]
|
||||
lines.append("observe: " + " ".join(observe))
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def main(argv):
|
||||
seed, count = 1, 200
|
||||
aji = os.path.join(ROOT, "zig-out", "bin", "aji")
|
||||
while argv:
|
||||
if argv[0] == "--seed":
|
||||
seed = int(argv[1])
|
||||
elif argv[0] == "--count":
|
||||
count = int(argv[1])
|
||||
elif argv[0] == "--aji":
|
||||
aji = argv[1]
|
||||
else:
|
||||
raise SystemExit(__doc__)
|
||||
argv = argv[2:]
|
||||
rng = random.Random(seed)
|
||||
unsound = exact = 0
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for n in range(count):
|
||||
text = program(rng, n)
|
||||
allowed = {tuple(o) for o in oracle.enumerate_program(oracle.parse(text))[0]}
|
||||
prog = to_air.parse(text)
|
||||
air = os.path.join(tmp, f"d{n}.air")
|
||||
open(air, "w").write(to_air.translate(text))
|
||||
r = subprocess.run([aji, "explore", "--grant", "heap=mem.alloc:65536", air], capture_output=True, text=True)
|
||||
res = next((json.loads(l) for l in r.stdout.splitlines() if l.strip().startswith('{"runs"')), None)
|
||||
if res is None:
|
||||
print(f"ERROR program {n}:\n{text}{r.stdout[:500]}{r.stderr[:500]}")
|
||||
return 1
|
||||
observed = {tuple(o["outcome"]["value"][f"o{i}"] for i in range(len(prog["observe"]))) for o in res["outcomes"]}
|
||||
if observed - allowed:
|
||||
unsound += 1
|
||||
print(f"UNSOUND program {n} (seed {seed}): interpreter produced {sorted(observed - allowed)}\n{text}")
|
||||
elif observed == allowed and res["complete"]:
|
||||
exact += 1
|
||||
print(f"{count} programs: {count - unsound} sound ({exact} exact), {unsound} unsound")
|
||||
return 1 if unsound else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Interpreter conformance on the normative litmus corpus (spec 04 §20.5).
|
||||
|
||||
For every test, the outcomes the interpreter produces under exhaustive
|
||||
exploration (`aji explore`) MUST equal the stated allowed set:
|
||||
|
||||
observed_exhaustive == allowed
|
||||
|
||||
Usage: python3 tools/litmus/run_interp.py [--aji PATH] [tests/litmus/*.lit]
|
||||
"""
|
||||
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(os.path.dirname(HERE))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
import check # noqa: E402 (stated sets)
|
||||
import to_air # noqa: E402
|
||||
|
||||
|
||||
def main(argv):
|
||||
aji = os.path.join(ROOT, "zig-out", "bin", "aji")
|
||||
if argv[:1] == ["--aji"]:
|
||||
aji, argv = argv[1], argv[2:]
|
||||
files = argv or sorted(glob.glob(os.path.join(ROOT, "tests", "litmus", "*.lit")))
|
||||
failures = 0
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for f in files:
|
||||
name = os.path.relpath(f, ROOT)
|
||||
allowed, forbidden = check.stated(f)
|
||||
air = os.path.join(tmp, os.path.basename(f) + ".air")
|
||||
prog = to_air.parse(open(f).read())
|
||||
open(air, "w").write(to_air.translate(open(f).read()))
|
||||
r = subprocess.run([aji, "explore", "--grant", "heap=mem.alloc:65536", air], capture_output=True, text=True)
|
||||
lines = [json.loads(l) for l in r.stdout.splitlines() if l.strip()]
|
||||
result = next((l for l in lines if "outcomes" in l), None)
|
||||
if result is None:
|
||||
failures += 1
|
||||
print(f"ERROR {name}: {r.stdout.strip()[:300]} {r.stderr.strip()[:300]}")
|
||||
continue
|
||||
observed = set()
|
||||
others = []
|
||||
for o in result["outcomes"]:
|
||||
out = o["outcome"]
|
||||
if out.get("status") != "returned":
|
||||
others.append(out)
|
||||
continue
|
||||
observed.add(tuple(out["value"][f"o{i}"] for i in range(len(prog["observe"]))))
|
||||
problems = []
|
||||
if not result["complete"]:
|
||||
problems.append(f"exploration incomplete after {result['runs']} runs")
|
||||
if others:
|
||||
problems.append(f"non-returning outcomes {others[:3]}")
|
||||
if observed - allowed:
|
||||
problems.append(f"interpreter produced unallowed {sorted(observed - allowed)}")
|
||||
if allowed - observed:
|
||||
problems.append(f"interpreter never produced allowed {sorted(allowed - observed)}")
|
||||
if observed & forbidden:
|
||||
problems.append(f"interpreter produced forbidden {sorted(observed & forbidden)}")
|
||||
if problems:
|
||||
failures += 1
|
||||
print(f"MISMATCH {name}: " + "; ".join(problems))
|
||||
else:
|
||||
print(f"ok {name} ({result['runs']} runs)")
|
||||
print(f"\n{len(files) - failures} exact, {failures} not")
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,343 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Translate a litmus test (tests/litmus/README.md) into a text AIR program.
|
||||
|
||||
The program's result is a struct `@Out` with one u64 field per observed
|
||||
value, in `observe:` order. Run it with
|
||||
`aji explore --grant heap=mem.alloc:65536 FILE.air`.
|
||||
|
||||
Mapping:
|
||||
|
||||
- every location is an `atomic<u64>` created in `@main` and lent to the
|
||||
tasks as `ref<atomic<u64>>`; `final x` is `atomic.take` after all joins;
|
||||
- every task is a function returning a struct of its registers and of the
|
||||
results of the tasks it joins;
|
||||
- a channel is a `channel.make u64` with room for every send; each sending
|
||||
task receives its own sender and closes it after its last send, the
|
||||
receiving task receives the receiver and closes it at its end;
|
||||
- a mutex is a `mutex<u64>` lent as `ref<mutex<u64>>`;
|
||||
- `spawn Tn` / `join Tn` open a task scope in the spawning task.
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
|
||||
ORD = {"rlx": "relaxed", "acq": "acquire", "rel": "release", "ar": "acq_rel", "sc": "seq_cst"}
|
||||
RMW = {"xchg": "xchg", "add": "add.wrap", "sub": "sub.wrap", "and": "and", "or": "or", "xor": "xor"}
|
||||
|
||||
|
||||
def parse(text):
|
||||
prog = {"name": None, "init": {}, "tasks": {}, "order": [], "spawned": set(), "observe": []}
|
||||
cur = None
|
||||
for raw in text.splitlines():
|
||||
line = raw.split("#", 1)[0].rstrip()
|
||||
if not line.strip():
|
||||
continue
|
||||
if not line.startswith((" ", "\t")):
|
||||
cur = None
|
||||
key, _, rest = line.partition(":")
|
||||
m = re.fullmatch(r"(T\d+)( \(spawned\))?", key.strip())
|
||||
if m:
|
||||
cur = m.group(1)
|
||||
prog["tasks"][cur] = []
|
||||
prog["order"].append(cur)
|
||||
if m.group(2):
|
||||
prog["spawned"].add(cur)
|
||||
elif key == "name":
|
||||
prog["name"] = rest.strip()
|
||||
elif key == "init":
|
||||
for kv in rest.split():
|
||||
k, v = kv.split("=")
|
||||
prog["init"][k] = int(v)
|
||||
elif key == "observe":
|
||||
toks = rest.split()
|
||||
i = 0
|
||||
while i < len(toks):
|
||||
if toks[i] == "final":
|
||||
prog["observe"].append(("final", toks[i + 1]))
|
||||
i += 2
|
||||
else:
|
||||
t, r = toks[i].split(".")
|
||||
prog["observe"].append(("reg", t, r))
|
||||
i += 1
|
||||
continue
|
||||
prog["tasks"][cur].append(line.split())
|
||||
return prog
|
||||
|
||||
|
||||
class Gen:
|
||||
def __init__(self, prog):
|
||||
self.p = prog
|
||||
self.lines = []
|
||||
self.n = 0
|
||||
locs = list(prog["init"])
|
||||
self.locs = locs
|
||||
self.chans = sorted({op[1] for ops in prog["tasks"].values() for op in ops if op[0] in ("send", "recv")})
|
||||
self.mutexes = sorted({op[1] for ops in prog["tasks"].values() for op in ops if op[0] in ("lock", "unlock")})
|
||||
# Which task sends / receives on each channel; who spawns whom.
|
||||
self.senders = {c: [t for t in prog["order"] if any(op[:2] == ["send", c] for op in prog["tasks"][t])] for c in self.chans}
|
||||
self.receiver = {c: next(t for t in prog["order"] if any(op[:2] == ["recv", c] for op in prog["tasks"][t])) for c in self.chans}
|
||||
self.spawns = {t: [op[1] for op in prog["tasks"][t] if op[0] == "spawn"] for t in prog["order"]}
|
||||
|
||||
def fresh(self, base):
|
||||
self.n += 1
|
||||
return f"%{base}_{self.n}"
|
||||
|
||||
def emit(self, s):
|
||||
self.lines.append(s)
|
||||
|
||||
def regs(self, t):
|
||||
out = []
|
||||
for op in self.p["tasks"][t]:
|
||||
if len(op) > 1 and op[1] == "=":
|
||||
out.append(op[0])
|
||||
return out
|
||||
|
||||
def ret_type(self, t):
|
||||
return f"@R_{t}"
|
||||
|
||||
def type_decls(self):
|
||||
for t in self.p["order"]:
|
||||
fields = [f"{r}: u64" for r in self.regs(t)] + [f"j_{c}: {self.ret_type(c)}" for c in self.spawns[t]]
|
||||
self.emit(f"type {self.ret_type(t)} = struct {{ {', '.join(fields)} }}" if fields else f"type {self.ret_type(t)} = struct {{}}")
|
||||
fields = [f"o{i}: u64" for i in range(len(self.p["observe"]))]
|
||||
self.emit(f"type @Out = struct {{ {', '.join(fields)} }}")
|
||||
|
||||
def params(self, t):
|
||||
"""The parameters of task t: refs of every location and mutex, its
|
||||
endpoints, and the endpoints of the tasks it spawns."""
|
||||
ps = [(f"%{l}", "ref<atomic<u64>>") for l in self.locs]
|
||||
ps += [(f"%m_{m}", "ref<mutex<u64>>") for m in self.mutexes]
|
||||
for c in self.chans:
|
||||
for tt in self.closure(t):
|
||||
if tt in self.senders[c]:
|
||||
ps.append((f"%tx_{c}_{tt}", "sender<u64>"))
|
||||
if self.receiver[c] == tt:
|
||||
ps.append((f"%rx_{c}", "receiver<u64>"))
|
||||
return ps
|
||||
|
||||
def closure(self, t):
|
||||
out = [t]
|
||||
for c in self.spawns[t]:
|
||||
out += self.closure(c)
|
||||
return out
|
||||
|
||||
def task(self, t, effects):
|
||||
ps = self.params(t)
|
||||
self.emit("")
|
||||
self.emit(f"fn @{t}({', '.join(f'{n}: {ty}' for n, ty in ps)}) -> {self.ret_type(t)}")
|
||||
self.emit(f"effects [{', '.join(effects)}]")
|
||||
self.emit("entry:")
|
||||
joined = {}
|
||||
scope = None
|
||||
handles = {}
|
||||
last_send = {c: max((i for i, op in enumerate(self.p["tasks"][t]) if op[:2] == ["send", c]), default=-1) for c in self.chans}
|
||||
guards = {}
|
||||
for i, op in enumerate(self.p["tasks"][t]):
|
||||
if op[0] == "store":
|
||||
k = self.fresh("k")
|
||||
self.emit(f" {k} = const.u64 {op[2]}")
|
||||
self.emit(f" atomic.store.{ORD[op[3]]} %{op[1]}, {k}")
|
||||
elif op[0] == "fence":
|
||||
self.emit(f" atomic.fence.{ORD[op[1]]}")
|
||||
elif op[1] == "=" and op[2] == "load":
|
||||
self.emit(f" %{op[0]} = atomic.load.{ORD[op[4]]} %{op[3]}")
|
||||
elif op[1] == "=" and op[2] == "rmw":
|
||||
k = self.fresh("k")
|
||||
self.emit(f" {k} = const.u64 {op[5]}")
|
||||
self.emit(f" %{op[0]} = atomic.{RMW[op[3]]}.{ORD[op[6]]} %{op[4]}, {k}")
|
||||
elif op[1] == "=" and op[2] == "cas":
|
||||
e, n = self.fresh("e"), self.fresh("n")
|
||||
self.emit(f" {e} = const.u64 {op[4]}")
|
||||
self.emit(f" {n} = const.u64 {op[5]}")
|
||||
self.emit(f" %{op[0]}, {self.fresh('ok')} = atomic.cmpxchg.{ORD[op[6]]}.{ORD[op[7]]} %{op[3]}, {e}, {n}")
|
||||
elif op[0] == "send":
|
||||
c = op[1]
|
||||
tok = self.fresh("tok")
|
||||
b = self.fresh("tx")
|
||||
ok = self.fresh("sent")[1:]
|
||||
bad = self.fresh("send_failed")[1:]
|
||||
self.emit(f" {tok} = const.u64 0")
|
||||
self.emit(f" {b} = borrow.mut %tx_{c}_{t}")
|
||||
self.emit(f" channel.send {b}, {tok}, ok -> @{ok}, closed -> @{bad}, cancelled -> @{bad}")
|
||||
self.emit(f"{bad}(%v_{bad}: u64):")
|
||||
self.emit(" trap")
|
||||
self.emit(f"{ok}:")
|
||||
self.emit(f" borrow.end {b}")
|
||||
if i == last_send[c]:
|
||||
self.emit(f" channel.close_sender %tx_{c}_{t}")
|
||||
elif op[0] == "recv":
|
||||
c = op[1]
|
||||
b = self.fresh("rx")
|
||||
ok = self.fresh("got")[1:]
|
||||
bad = self.fresh("recv_failed")[1:]
|
||||
self.emit(f" {b} = borrow.mut %rx_{c}")
|
||||
self.emit(f" channel.recv {b}, ok -> @{ok}, closed -> @{bad}, cancelled -> @{bad}")
|
||||
self.emit(f"{bad}:")
|
||||
self.emit(" trap")
|
||||
self.emit(f"{ok}(%msg_{ok}: u64):")
|
||||
self.emit(f" borrow.end {b}")
|
||||
elif op[0] == "lock":
|
||||
ok = self.fresh("locked")[1:]
|
||||
bad = self.fresh("lock_cancelled")[1:]
|
||||
g = f"%g_{ok}"
|
||||
self.emit(f" mutex.lock %m_{op[1]}, ok -> @{ok}, cancelled -> @{bad}")
|
||||
self.emit(f"{bad}:")
|
||||
self.emit(" trap")
|
||||
self.emit(f"{ok}({g}: guard<u64>):")
|
||||
guards[op[1]] = g
|
||||
elif op[0] == "unlock":
|
||||
self.emit(f" mutex.unlock {guards.pop(op[1])}")
|
||||
elif op[0] == "spawn":
|
||||
c = op[1]
|
||||
if scope is None:
|
||||
scope = self.fresh("scope")
|
||||
self.emit(f" {scope} = task.scope.begin")
|
||||
args = [n for n, _ in self.params(c)]
|
||||
h = self.fresh("task")
|
||||
self.emit(f" {h} = task.spawn {scope}, @{c}({', '.join(args)})")
|
||||
handles[c] = h
|
||||
elif op[0] == "join":
|
||||
c = op[1]
|
||||
r = self.fresh("joined")
|
||||
self.emit(f" {r} = task.join {handles[c]}")
|
||||
joined[c] = r
|
||||
else:
|
||||
raise SystemExit(f"unknown operation {op}")
|
||||
for c in self.chans:
|
||||
if self.receiver[c] == t:
|
||||
ok = self.fresh("closed")[1:]
|
||||
pend = self.fresh("pending")[1:]
|
||||
self.emit(f" channel.close_receiver %rx_{c}, ok -> @{ok}, pending -> @{pend}")
|
||||
self.emit(f"{pend}(%p_{pend}: receiver<u64>):")
|
||||
self.emit(" trap")
|
||||
self.emit(f"{ok}:")
|
||||
if scope is not None:
|
||||
self.emit(f" task.scope.end {scope}")
|
||||
fields = [f"%{r}" for r in self.regs(t)] + [joined[c] for c in self.spawns[t]]
|
||||
res = self.fresh("result")
|
||||
self.emit(f" {res} = struct.make {self.ret_type(t)}({', '.join(fields)})")
|
||||
self.emit(f" ret {res}")
|
||||
|
||||
def main(self, effects):
|
||||
roots = [t for t in self.p["order"] if t not in self.p["spawned"]]
|
||||
self.emit("")
|
||||
self.emit("fn @main(%heap: cap<mem.alloc>) -> @Out")
|
||||
self.emit(f"effects [{', '.join(effects)}]")
|
||||
self.emit("entry:")
|
||||
for l in self.locs:
|
||||
v = self.fresh("init")
|
||||
self.emit(f" {v} = const.u64 {self.p['init'][l]}")
|
||||
self.emit(f" %a_{l} = atomic.new {v}")
|
||||
self.emit(f" %{l} = borrow.ref %a_{l}")
|
||||
for m in self.mutexes:
|
||||
z = self.fresh("z")
|
||||
self.emit(f" {z} = const.u64 0")
|
||||
self.emit(f" %mx_{m} = mutex.make {z}")
|
||||
self.emit(f" %m_{m} = borrow.ref %mx_{m}")
|
||||
for c in self.chans:
|
||||
sends = sum(1 for ops in self.p["tasks"].values() for op in ops if op[:2] == ["send", c])
|
||||
cap = self.fresh("cap")
|
||||
ok = self.fresh("chan")[1:]
|
||||
bad = self.fresh("oom")[1:]
|
||||
self.emit(f" {cap} = const.usize {max(sends, 1)}")
|
||||
self.emit(f" channel.make u64, {cap}, %heap, ok -> @{ok}, err -> @{bad}")
|
||||
self.emit(f"{bad}(%e_{bad}: alloc_error):")
|
||||
self.emit(" trap")
|
||||
self.emit(f"{ok}(%tx0_{c}: sender<u64>, %rx_{c}: receiver<u64>):")
|
||||
senders = self.senders[c]
|
||||
for i, s in enumerate(senders):
|
||||
if i + 1 < len(senders):
|
||||
b = self.fresh("txb")
|
||||
self.emit(f" {b} = borrow.ref %tx0_{c}")
|
||||
self.emit(f" %tx_{c}_{s} = channel.sender.dup {b}")
|
||||
self.emit(f" borrow.end {b}")
|
||||
else:
|
||||
self.emit(f" %tx_{c}_{s} = copy %tx0_{c}" if False else f" ; last sender takes the original")
|
||||
if senders:
|
||||
self.last_sender_alias = getattr(self, "last_sender_alias", {})
|
||||
self.last_sender_alias[c] = senders[-1]
|
||||
# Rename the original sender to the last sending task's name.
|
||||
text = "\n".join(self.lines)
|
||||
for c, s in getattr(self, "last_sender_alias", {}).items():
|
||||
text = text.replace(f"%tx0_{c}", f"%tx_{c}_{s}")
|
||||
self.lines = text.split("\n")
|
||||
self.emit(" %scope = task.scope.begin")
|
||||
for t in roots:
|
||||
args = [n for n, _ in self.params(t)]
|
||||
self.emit(f" %h_{t} = task.spawn %scope, @{t}({', '.join(args)})")
|
||||
for t in roots:
|
||||
self.emit(f" %res_{t} = task.join %h_{t}")
|
||||
self.emit(" task.scope.end %scope")
|
||||
for l in self.locs:
|
||||
self.emit(f" borrow.end %{l}")
|
||||
for m in self.mutexes:
|
||||
self.emit(f" borrow.end %m_{m}")
|
||||
self.emit(f" %mv_{m} = mutex.take %mx_{m}")
|
||||
finals = {}
|
||||
for l in self.locs:
|
||||
finals[l] = f"%final_{l}"
|
||||
self.emit(f" %final_{l} = atomic.take %a_{l}")
|
||||
outs = []
|
||||
for o in self.p["observe"]:
|
||||
if o[0] == "final":
|
||||
outs.append(finals[o[1]])
|
||||
continue
|
||||
_, t, r = o
|
||||
# The struct path from a root task down to t.
|
||||
path = self.path_to(t)
|
||||
cur = f"%res_{path[0]}"
|
||||
for parent, child in zip(path, path[1:]):
|
||||
v = self.fresh("j")
|
||||
self.emit(f" {v} = struct.get {self.ret_type(parent)}.j_{child}, {cur}")
|
||||
cur = v
|
||||
v = self.fresh("o")
|
||||
self.emit(f" {v} = struct.get {self.ret_type(t)}.{r}, {cur}")
|
||||
outs.append(v)
|
||||
self.emit(f" %out = struct.make @Out({', '.join(outs)})")
|
||||
self.emit(" ret %out")
|
||||
|
||||
def path_to(self, t):
|
||||
for root in self.p["order"]:
|
||||
if root in self.p["spawned"]:
|
||||
continue
|
||||
path = self.find(root, t)
|
||||
if path:
|
||||
return path
|
||||
raise SystemExit(f"task {t} is never started")
|
||||
|
||||
def find(self, cur, t):
|
||||
if cur == t:
|
||||
return [cur]
|
||||
for c in self.spawns[cur]:
|
||||
p = self.find(c, t)
|
||||
if p:
|
||||
return [cur] + p
|
||||
return None
|
||||
|
||||
def module(self):
|
||||
name = re.sub(r"[^a-z0-9_]", "_", self.p["name"].lower())
|
||||
effects = ["atomic", "atomic.weak", "mem.alloc", "task.spawn", "task.wait"]
|
||||
self.type_decls()
|
||||
decls = self.lines
|
||||
self.lines = []
|
||||
self.main(effects)
|
||||
body_main = self.lines
|
||||
self.lines = []
|
||||
for t in self.p["order"]:
|
||||
self.task(t, effects)
|
||||
header = [
|
||||
f"module litmus.{name}",
|
||||
"air 0",
|
||||
"lang 0.1",
|
||||
"features [atomics, cancellation, capabilities, channels, effects, heap, ownership, resources, sync, tasks]",
|
||||
"",
|
||||
]
|
||||
return "\n".join(header + decls + body_main + self.lines) + "\n"
|
||||
|
||||
|
||||
def translate(text):
|
||||
return Gen(parse(text)).module()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.stdout.write(translate(open(sys.argv[1]).read()))
|
||||
@@ -79,6 +79,12 @@ CHECKLIST = [
|
||||
("graphs", "`arc.from_frozen` / `arc.clone` / `arc.release` / `arc.at`", r"arc\.(from_frozen|clone|release|at)\(", True),
|
||||
("graphs", "`iref` equality", r"(?s)(?:island|frozen|arc)\.root\(.*\b\w+ (?:==|!=) (?:\w+|arc\.root\(\w+\)) \{", False),
|
||||
("graphs", "graphs through channels and tasks", r"channel\.make<(island|arc)<", True),
|
||||
("atomics", "`atomic.new` / `atomic.take`", r"atomic\.(new|take)\(", True),
|
||||
("atomics", "`atomic.load` / `atomic.store` with an ordering", r"atomic\.(load|store)\([^)]*(relaxed|acquire|release|seq_cst)\)", True),
|
||||
("atomics", "read-modify-write (`swap`, `add.wrap`, `sub.wrap`, `and`, `or`, `xor`)", r"atomic\.(swap|add\.wrap|sub\.wrap|and|or|xor)\(", False),
|
||||
("atomics", "`let (old, exchanged) = atomic.compare_exchange(…)`", r"let \(\w+, \w+\) = atomic\.compare_exchange\(", True),
|
||||
("atomics", "`atomic.fence`", r"atomic\.fence\(", False),
|
||||
("atomics", "cells lent to tasks (`ref c = cell;`)", r"(?s)ref \w+ = \w+;.*task\.spawn\(.*atomic\.", True),
|
||||
("unsafe", "`ref unchecked` / `assume`", r"\bunchecked\b|\bassume\(", True),
|
||||
("unsafe", "`trusted` rejected", r"\btrusted\b", True),
|
||||
]
|
||||
|
||||
Reference in new issue
Block a user