synth_core/wcet.rs
1//! #778 (v0.46 Wave-1 Lane 2) — the `synth-wcet-v1` static worst-case-cycle map.
2//!
3//! synth holds the EXACT final instruction sequence of every compiled function,
4//! so it is the natural owner of a SOUND static per-function worst-case execution
5//! time (WCET) bound. gale's schedulability track (spar T3/T4) computes a
6//! machine-checked response-time bound, but its per-task cost inputs (`C_i`) are
7//! only DWT high-water-marks — *observations*, not *bounds* — and a hard build
8//! gate forbids sizing budgets from DWT. This sidecar supplies the missing SOUND
9//! input: a cycle bound that is provably ≥ any real execution of the function.
10//!
11//! ## Soundness contract (the whole point)
12//!
13//! A bound that is EVER less than the real cycle count is a defect. This module
14//! is therefore deliberately conservative and DECLINES loudly rather than emit a
15//! number it cannot defend:
16//!
17//! - **Loop-free functions** get an EXACT-form bound: every instruction in the
18//! final stream executes at most once, so the bound is the SUM of each
19//! instruction's documented worst-case cycles. Summing every instruction
20//! (including both arms of an `if/else`) is an over-estimate, hence sound; no
21//! path enumeration is needed.
22//! - **Loops with statically-evident trip counts** (#778 phase 2): a canonical
23//! counted loop — const-initialized counter, const step, const bound, single
24//! backward branch — whose trip count synth PROVES from the final instruction
25//! stream gets `trip × body-worst + overhead` as an upper bound; every
26//! instruction's cost is multiplied by its proven worst-case execution count.
27//! Nested loops multiply only when EVERY level proves.
28//! - **Everything else** — any loop synth cannot prove a trip count for
29//! (data-dependent bounds, non-canonical shapes), any residual/external
30//! label branch (unknown direction), any call (`Bl`/`Blx`, inter-procedural),
31//! any op whose encoder expansion contains an internal runtime loop
32//! (`i64` software div/rem), any unsupported core class — is DECLINED with a
33//! machine-readable reason. gale cannot size a budget from an unsound number,
34//! so a decline is strictly better than a guess.
35//!
36//! `--wcet-hints` (#778 phase 2, the scry seam) supplies UNTRUSTED per-loop
37//! trip-count hints; each is soundly CHECKED against synth's own induction
38//! proof before use and REJECTED with a machine reason otherwise (see
39//! [`WcetHints`] / [`WcetHintReject`]). Richer hint certificates (data-dependent
40//! bounds) and inter-procedural composition remain the named scry / spar
41//! follow-ups, explicitly OUT of scope.
42//!
43//! ## Precondition — a bound without its assumptions is not a safety input
44//!
45//! The per-instruction cycle numbers are documented worst cases for the
46//! **Cortex-M3 / Cortex-M4(F)** in-order pipeline under a **zero-wait-state**
47//! instruction memory (flash accelerator / I-cache hit). The bound is CONDITIONAL
48//! on that precondition, which is recorded in the JSON (`core_class`,
49//! `wait_states`, `memory_assumption`) so the T4 consumer knows exactly what it
50//! holds under. Cortex-M7 (dual-issue + caches with wait-states that can make
51//! actual cycles EXCEED a zero-wait straight sum) is DECLINED, not
52//! approximated — soundness over coverage.
53//!
54//! ## Schema (`synth-wcet-v1`)
55//!
56//! A JSON sidecar written next to the object (`<output>.wcet.json`). Purely
57//! additive metadata: it is derived from the already-decided instruction stream
58//! and never touches `.text`, so the emitted bytes are byte-identical whether or
59//! not the bound is emitted (frozen-safe).
60
61use serde::{Deserialize, Serialize};
62
63/// The schema version string embedded at the top of the sidecar.
64pub const SCHEMA: &str = "synth-wcet-v1";
65
66/// The schema string a `--wcet-hints` file must carry (#778 phase 2).
67pub const HINTS_SCHEMA: &str = "synth-wcet-hints-v1";
68
69/// Why a function could not receive a sound static cycle bound. Each variant is a
70/// distinct, machine-readable decline reason so a consumer (spar T4) can tell an
71/// unbounded loop from an inter-procedural edge from an unsupported core.
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73#[serde(rename_all = "kebab-case")]
74pub enum WcetDecline {
75 /// A backward branch in the final instruction stream — a loop — whose trip
76 /// count synth could NOT statically prove (#778 phase 2 proves canonical
77 /// const-init/const-step/const-bound counted loops; equality-exit shapes
78 /// additionally need a verified `--wcet-hints` entry). Data-dependent
79 /// bounds remain the scry loop-bound-inference follow-up.
80 Loop,
81 /// A DIRECT call (`Bl func_N`) that could not be composed into a bound because
82 /// the callee is unbounded or unresolvable in THIS module — an external/imported
83 /// callee (a WASM import, `__meld_dispatch_import`, or an `__aeabi_*` runtime
84 /// helper: it has no per-function body in this module to sum). #778 phase 3
85 /// composes direct calls to LOCAL, bounded callees over the direct call graph;
86 /// this reason remains for the direct edges that cannot be composed.
87 Call,
88 /// A cycle in the direct call graph (self-recursion or mutual recursion). An
89 /// upper cycle bound cannot be composed from a call graph that revisits a frame
90 /// an unbounded number of times, so every function on the cycle DECLINES. This
91 /// is the #778 phase-3 decline-honesty guard: composition only bounds an acyclic
92 /// direct call graph.
93 Recursion,
94 /// An INDIRECT call (`Blx <reg>` / `call_indirect` / a function-pointer
95 /// dispatch such as `__meld_dispatch_import`): the callee is not statically
96 /// known, so its bound cannot be composed. Declined, not guessed. (#778 phase 3.)
97 IndirectCall,
98 /// A caller whose own body is bounded but that DIRECTLY calls a callee which
99 /// itself declined (transitively): a decline must PROPAGATE up the call graph —
100 /// a caller cannot be bounded while a callee it invokes is unbounded. (#778
101 /// phase 3.) The `note()` names the first unbounded callee for diagnosis.
102 CalleeUnbounded,
103 /// A residual/external label branch (`B`/`Bcc`/… still carrying a label): its
104 /// direction is not statically known here, so it cannot be proven loop-free.
105 UnresolvedBranch,
106 /// An op whose encoder expansion contains an internal RUNTIME loop (the `i64`
107 /// software div/rem shift-subtract: emitted once but executed 64×). Its body
108 /// bytes appear once in the stream, so a straight sum would undercount — a
109 /// sound bound needs a per-op `trip × body` model, a named follow-up.
110 LoopedExpansion,
111 /// The target core class is not soundly summable with a zero-wait per-op table
112 /// (Cortex-M7/M7dp: dual-issue + cache wait-states). Declined, not
113 /// approximated.
114 UnsupportedCore,
115 /// An op the cycle model has not classified. Never emitted in a released
116 /// build (the classifier is exhaustive with no wildcard) — present so the
117 /// schema can carry a conservative decline if the table is ever incomplete.
118 UnmodeledOp,
119}
120
121impl WcetDecline {
122 /// A short human-readable explanation, embedded alongside the machine reason.
123 pub fn note(&self) -> &'static str {
124 match self {
125 WcetDecline::Loop => {
126 "backward branch (loop) without a statically-proven trip count — \
127 canonical const-bound counted loops are proven automatically; \
128 equality-exit shapes need a verified --wcet-hints entry; \
129 data-dependent bounds are the scry loop-bound-inference follow-up"
130 }
131 WcetDecline::Call => {
132 "direct call to an external/imported/unresolvable callee with no \
133 per-function bound in this module — cannot compose an \
134 inter-procedural bound (local direct calls ARE composed, #778 phase 3)"
135 }
136 WcetDecline::Recursion => {
137 "cycle in the direct call graph (self- or mutual recursion) — an \
138 upper cycle bound cannot be composed from a recursive call graph"
139 }
140 WcetDecline::IndirectCall => {
141 "indirect call (Blx <reg> / call_indirect / function-pointer \
142 dispatch) — the callee is not statically known, cannot compose"
143 }
144 WcetDecline::CalleeUnbounded => {
145 "a directly-called callee is itself unbounded — the decline \
146 propagates up the call graph (a caller cannot be bounded while a \
147 callee it invokes is unbounded)"
148 }
149 WcetDecline::UnresolvedBranch => {
150 "residual external/unresolved label branch — direction not \
151 statically known, cannot prove loop-free"
152 }
153 WcetDecline::LoopedExpansion => {
154 "op expands to an internal runtime loop (i64 software div/rem, \
155 executed 64×) — straight sum would undercount"
156 }
157 WcetDecline::UnsupportedCore => {
158 "core class not soundly summable with a zero-wait per-op table \
159 (Cortex-M7 dual-issue + cache wait-states)"
160 }
161 WcetDecline::UnmodeledOp => "op not classified by the cycle model",
162 }
163 }
164}
165
166/// How a loop's trip count was established (#778 phase 2).
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
168#[serde(rename_all = "kebab-case")]
169pub enum WcetLoopBoundSource {
170 /// Fully static proof: const-initialized counter, const step, const bound,
171 /// exit-guaranteeing comparison — the trip count is derived by synth alone.
172 Static,
173 /// The loop is an equality-exit shape synth only bounds under an explicit
174 /// `--wcet-hints` assertion; the hint was CHECKED against synth's own derived
175 /// trip count (divisibility + monotonicity + derived ≤ hint) before use. The
176 /// emitted trip count is still synth's DERIVED value, never the raw hint.
177 HintVerified,
178}
179
180/// One proven-bounded loop inside a bounded function (#778 phase 2). Loops are
181/// listed in ascending `head_offset` order — the SAME order `--wcet-hints`
182/// `loop_bounds` entries are matched by.
183#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
184pub struct WcetLoopBound {
185 /// Byte offset of the loop head (backward-branch target) within the function.
186 pub head_offset: u64,
187 /// The PROVEN maximum number of body executions (full iterations).
188 pub trip_count: u64,
189 /// Number of instructions inside the loop region (head..=backward branch),
190 /// so a consumer can cross-check `cycles ≥ trip_count × region_instr_count`
191 /// (every instruction costs ≥ 1 cycle).
192 pub region_instr_count: usize,
193 /// How the trip count was established.
194 pub source: WcetLoopBoundSource,
195 /// The hint value consumed (present iff `source == HintVerified` or a
196 /// redundant hint was cross-checked against a static proof).
197 #[serde(default, skip_serializing_if = "Option::is_none")]
198 pub hint: Option<u64>,
199}
200
201/// Machine-readable reason a `--wcet-hints` entry was REJECTED (#778 phase 2).
202/// The hint file is UNTRUSTED input: a hint is only ever consumed after synth
203/// verifies the loop's induction against it; everything else lands here.
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
205#[serde(rename_all = "kebab-case")]
206pub enum WcetHintReject {
207 /// The hint is SMALLER than synth's own derived trip count — a wrong hint.
208 /// Trusting it would emit a bound < a real execution (the fatal class).
209 HintBelowDerivedTrip,
210 /// synth could not verify the loop's induction against the hint (counter not
211 /// provably monotonic toward a statically-known bound ≤ hint — e.g. a
212 /// data-dependent bound register, a non-canonical shape, or an equality exit
213 /// whose step does not divide the distance). An unverifiable hint is never
214 /// trusted into a bound.
215 HintUnverifiableInduction,
216 /// The hint indexes a loop that does not exist in this function's final
217 /// instruction stream.
218 HintUnknownLoop,
219}
220
221impl WcetHintReject {
222 /// A short human-readable explanation, embedded alongside the machine reason.
223 pub fn note(&self) -> &'static str {
224 match self {
225 WcetHintReject::HintBelowDerivedTrip => {
226 "hint is below synth's derived trip count — a wrong hint; \
227 trusting it would emit an unsound bound"
228 }
229 WcetHintReject::HintUnverifiableInduction => {
230 "loop induction not verifiable against the hint (counter not \
231 provably monotonic toward a statically-known bound ≤ hint) — \
232 an unverifiable hint is never trusted into a bound"
233 }
234 WcetHintReject::HintUnknownLoop => {
235 "hint indexes a loop that does not exist in the final \
236 instruction stream"
237 }
238 }
239 }
240}
241
242/// One rejected hint, recorded in the sidecar so the oracle (scry) sees exactly
243/// which of its claims synth refused and why.
244#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
245pub struct WcetHintRejection {
246 /// Index into the function's `loop_bounds` hint array (== loop order by
247 /// ascending head offset).
248 pub loop_index: usize,
249 /// Byte offset of the loop head this hint addressed, when the loop exists.
250 #[serde(default, skip_serializing_if = "Option::is_none")]
251 pub head_offset: Option<u64>,
252 /// The rejected hint value.
253 pub hint: u64,
254 /// Machine-readable rejection reason.
255 pub reason: WcetHintReject,
256 /// Human-readable note (`reason.note()`).
257 pub note: String,
258}
259
260/// The per-function result: either a sound cycle bound or a loud decline.
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
262#[serde(tag = "status", rename_all = "kebab-case")]
263pub enum WcetFunction {
264 /// A sound upper bound on this function's execution in cycles.
265 Bounded {
266 /// Function name (WASM export or generated).
267 name: String,
268 /// The sound worst-case cycle bound. For a loop-free function this is the
269 /// SUM of each instruction's documented worst-case cycles (each executes
270 /// at most once). For a function whose loops ALL have proven trip counts
271 /// (#778 phase 2) each instruction's cost is multiplied by its proven
272 /// worst-case execution count. Always ≥ any real execution under the
273 /// stated precondition.
274 cycles: u64,
275 /// Number of ARM instructions summed (diagnostic).
276 instr_count: usize,
277 /// Proven loops (empty for a loop-free function), ascending head offset.
278 #[serde(default, skip_serializing_if = "Vec::is_empty")]
279 loops: Vec<WcetLoopBound>,
280 /// Hints that were rejected (the static proof stands independently).
281 #[serde(default, skip_serializing_if = "Vec::is_empty")]
282 hint_rejections: Vec<WcetHintRejection>,
283 },
284 /// No bound emitted — a loud decline with a machine-readable reason. A decline
285 /// is emitted (rather than the function omitted) so the map is COMPLETE: a
286 /// consumer sees every function is either bounded or explicitly unbounded,
287 /// never silently missing.
288 Declined {
289 /// Function name.
290 name: String,
291 /// Machine-readable reason.
292 reason: WcetDecline,
293 /// Human-readable note (`reason.note()`).
294 note: String,
295 /// Hints that were offered for this function and rejected.
296 #[serde(default, skip_serializing_if = "Vec::is_empty")]
297 hint_rejections: Vec<WcetHintRejection>,
298 },
299}
300
301impl WcetFunction {
302 /// Construct a decline, filling in the note from the reason.
303 pub fn declined(name: impl Into<String>, reason: WcetDecline) -> Self {
304 let note = reason.note().to_string();
305 WcetFunction::Declined {
306 name: name.into(),
307 reason,
308 note,
309 hint_rejections: Vec::new(),
310 }
311 }
312
313 /// Construct a decline carrying rejected-hint records.
314 pub fn declined_with_rejections(
315 name: impl Into<String>,
316 reason: WcetDecline,
317 hint_rejections: Vec<WcetHintRejection>,
318 ) -> Self {
319 let note = reason.note().to_string();
320 WcetFunction::Declined {
321 name: name.into(),
322 reason,
323 note,
324 hint_rejections,
325 }
326 }
327}
328
329/// One direct call site inside a composable function (#778 phase 3). Records the
330/// callee's `BL` label (`func_<idx>` for a local/relocatable-import call) and the
331/// per-instruction execution-count multiplier of the `BL` (1 outside any loop; the
332/// enclosing loop's proven trip product when the call sits inside a proven counted
333/// loop, so a call in a loop is counted `trip` times, never once).
334#[derive(Debug, Clone, PartialEq, Eq)]
335pub struct WcetCallSite {
336 /// The `BL` target label as emitted by the selector (`func_<wasm_index>` for a
337 /// direct local/import call; any other label is a runtime helper → external).
338 pub callee_label: String,
339 /// The call site's worst-case execution count (product of enclosing proven loop
340 /// trip factors; 1 outside any loop). `u128` to survive deep nesting without
341 /// wrapping, matching the loop-multiplier domain.
342 pub multiplier: u128,
343}
344
345/// The per-function INTERMEDIATE result of the WCET pass BEFORE inter-procedural
346/// composition (#778 phase 3). The backend produces one of these per function; the
347/// module-level composer ([`crate::wcet`] consumers call `synth_backend::wcet_compose`)
348/// resolves each function's direct call sites against the whole module and emits the
349/// final [`WcetFunction`] (a composed bound, or a propagated/recursion/indirect
350/// decline).
351///
352/// Splitting the pass in two keeps composition a PURE function over already-decided
353/// per-function facts: `own_cycles` already prices every non-call instruction
354/// (including each `BL`'s branch overhead) at its proven execution count, so the
355/// composed total is `own_cycles + Σ_site multiplier_site × callee_total` — the
356/// per-site multiplier makes a call inside a proven loop sound by construction.
357#[derive(Debug, Clone, PartialEq, Eq)]
358pub enum WcetIntermediate {
359 /// The function declines for a reason INDEPENDENT of composition (an unproven
360 /// loop, an internal looped expansion, an unsupported core, an unresolved label
361 /// branch, an indirect call, or an unmodeled op). Carried straight through to a
362 /// [`WcetFunction::Declined`]; composition never rescues these.
363 Declined {
364 name: String,
365 reason: WcetDecline,
366 hint_rejections: Vec<WcetHintRejection>,
367 },
368 /// The function's own body is bounded; its final bound depends only on resolving
369 /// the recorded direct call sites against the module's other functions.
370 Composable {
371 name: String,
372 /// The summed worst-case cost of every instruction in the final stream
373 /// (each priced at its documented worst case × its proven execution-count
374 /// multiplier), INCLUDING each direct `BL`'s branch overhead. The callee
375 /// bodies are added by the composer via `call_sites`.
376 own_cycles: u64,
377 /// Number of ARM instructions summed (diagnostic, carried to the bound).
378 instr_count: usize,
379 /// The direct call sites to resolve at compose time.
380 call_sites: Vec<WcetCallSite>,
381 /// Proven loops inside this function (carried to the bound unchanged).
382 loops: Vec<WcetLoopBound>,
383 /// Hints rejected while analyzing this function (carried to the bound).
384 hint_rejections: Vec<WcetHintRejection>,
385 },
386}
387
388impl WcetIntermediate {
389 /// The compiled function name this intermediate is for.
390 pub fn name(&self) -> &str {
391 match self {
392 WcetIntermediate::Declined { name, .. } | WcetIntermediate::Composable { name, .. } => {
393 name
394 }
395 }
396 }
397}
398
399/// The parsed `--wcet-hints` file (`synth-wcet-hints-v1`) — an UNTRUSTED oracle
400/// input (#778 phase 2, the scry integration seam). Per function, an ordered
401/// array of claimed loop-trip-count upper bounds, matched to loops by ascending
402/// head offset (entry N = N-th loop head in the function; `null` skips a loop).
403/// Every entry is soundly CHECKED before use: synth re-derives the loop's trip
404/// count from its own induction proof and consumes the hint only when the
405/// derived count is ≤ the hint. A wrong or unverifiable hint is rejected with a
406/// machine reason ([`WcetHintReject`]) — never trusted into a bound.
407#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
408pub struct WcetHints {
409 /// Must equal [`HINTS_SCHEMA`].
410 pub schema: String,
411 /// Per-function hint arrays, keyed by the compiled function name.
412 #[serde(default)]
413 pub functions: std::collections::BTreeMap<String, WcetFunctionHints>,
414}
415
416/// Per-function loop-bound hints.
417#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
418pub struct WcetFunctionHints {
419 /// Claimed trip-count upper bounds, one per loop in ascending-head-offset
420 /// order; `null` leaves that loop unhinted.
421 #[serde(default)]
422 pub loop_bounds: Vec<Option<u64>>,
423}
424
425/// The full `synth-wcet-v1` sidecar: schema header, precondition, and per-function
426/// bounds/declines.
427#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
428pub struct WcetReport {
429 /// Schema version (`synth-wcet-v1`).
430 pub schema: String,
431 /// The compiled module name (for diagnostics).
432 pub module: String,
433 /// The core class the cycle table is written for (e.g. `"cortex-m4"`). The
434 /// bound is CONDITIONAL on this core.
435 pub core_class: String,
436 /// Assumed instruction-memory wait states (0 for the sound zero-wait table).
437 pub wait_states: u32,
438 /// Human statement of the memory precondition the bound holds under.
439 pub memory_assumption: String,
440 /// Per-function bound or decline. Complete: one entry per compiled function.
441 pub functions: Vec<WcetFunction>,
442}
443
444impl WcetReport {
445 /// Start an empty report for `module`, targeting `core_class` under the sound
446 /// zero-wait precondition.
447 pub fn new(module: impl Into<String>, core_class: impl Into<String>) -> Self {
448 WcetReport {
449 schema: SCHEMA.to_string(),
450 module: module.into(),
451 core_class: core_class.into(),
452 wait_states: 0,
453 memory_assumption:
454 "zero-wait-state instruction memory (flash accelerator / I-cache hit); \
455 in-order single-issue pipeline; documented per-instruction worst-case cycles"
456 .to_string(),
457 functions: Vec::new(),
458 }
459 }
460
461 /// Serialize to pretty JSON.
462 pub fn to_json(&self) -> serde_json::Result<String> {
463 serde_json::to_string_pretty(self)
464 }
465
466 /// Resolve the sidecar path (`<output>.wcet.json`) next to the ELF output.
467 pub fn sidecar_path(output: &std::path::Path) -> std::path::PathBuf {
468 let mut s = output.as_os_str().to_os_string();
469 s.push(".wcet.json");
470 std::path::PathBuf::from(s)
471 }
472}
473
474#[cfg(test)]
475mod tests {
476 use super::*;
477
478 #[test]
479 fn bounded_and_declined_roundtrip() {
480 let mut r = WcetReport::new("m", "cortex-m4");
481 r.functions.push(WcetFunction::Bounded {
482 name: "leaf".into(),
483 cycles: 42,
484 instr_count: 7,
485 loops: Vec::new(),
486 hint_rejections: Vec::new(),
487 });
488 r.functions
489 .push(WcetFunction::declined("spins", WcetDecline::Loop));
490 let json = r.to_json().unwrap();
491 let back: WcetReport = serde_json::from_str(&json).unwrap();
492 assert_eq!(r, back);
493 // Decline reason is machine-readable and carries a note.
494 assert!(json.contains("\"reason\": \"loop\""));
495 assert!(json.contains("synth-wcet-v1"));
496 }
497
498 #[test]
499 fn sidecar_path_appends_suffix() {
500 let p = WcetReport::sidecar_path(std::path::Path::new("out/app.elf"));
501 assert_eq!(p, std::path::PathBuf::from("out/app.elf.wcet.json"));
502 }
503}