logicaffeine_compile/optimize/mod.rs
1mod dce;
2mod defunctionalize;
3pub(crate) mod dependence;
4pub(crate) mod facts;
5mod fold;
6mod gvn;
7mod inline_leaf;
8mod inline_recursive;
9mod inline_tiny;
10pub(crate) mod iteration;
11pub(crate) mod item_growth;
12pub(crate) mod kinds;
13mod popcount_leaf;
14mod propagate;
15pub(crate) mod purity;
16mod sccp;
17pub(crate) mod sequence;
18mod splice_fuse;
19mod symmetry;
20pub(crate) mod version;
21pub(crate) mod writes;
22pub(crate) use writes::WriteSet;
23pub(crate) mod mentions;
24pub(crate) mod modwrap;
25pub(crate) use mentions::{expr_touches, stmt_touches, use_counts, Mentions};
26mod swap_classes;
27pub(crate) use swap_classes::{swapped_pairs, SwapClasses};
28mod accum_bound;
29mod bound_version;
30pub(crate) mod capture;
31mod closed_form;
32mod ctfe;
33mod divmod_fuse;
34mod float_induction_sr;
35mod int_induction_sr;
36mod licm;
37mod loop_carried_cse;
38mod loop_interchange;
39mod memoize_run;
40mod reg_promote;
41mod specialize_loop;
42pub(crate) use ctfe::ascii_class_masks;
43mod deforest;
44mod ast_build;
45mod divisor_sieve;
46mod fold_fusion;
47mod sort_nest;
48mod trace_memo;
49// Loop unrolling reuses the codegen peephole's counted-loop recognizer, so it
50// rides the same feature gate; the AOT (Rust-emitting) pipeline is its consumer.
51#[cfg(feature = "codegen")]
52mod unroll;
53// Fixed-size float/int Seq scalarization (the interpreter's SROA). Reuses the
54// codegen scalarization detection, so it rides the same feature gate; paired
55// AFTER the run-path unroller, which makes every surviving index constant.
56#[cfg(feature = "codegen")]
57mod scalarize;
58// Affine read-only `Seq` scalarization (the interpreter's analog of the AOT's
59// `codegen::affine_array`): delete a CSR-style offset array built by one affine
60// `Push f(i) to arr` loop and substitute every `item k of arr` read with the
61// closed form `f(k-1)`. Default OFF behind `LOGOS_RUN_AFFINE`; AOT-only feature
62// gate (it rewrites the run-path AST). Runs before `scalarize`, on the array
63// form GVN already proved reload-correct.
64#[cfg(feature = "codegen")]
65mod affine_scalarize;
66// Guard-based loop index-set splitting reuses the same recognizer (its emitted
67// sub-loops must satisfy it to vectorize), so it rides the same gate; AOT-only.
68mod abstract_interp;
69mod affine;
70mod karr;
71#[cfg(feature = "codegen")]
72mod loop_split;
73pub use abstract_interp::{
74 lin_to_rust, oracle_analyze, oracle_analyze_with, oracle_analyze_with_entry_guards,
75 OracleFacts, ScalarKind, VarProvenFacts,
76};
77pub mod bta;
78pub mod effects;
79pub mod egraph;
80pub mod partial_eval;
81pub mod supercompile;
82
83use std::collections::HashMap;
84
85use crate::arena::Arena;
86use crate::ast::stmt::{Expr, Stmt};
87use crate::intern::{Interner, Symbol};
88use crate::optimization::{
89 admits_pinned, BackendOptimizationTrace, FiredOptimizations, HotswapConfig, Opt,
90 OptimizationBackend, OptimizationConfig, OptimizationDecline, OptimizationFallback, Pin, Tier,
91};
92
93thread_local! {
94 /// The optimization config for the CURRENT compile, consulted by codegen and
95 /// the VM compiler for their per-emit toggle decisions (e.g. emit
96 /// `get_unchecked` vs a checked index). It is set ONCE at each compile entry
97 /// (`codegen_program`, `optimize_for_run`) from the explicitly-threaded
98 /// `OptimizationConfig`; any path that does not set it sees the all-on
99 /// default (the prior, fully-optimized behaviour). This is the single
100 /// replacement for the ~16 scattered `std::env::var("LOGOS_*")` reads codegen
101 /// and the VM used to perform — one controlled per-compile source, not
102 /// ambient process state.
103 static ACTIVE_CONFIG: std::cell::Cell<OptimizationConfig> =
104 std::cell::Cell::new(OptimizationConfig::all_on());
105}
106
107/// Record the optimization config for the current compile. Call at every compile
108/// entry (codegen / VM) so the deep codegen + VM toggle reads see it.
109pub fn set_active_config(cfg: OptimizationConfig) {
110 ACTIVE_CONFIG.with(|c| c.set(cfg));
111}
112
113/// Whether `a` and `b` are the same expression, written alike: one literal, one name, one operator over the same
114/// operands, one read of the same item. Syntax only: whether the two evaluate alike where they stand is the
115/// caller's question, since a write between them can change what a read sees.
116pub(crate) fn same_expr(a: &crate::ast::stmt::Expr, b: &crate::ast::stmt::Expr) -> bool {
117 use crate::ast::stmt::Expr;
118 match (a, b) {
119 (Expr::Literal(x), Expr::Literal(y)) => x == y,
120 (Expr::Identifier(x), Expr::Identifier(y)) => x == y,
121 (
122 Expr::BinaryOp {
123 op: o1,
124 left: l1,
125 right: r1,
126 },
127 Expr::BinaryOp {
128 op: o2,
129 left: l2,
130 right: r2,
131 },
132 ) => o1 == o2 && same_expr(l1, l2) && same_expr(r1, r2),
133 (Expr::Not { operand: x }, Expr::Not { operand: y }) => same_expr(x, y),
134 (
135 Expr::Index {
136 collection: c1,
137 index: i1,
138 },
139 Expr::Index {
140 collection: c2,
141 index: i2,
142 },
143 ) => same_expr(c1, c2) && same_expr(i1, i2),
144 (Expr::Length { collection: x }, Expr::Length { collection: y }) => same_expr(x, y),
145 _ => false,
146 }
147}
148
149thread_local! {
150 /// The functions defunctionalization lifted out of closures: function values the program wrote, whose
151 /// integers every tier keeps exact as it keeps a closure's. Cleared at optimizer entry (symbols are reused
152 /// across programs on a thread).
153 static LIFTED_CLOSURES: std::cell::RefCell<std::collections::HashSet<crate::intern::Symbol>> =
154 std::cell::RefCell::new(std::collections::HashSet::new());
155}
156
157/// Forget the lifted closures (call at optimizer entry).
158pub(crate) fn clear_lifted_closures() {
159 LIFTED_CLOSURES.with(|s| s.borrow_mut().clear());
160}
161
162/// Record `f` as a function lifted out of a closure.
163pub(crate) fn mark_lifted_closure(f: crate::intern::Symbol) {
164 LIFTED_CLOSURES.with(|s| {
165 s.borrow_mut().insert(f);
166 });
167}
168
169/// Was `f` lifted out of a closure by defunctionalization?
170pub fn is_lifted_closure(f: crate::intern::Symbol) -> bool {
171 LIFTED_CLOSURES.with(|s| s.borrow().contains(&f))
172}
173
174/// The current compile's optimization config (all-on if unset).
175pub fn active_config() -> OptimizationConfig {
176 ACTIVE_CONFIG.with(|c| c.get())
177}
178
179thread_local! {
180 /// When `Some`, an optimization-firing trace is active for the current
181 /// compile: each optimization records (via [`mark_fired`]) the moment it
182 /// actually fires. `None` (the default) means no trace — [`mark_fired`] is
183 /// a no-op and the change-detection in [`run_traced`] is skipped, so the
184 /// normal compile path pays nothing. Opt-in, set once per traced compile by
185 /// [`begin_fired_trace`]; lives on the same thread that runs both the
186 /// optimizer and codegen, so codegen-time marks are recorded too.
187 static FIRED: std::cell::Cell<Option<crate::optimization::OptBits>> = const { std::cell::Cell::new(None) };
188
189 /// The PRECEDENCE decisions recorded during the current trace: each
190 /// `(winner, loser)` pair is a spot where the code chose `winner` and skipped
191 /// `loser` for an instance (the conflict the optimization SYSTEM resolves).
192 /// `None` when no trace is active, so [`mark_preempted`] is then a no-op and
193 /// the normal compile path pays nothing. Shares the trace lifetime with
194 /// [`FIRED`] — both reset by [`begin_fired_trace`].
195 static PREEMPTED: std::cell::RefCell<Option<Vec<(Opt, Opt)>>> =
196 const { std::cell::RefCell::new(None) };
197
198 /// Stage-separated evidence layered over the legacy union above. These are
199 /// populated only by `begin_backend_trace`; ordinary compilation and the
200 /// original fired-trace API retain their previous single-bitset behavior.
201 static TRACE_BACKEND: std::cell::Cell<Option<OptimizationBackend>> =
202 const { std::cell::Cell::new(None) };
203 static TRACE_STAGE: std::cell::Cell<TraceStage> =
204 const { std::cell::Cell::new(TraceStage::Optimizer) };
205 static OPTIMIZER_FIRED: std::cell::Cell<Option<crate::optimization::OptBits>> =
206 const { std::cell::Cell::new(None) };
207 static LOWERING_FIRED: std::cell::Cell<Option<crate::optimization::OptBits>> =
208 const { std::cell::Cell::new(None) };
209 static TRACE_DECLINES: std::cell::RefCell<Option<Vec<OptimizationDecline>>> =
210 const { std::cell::RefCell::new(None) };
211 static TRACE_FALLBACKS: std::cell::RefCell<Option<Vec<OptimizationFallback>>> =
212 const { std::cell::RefCell::new(None) };
213}
214
215#[derive(Clone, Copy)]
216enum TraceStage {
217 Optimizer,
218 Lowering,
219}
220
221/// Begin recording which optimizations fire AND which they preempt for the
222/// current compile. Resets both accumulators; pair with [`end_fired_trace`] /
223/// [`end_preempted_trace`].
224pub fn begin_fired_trace() {
225 FIRED.with(|f| f.set(Some(crate::optimization::OptBits::EMPTY)));
226 PREEMPTED.with(|p| *p.borrow_mut() = Some(Vec::new()));
227}
228
229/// Begin a stage-separated trace for one concrete backend. The legacy `FIRED`
230/// union is opened too, preserving `## Require` and existing tooling exactly.
231pub fn begin_backend_trace(backend: OptimizationBackend) {
232 begin_fired_trace();
233 TRACE_BACKEND.with(|b| b.set(Some(backend)));
234 TRACE_STAGE.with(|s| s.set(TraceStage::Optimizer));
235 OPTIMIZER_FIRED.with(|f| f.set(Some(crate::optimization::OptBits::EMPTY)));
236 LOWERING_FIRED.with(|f| f.set(Some(crate::optimization::OptBits::EMPTY)));
237 TRACE_DECLINES.with(|f| *f.borrow_mut() = Some(Vec::new()));
238 TRACE_FALLBACKS.with(|f| *f.borrow_mut() = Some(Vec::new()));
239}
240
241/// Close a stage-separated trace. Always clears every accumulator, including
242/// after a failed compile, so a later compile on the same thread starts clean.
243pub fn end_backend_trace() -> Option<BackendOptimizationTrace> {
244 let backend = TRACE_BACKEND.with(|b| b.take());
245 let optimizer = OPTIMIZER_FIRED.with(|f| f.take().map(FiredOptimizations::from_bits));
246 let lowering = LOWERING_FIRED.with(|f| f.take().map(FiredOptimizations::from_bits));
247 let declines = TRACE_DECLINES.with(|f| f.borrow_mut().take().unwrap_or_default());
248 let fallbacks = TRACE_FALLBACKS.with(|f| f.borrow_mut().take().unwrap_or_default());
249 TRACE_STAGE.with(|s| s.set(TraceStage::Optimizer));
250 let _ = end_fired_trace();
251 let _ = end_preempted_trace();
252 backend.map(|backend| BackendOptimizationTrace {
253 backend,
254 optimizer: optimizer.unwrap_or_default(),
255 lowering: lowering.unwrap_or_default(),
256 declines,
257 fallbacks,
258 })
259}
260
261struct TraceStageGuard(TraceStage);
262
263impl Drop for TraceStageGuard {
264 fn drop(&mut self) {
265 TRACE_STAGE.with(|s| s.set(self.0));
266 }
267}
268
269/// Attribute every `mark_fired` in `f` to backend lowering rather than the
270/// shared optimizer. Outside a backend trace this is a zero-behavior wrapper.
271pub fn with_backend_lowering<T>(f: impl FnOnce() -> T) -> T {
272 let previous = TRACE_STAGE.with(|s| {
273 let previous = s.get();
274 if TRACE_BACKEND.with(|b| b.get().is_some()) {
275 s.set(TraceStage::Lowering);
276 }
277 previous
278 });
279 let _guard = TraceStageGuard(previous);
280 f()
281}
282
283/// Record an explicit backend fallback. Outside a backend trace this is a
284/// no-op, so production compilation pays neither allocation nor formatting.
285pub fn mark_backend_fallback(to: OptimizationBackend, reason: impl Into<String>) {
286 let Some(from) = TRACE_BACKEND.with(|b| b.get()) else {
287 return;
288 };
289 TRACE_FALLBACKS.with(|f| {
290 if let Some(fallbacks) = f.borrow_mut().as_mut() {
291 fallbacks.push(OptimizationFallback {
292 from,
293 to,
294 reason: reason.into(),
295 });
296 }
297 });
298}
299
300/// Record that the current backend deliberately declined one optimization.
301/// Outside a backend trace this is a no-op. Duplicate decisions are collapsed
302/// so a loop containing many equivalent candidates produces one audit reason.
303pub fn mark_backend_decline(opt: Opt, reason: impl Into<String>) {
304 let Some(backend) = TRACE_BACKEND.with(|b| b.get()) else {
305 return;
306 };
307 let reason = reason.into();
308 TRACE_DECLINES.with(|f| {
309 if let Some(declines) = f.borrow_mut().as_mut() {
310 if !declines
311 .iter()
312 .any(|d| d.backend == backend && d.opt == opt && d.reason == reason)
313 {
314 declines.push(OptimizationDecline {
315 backend,
316 opt,
317 reason,
318 });
319 }
320 }
321 });
322}
323
324/// Stop recording and take the fired set (`None` if no trace was active).
325pub fn end_fired_trace() -> Option<FiredOptimizations> {
326 FIRED.with(|f| f.take().map(FiredOptimizations::from_bits))
327}
328
329/// Whether a firing trace is currently active. Gates the cost of the
330/// before/after fingerprint in `run_traced`.
331#[inline]
332pub fn fired_trace_active() -> bool {
333 FIRED.with(|f| f.get().is_some())
334}
335
336/// Record that `opt` fired in the current compile. No-op when no trace is active.
337#[inline]
338pub fn mark_fired(opt: Opt) {
339 FIRED.with(|f| {
340 if let Some(bits) = f.get() {
341 f.set(Some(bits.with(opt)));
342 }
343 });
344 if TRACE_BACKEND.with(|b| b.get().is_some()) {
345 TRACE_STAGE.with(|stage| match stage.get() {
346 TraceStage::Optimizer => OPTIMIZER_FIRED.with(|f| {
347 if let Some(bits) = f.get() {
348 f.set(Some(bits.with(opt)));
349 }
350 }),
351 TraceStage::Lowering => LOWERING_FIRED.with(|f| {
352 if let Some(bits) = f.get() {
353 f.set(Some(bits.with(opt)));
354 }
355 }),
356 });
357 }
358}
359
360/// The file-level optimization-decorator contract (`## No <opt>` / `## Require <opt>`) in ONE
361/// place, so no compile/run/emit tier can silently drop it — the drift that let the decorators
362/// be ignored on the C, VM, wasm and isa paths. Every tier does the same two steps:
363/// `install_decorators(...)` at scope entry, then `gate.verify()?` after compilation.
364#[must_use = "a DecoratorGate must be `.verify()`-ed after codegen so `## Require` is enforced"]
365pub struct DecoratorGate {
366 required: Vec<Opt>,
367 owns_trace: bool,
368}
369
370/// Merge the file's `## No` flags into `env`, install the result as the thread-local active
371/// config (so EVERY backend's `active_config().is_on(..)` gate honors them — AOT codegen, the
372/// VM compiler, the JIT), and open a fired-trace when any `## Require` was declared. Returns
373/// the merged config to hand to the optimizer/codegen plus the gate to `verify()` after the
374/// compile has run. When a trace is already active (a nested compile), the outer gate owns the
375/// verification, so this one is a no-op `verify()`.
376pub fn install_decorators(
377 env: OptimizationConfig,
378 flags: &OptimizationConfig,
379 required: Vec<Opt>,
380) -> (OptimizationConfig, DecoratorGate) {
381 let mut cfg = env.merged(flags);
382 cfg.normalize();
383 set_active_config(cfg);
384 let owns_trace = !required.is_empty() && !fired_trace_active();
385 if owns_trace {
386 begin_fired_trace();
387 }
388 (
389 cfg,
390 DecoratorGate {
391 required,
392 owns_trace,
393 },
394 )
395}
396
397impl DecoratorGate {
398 /// Open a fired-trace for `required` (when non-empty and no trace is already active) WITHOUT
399 /// touching the active config — for the run/VM/wasm/isa seam, where `## No` was already
400 /// installed upstream (`parse_seam`) and only `## Require` remains to enforce. Pair with
401 /// [`verify`](Self::verify) (checks) or [`close`](Self::close) (discards on a prior error).
402 pub fn for_required(required: Vec<Opt>) -> DecoratorGate {
403 let owns_trace = !required.is_empty() && !fired_trace_active();
404 if owns_trace {
405 begin_fired_trace();
406 }
407 DecoratorGate {
408 required,
409 owns_trace,
410 }
411 }
412
413 /// End the trace this gate owns without checking `## Require` — used when compilation already
414 /// failed so its own error propagates instead of a spurious `## Require` message.
415 pub fn close(self) {
416 if self.owns_trace {
417 let _ = end_fired_trace();
418 }
419 }
420
421 /// Close the trace this gate owns and fail loudly on any `## Require <opt>` whose
422 /// optimization did not fire for the program — the honest answer when a backend cannot
423 /// provide a demanded optimization (e.g. `## Require memo` under the VM/wasm tier, where
424 /// memoization is an AOT-codegen construct). Returns the ready-to-surface error message.
425 pub fn verify(self) -> Result<(), String> {
426 if !self.owns_trace {
427 return Ok(());
428 }
429 let fired = end_fired_trace().unwrap_or_default();
430 for opt in &self.required {
431 if !fired.fired(*opt) {
432 let kw = opt.meta().keyword;
433 return Err(format!(
434 "`## Require {kw}` was declared, but the `{kw}` optimization did not \
435 fire for this program — the optimizer found nowhere to apply it. \
436 Rewrite so `{kw}` has something to optimize, or remove the `## Require {kw}`."
437 ));
438 }
439 }
440 Ok(())
441 }
442}
443
444/// Record that `winner` took precedence over `loser` here — the exact spot the
445/// code skips one optimization for another (the conflict, traced at its source,
446/// the same way [`mark_fired`] traces firing). No-op when no trace is active, so
447/// the normal compile path and the benchmark scripts pay nothing. Self-gated on
448/// BOTH being enabled in the current config: a preemption is only meaningful when
449/// the two genuinely contest an instance — so toggling either off cleanly stops
450/// the edge from being reported.
451#[inline]
452pub fn mark_preempted(winner: Opt, loser: Opt) {
453 if !fired_trace_active() {
454 return;
455 }
456 let cfg = active_config();
457 if !cfg.is_on(winner) || !cfg.is_on(loser) {
458 return;
459 }
460 PREEMPTED.with(|p| {
461 if let Some(v) = p.borrow_mut().as_mut() {
462 v.push((winner, loser));
463 }
464 });
465}
466
467/// Stop recording and take the deduplicated set of `(winner, loser)` precedence
468/// decisions made during the trace (empty if no trace was active).
469pub fn end_preempted_trace() -> Vec<(Opt, Opt)> {
470 let mut edges = PREEMPTED.with(|p| p.borrow_mut().take().unwrap_or_default());
471 edges.sort_by_key(|&(w, l)| (w as u8, l as u8));
472 edges.dedup();
473 edges
474}
475
476/// Run an AST pass, recording that `opt` fired iff the pass changed the program
477/// — but only while a trace is active. The AST derives `Debug` (not `PartialEq`),
478/// so a `{:?}` fingerprint is the change signal; it is taken only under a live
479/// trace, so the normal compile path runs the pass exactly as before with no
480/// extra cost. The pass runs exactly once either way (no behavior change).
481#[inline]
482pub(crate) fn run_traced<'a>(
483 opt: Opt,
484 input: Vec<Stmt<'a>>,
485 pass: impl FnOnce(Vec<Stmt<'a>>) -> Vec<Stmt<'a>>,
486) -> Vec<Stmt<'a>> {
487 if !fired_trace_active() {
488 return pass(input);
489 }
490 let before = format!("{input:?}");
491 let out = pass(input);
492 if format!("{out:?}") != before {
493 mark_fired(opt);
494 }
495 out
496}
497
498/// Lighter optimization for Futamura P1: fold + propagate + PE + CTFE.
499/// Skips DCE, abstract interpretation, supercompilation, and structural
500/// transforms (LICM, closed-form, deforestation) that eliminate branches
501/// or restructure control flow. The residual preserves the program's
502/// original control-flow structure while still folding constants,
503/// propagating values, specializing functions, and evaluating CTFE.
504pub fn optimize_for_projection<'a>(
505 stmts: Vec<Stmt<'a>>,
506 expr_arena: &'a Arena<Expr<'a>>,
507 stmt_arena: &'a Arena<Stmt<'a>>,
508 interner: &mut Interner,
509 cfg: &OptimizationConfig,
510) -> Vec<Stmt<'a>> {
511 crate::analysis::callgraph::install_lending_parameters(&stmts);
512 let bta_cache = bta::analyze_with_sccs(&stmts, interner);
513 let mut current = stmts;
514 if cfg.is_on(Opt::Specialize) {
515 let mut variant_count: HashMap<Symbol, usize> = HashMap::new();
516 for _ in 0..16 {
517 let folded = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
518 let propagated = propagate::propagate_stmts(folded, expr_arena, stmt_arena, interner);
519 let (specialized, changes) = partial_eval::specialize_stmts_with_state(
520 propagated,
521 expr_arena,
522 stmt_arena,
523 interner,
524 &mut variant_count,
525 Some(&bta_cache),
526 );
527 current = specialized;
528 if changes == 0 {
529 break;
530 }
531 }
532 }
533 if cfg.is_on(Opt::Comptime) {
534 current = ctfe::ctfe_stmts(current, expr_arena, stmt_arena, interner);
535 current = ctfe::tableize_stmts(current, expr_arena, stmt_arena, interner);
536 }
537 fold::fold_stmts(current, expr_arena, stmt_arena, interner)
538}
539
540/// The RUN-PATH pipeline (EXODIA D1): the Futamura residual — fold,
541/// propagate, polyvariant PE, CTFE, GVN, LICM, closed-form, deforestation,
542/// interval analysis, DCE — everything except supercompilation (whose
543/// driving cost is unbounded; it stays AOT-only). Budgeted: programs beyond
544/// the statement gate run raw, and `LOGOS_RUN_OPT=0` kills the pass
545/// entirely. Optimizer time lands inside the measured run, so the budget is
546/// part of the contract.
547pub fn optimize_for_run<'a>(
548 stmts: Vec<Stmt<'a>>,
549 expr_arena: &'a Arena<Expr<'a>>,
550 stmt_arena: &'a Arena<Stmt<'a>>,
551 interner: &mut Interner,
552 cfg: &OptimizationConfig,
553) -> Vec<Stmt<'a>> {
554 // The un-tiered entry point is `Tier::T3`: every admitted opt runs, so with an
555 // all-on config this is today's whole-program pipeline, bit-for-bit (HOTSWAP §2).
556 optimize_for_run_tiered(
557 stmts,
558 expr_arena,
559 stmt_arena,
560 interner,
561 cfg,
562 &HotswapConfig::default(),
563 Tier::T3,
564 )
565}
566
567/// How many partial-evaluation fixpoint iterations to pay for. `Tier::T3` runs the
568/// full 16-iteration fixpoint (PE-full); `Tier::T2` runs a capped 4 (PE-light) to feed
569/// the Medium passes folded/specialized code without the full tax. Below T2 the
570/// Specialize pass is not admitted at all (it is `Medium`), so the cap is unused. A
571/// `## Tier specialize <eager|t..>` pin brings PE forward AND gives it the full
572/// fixpoint ("ignore its cost", HOTSWAP §8).
573fn pe_iters(hs: &HotswapConfig, tier: Tier) -> usize {
574 if matches!(hs.pin(Opt::Specialize), Some(Pin::Eager) | Some(Pin::At(_))) {
575 return 16;
576 }
577 match tier {
578 Tier::T0 | Tier::T1 => 0,
579 Tier::T2 => 4,
580 Tier::T3 => 16,
581 }
582}
583
584/// The run-path optimizer, gated by the unit's hotness `tier` (HOTSWAP §4). Every
585/// pass runs in the SAME order as the un-tiered pipeline; `tier` decides WHICH passes
586/// run (via [`admits_pinned`], a single cost comparison, with `hs`'s per-opt pins
587/// applied) and how many PE-fixpoint iterations to pay for. `Tier::T3` with an all-on
588/// config and no pins reproduces [`optimize_for_run`] exactly — the compatibility +
589/// soundness anchor.
590pub fn optimize_for_run_tiered<'a>(
591 stmts: Vec<Stmt<'a>>,
592 expr_arena: &'a Arena<Expr<'a>>,
593 stmt_arena: &'a Arena<Stmt<'a>>,
594 interner: &mut Interner,
595 cfg: &OptimizationConfig,
596 hs: &HotswapConfig,
597 tier: Tier,
598) -> Vec<Stmt<'a>> {
599 set_active_config(*cfg);
600 clear_lifted_closures();
601 crate::analysis::callgraph::install_lending_parameters(&stmts);
602 if cfg.is_all_off() || tier == Tier::T0 {
603 return stmts;
604 }
605 const MAX_RUN_OPT_STMTS: usize = 5_000;
606 if stmts.len() > MAX_RUN_OPT_STMTS {
607 return stmts;
608 }
609 let bta_cache = bta::analyze_with_sccs(&stmts, interner);
610 let mut current = stmts;
611 // Range-specialize helper calls before the general inliners erase the
612 // counted-loop context that proves their arguments non-negative. This is
613 // a backend-neutral AST rewrite: the run/VM/JIT family benefits from the
614 // same call-free arithmetic residual as AOT, while the tier/cost gate keeps
615 // it out of cold units.
616 #[cfg(feature = "codegen")]
617 if admits_pinned(cfg, hs, tier, Opt::SpecializeLoop) {
618 current = run_traced(Opt::SpecializeLoop, current, |c| {
619 specialize_loop::specialize_loop_stmts(c, expr_arena, stmt_arena, interner)
620 });
621 }
622 if admits_pinned(cfg, hs, tier, Opt::Inline) {
623 // Tiny pure helpers inline first, so PE/fold/GVN/LICM see straight
624 // arithmetic and the loop regions compile call-free.
625 current = run_traced(Opt::Inline, current, |c| {
626 inline_tiny::inline_tiny_fns(c, expr_arena, stmt_arena, interner)
627 });
628 // Statement-body leaf helpers (iterative gcd shape) fold in next, so
629 // their calling loops compile as one call-free region.
630 current = run_traced(Opt::Inline, current, |c| {
631 inline_leaf::inline_leaf_fns(c, expr_arena, stmt_arena, interner)
632 });
633 }
634 // Sparse conditional constant propagation before the PE fixpoint: prune
635 // dead branches so specialization/fold/GVN see the smaller, no-poison
636 // residual (the branch a proven-constant guard can never take is gone, and
637 // its `Set`s can no longer force a variable to ⊥).
638 if admits_pinned(cfg, hs, tier, Opt::Sccp) {
639 current = run_traced(Opt::Sccp, current, |c| {
640 sccp::sccp_stmts(c, expr_arena, stmt_arena, interner)
641 });
642 }
643 // Loop interchange on the RAW affine nest — before specialization/IntStrength
644 // linearize the indices — reorders an integer commutative-reduction nest to
645 // put the unit-stride access innermost. Bit-identical (integer +/% reduction
646 // is order-invariant) and only toward better locality.
647 if admits_pinned(cfg, hs, tier, Opt::Interchange) {
648 let (c, fired) =
649 loop_interchange::interchange_stmts(current, expr_arena, stmt_arena, interner);
650 current = c;
651 if fired {
652 mark_fired(Opt::Interchange);
653 }
654 }
655 if admits_pinned(cfg, hs, tier, Opt::Specialize) {
656 let mut variant_count: HashMap<Symbol, usize> = HashMap::new();
657 let mut specialized_any = false;
658 let cap = pe_iters(hs, tier);
659 let mut capped_early = false;
660 for i in 0..cap {
661 let folded = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
662 let propagated = propagate::propagate_stmts(folded, expr_arena, stmt_arena, interner);
663 let (specialized, changes) = partial_eval::specialize_stmts_with_state(
664 propagated,
665 expr_arena,
666 stmt_arena,
667 interner,
668 &mut variant_count,
669 Some(&bta_cache),
670 );
671 current = specialized;
672 if changes == 0 {
673 break;
674 }
675 specialized_any = true;
676 // The fixpoint had not converged by the tier's iteration budget.
677 capped_early = i + 1 == cap;
678 }
679 if specialized_any {
680 mark_fired(Opt::Specialize);
681 }
682 // PE-light (T2) stops the fixpoint early, which can leave the residual not
683 // fold-stable; the Medium passes below (loop-carried CSE, GVN, closed-form)
684 // assume canonical sub-expressions. Re-normalize after a capped-early exit so
685 // they fire on the same shape they would at T3. T3 runs to convergence (its
686 // last iteration specialized 0 changes on folded+propagated input), so it is
687 // already canonical and stays byte-for-byte today's pipeline.
688 if capped_early && tier < Tier::T3 {
689 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
690 current = propagate::propagate_stmts(current, expr_arena, stmt_arena, interner);
691 }
692 }
693 if admits_pinned(cfg, hs, tier, Opt::Comptime) {
694 current = run_traced(Opt::Comptime, current, |c| {
695 let c = ctfe::ctfe_stmts(c, expr_arena, stmt_arena, interner);
696 ctfe::tableize_stmts(c, expr_arena, stmt_arena, interner)
697 });
698 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
699 }
700 // Loop-carried CSE: hoist a squared term that a `While`'s escape guard
701 // computes over the freshly assigned loop iterate and the next iteration's
702 // body recomputes over the same value (mandelbrot's `zr*zr` / `zi*zi`) into a
703 // fresh per-iteration temp — computed ONCE just after the operand's `Set`,
704 // substituted into both the guard and the body recomputation. Runs after the
705 // mask&1 PE fixpoint (so identical sub-expressions are already canonical) and
706 // before GVN; fold+propagate refold the substituted forms. PROMOTED 2026-06-21:
707 // default ON (kill-switch LOGOS_RUN_LCSE=0) — mandelbrot -14% on the faithful
708 // interleaved A/B (2.40x->2.07x Node), 30/30 benchmarks bit-identical, no regress.
709 if admits_pinned(cfg, hs, tier, Opt::LoopCse) {
710 let (c, fired) =
711 loop_carried_cse::loop_carried_cse_stmts(current, expr_arena, stmt_arena, interner);
712 current = c;
713 if fired {
714 mark_fired(Opt::LoopCse);
715 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
716 current = propagate::propagate_stmts(current, expr_arena, stmt_arena, interner);
717 }
718 }
719 // U6: float induction-variable strength reduction — replace a per-iteration
720 // `c1*k + c2` (a multiply + int->float cvtsi2sd) with a guarded incremental
721 // float accumulator. PROMOTED 2026-06-21: default ON (kill-switch
722 // LOGOS_RUN_FLOATSR=0) — pi_leibniz -31.7% on the faithful A/B (geomean
723 // 0.891->0.879), bit-identical, no regression (the runtime trip-count guard
724 // keeps it bit-identical for ALL inputs). Found via the stencil investigation.
725 if admits_pinned(cfg, hs, tier, Opt::FloatStrength) {
726 let (c, fired) =
727 float_induction_sr::float_induction_sr_stmts(current, expr_arena, stmt_arena, interner);
728 current = c;
729 if fired {
730 mark_fired(Opt::FloatStrength);
731 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
732 current = propagate::propagate_stmts(current, expr_arena, stmt_arena, interner);
733 }
734 }
735 // Integer induction strength reduction: a counted loop's affine index
736 // `coeff*j + base` (base loop-invariant) becomes a seeded accumulator
737 // advanced by `coeff*step`, removing the per-iteration multiply. Runs after
738 // float strength reduction (its integer sibling) and BEFORE GVN, so the
739 // linearized single-identifier indices are what GVN value-numbers. Exact —
740 // no runtime guard (integer arithmetic promotes to BigInt identically).
741 if admits_pinned(cfg, hs, tier, Opt::IntStrength) {
742 // Run path: no codegen tiler downstream, so reduce every affine index
743 // (the interpreter has no cache-tiling to defer to).
744 let (c, fired) = int_induction_sr::int_induction_sr_stmts(
745 current, expr_arena, stmt_arena, interner, false,
746 );
747 current = c;
748 if fired {
749 mark_fired(Opt::IntStrength);
750 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
751 current = propagate::propagate_stmts(current, expr_arena, stmt_arena, interner);
752 }
753 }
754 // Register-promote an invariant-indexed RMW element (store-to-load
755 // forwarding across the loop) BEFORE GVN, so GVN never restructures the
756 // `item IDX of C` read/write pair this pass recognizes. Its `loads_equal`
757 // alias check benefits from IntStrength having just linearized the index.
758 if admits_pinned(cfg, hs, tier, Opt::RegPromote) {
759 let (c, fired) = reg_promote::reg_promote_stmts(current, expr_arena, stmt_arena, interner);
760 current = c;
761 if fired {
762 mark_fired(Opt::RegPromote);
763 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
764 current = propagate::propagate_stmts(current, expr_arena, stmt_arena, interner);
765 }
766 }
767 if admits_pinned(cfg, hs, tier, Opt::Cse) {
768 current = run_traced(Opt::Cse, current, |c| {
769 gvn::cse_stmts(c, expr_arena, stmt_arena, interner)
770 });
771 }
772 // Run-path array scalarization (the interpreter's SROA): fully unroll the
773 // constant-trip loops over a fixed-size float/int Seq, then replace the Seq
774 // with N scalar locals so every `item k of arr` is a register-resident
775 // variable read instead of a bounds-checked heap load. Unroll alone was a
776 // measured loss (a bigger region over the same loads); the scalarize half is
777 // what removes them. PROMOTED 2026-06-21: default ON (kill-switch
778 // LOGOS_RUN_SCALARIZE=0) — nbody -17% on the faithful interleaved A/B,
779 // 30/30 benchmarks bit-identical, no benchmark regressed.
780 //
781 // It runs AFTER GVN deliberately: GVN's value numbering is reload-correct on
782 // the array form (it never CSEs an `item k of arr` read across a write), but
783 // it would unsoundly CSE the loop-carried SCALAR reads this pass introduces
784 // across the step loop's mutations. Sequencing scalarization after GVN keeps
785 // GVN on the sound array form; the structural passes below (LICM, closed-form,
786 // deforestation, interval analysis, DCE) are reload-correct on the scalar form.
787 // Affine read-only array scalarization: delete a CSR-style offset array
788 // (graph_bfs's `adjStarts`, built by one affine `Push i*5 to adjStarts`
789 // loop) and substitute every `item k of arr` random heap load with the
790 // closed form `5*(k-1)` — C's `v*5` shift. Runs on the ARRAY form, BEFORE
791 // unroll/scalarize, so GVN (which already ran) stayed reload-correct over
792 // the original reads. fold+propagate after it collapse the substituted
793 // closed forms. PROMOTED 2026-06-21: default ON (kill-switch
794 // LOGOS_RUN_AFFINE=0) — graph_bfs -20% on the faithful interleaved A/B
795 // (2.86x->2.29x Node), 30/30 benchmarks bit-identical, no benchmark regressed.
796 #[cfg(feature = "codegen")]
797 if admits_pinned(cfg, hs, tier, Opt::Affine) {
798 let (a, ca) =
799 affine_scalarize::affine_scalarize_seqs(current, expr_arena, stmt_arena, interner);
800 current = a;
801 if ca {
802 mark_fired(Opt::Affine);
803 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
804 current = propagate::propagate_stmts(current, expr_arena, stmt_arena, interner);
805 }
806 }
807 #[cfg(feature = "codegen")]
808 {
809 let mut changed = false;
810 if admits_pinned(cfg, hs, tier, Opt::Unroll) {
811 let (u, c1) = unroll::unroll_stmts_run(current, expr_arena, stmt_arena, interner);
812 current = u;
813 if c1 {
814 mark_fired(Opt::Unroll);
815 }
816 changed |= c1;
817 }
818 if admits_pinned(cfg, hs, tier, Opt::Scalarize) {
819 let (s, c2) = scalarize::scalarize_seqs(current, expr_arena, stmt_arena, interner);
820 current = s;
821 if c2 {
822 mark_fired(Opt::Scalarize);
823 }
824 changed |= c2;
825 }
826 if changed {
827 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
828 current = propagate::propagate_stmts(current, expr_arena, stmt_arena, interner);
829 }
830 }
831 if admits_pinned(cfg, hs, tier, Opt::LoopHoist) {
832 current = run_traced(Opt::LoopHoist, current, |c| {
833 licm::licm_stmts_run(c, expr_arena, stmt_arena, interner)
834 });
835 }
836 if admits_pinned(cfg, hs, tier, Opt::ClosedForm) {
837 current = run_traced(Opt::ClosedForm, current, |c| {
838 closed_form::closed_form_stmts(c, expr_arena, stmt_arena, interner)
839 });
840 }
841 // Run-path memoization: cache a pure single-arg self-recursive function in a
842 // module-level `Map` global (the interpreter/VM analog of the AOT thread-local
843 // cache). AFTER ClosedForm, so a function ClosedForm already solved has no
844 // self-calls left and this declines — the natural ClosedForm-preempts-Memo.
845 if admits_pinned(cfg, hs, tier, Opt::Memo) {
846 let (c, fired) = memoize_run::memoize_run_stmts(current, expr_arena, stmt_arena, interner);
847 current = c;
848 if fired {
849 mark_fired(Opt::Memo);
850 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
851 current = propagate::propagate_stmts(current, expr_arena, stmt_arena, interner);
852 }
853 }
854 if admits_pinned(cfg, hs, tier, Opt::Fuse) {
855 current = run_traced(Opt::Fuse, current, |c| {
856 deforest::deforest_stmts(c, expr_arena, stmt_arena, interner)
857 });
858 }
859 if admits_pinned(cfg, hs, tier, Opt::Oracle) {
860 current = run_traced(Opt::Oracle, current, |c| {
861 abstract_interp::abstract_interp_stmts(c, expr_arena, stmt_arena)
862 });
863 }
864 if admits_pinned(cfg, hs, tier, Opt::DeadCode) {
865 current = run_traced(Opt::DeadCode, current, |c| {
866 dce::eliminate_dead_code(c, stmt_arena, expr_arena)
867 });
868 }
869 // Bounded recursion inlining (recursion unrolling) — the lone AOT pass we
870 // also run on the live run path. It flattens a self-recursive function's
871 // own loop-interleaved body k levels deep (the inline LLVM refuses, gcc
872 // -O3 performs), cutting the per-call VM overhead that dominates the
873 // recursion benchmarks. It MUST run LAST: placed before the fixpoint
874 // passes it re-analyses k enlarged clones and the optimizer cost balloons
875 // ~30×, so it runs on the already-optimized residual exactly like the AOT
876 // pipeline (each clone is pre-optimized). It defers to TCE/accumulator by
877 // construction — it fires only on loop-interleaved recursion, never on the
878 // return-position shape `tail_call` later rewrites to a constant-stack
879 // loop. Optimizer time lands inside the measured run, so it is gated twice:
880 // the mask bit (256), and a tight statement budget (`MAX_RUN_INLINE_STMTS`)
881 // below the broad run-opt gate — the recursive kernels are tiny source
882 // programs, while a large body's inlining cost would outweigh the savings.
883 const MAX_RUN_INLINE_STMTS: usize = 1_500;
884 if admits_pinned(cfg, hs, tier, Opt::Unfold) && current.len() <= MAX_RUN_INLINE_STMTS {
885 let unrolled = run_traced(Opt::Unfold, current, |c| {
886 inline_recursive::inline_recursive_fns_run(c, expr_arena, stmt_arena, interner)
887 });
888 // Collapse the argument-binding temps the splice introduces
889 // (`__rN_n = n`), exactly as the AOT pipeline does after this pass.
890 let folded = fold::fold_stmts(unrolled, expr_arena, stmt_arena, interner);
891 let propagated = propagate::propagate_stmts(folded, expr_arena, stmt_arena, interner);
892 current = dce::eliminate_dead_code(propagated, stmt_arena, expr_arena);
893 }
894 current
895}
896
897/// The AOT optimizer — ONE pipeline. The Futamura residual (fold, propagate,
898/// polyvariant PE, CTFE) then the ARCHITECT: equality saturation over a
899/// kernel-certified e-graph, Oracle facts gating the conditional rewrites
900/// (value facts suppressed for loop-mutated variables — see `egraph::convert`);
901/// then defunctionalization, deforestation, interval analysis, DCE, and
902/// supercompilation. GVN/LICM/closed-form STILL run after the e-graph until it
903/// subsumes their cross-statement and loop-recurrence reach (the EG waves).
904/// Memoize the pure single-argument self-recursive functions of an already-optimized program for a
905/// lowering that has no native memoization construct. Rust emits its own cache during codegen; direct C
906/// and bytecode-derived backends instead consume this explicit Map-based residual. Keeping the transform
907/// here makes `Memo` one optimization with one eligibility rule and firing trace across those backends.
908pub fn memoize_for_explicit_lowering<'a>(
909 stmts: Vec<Stmt<'a>>,
910 expr_arena: &'a Arena<Expr<'a>>,
911 stmt_arena: &'a Arena<Stmt<'a>>,
912 interner: &mut Interner,
913 cfg: &OptimizationConfig,
914) -> Vec<Stmt<'a>> {
915 if !cfg.is_on(Opt::Memo) {
916 return stmts;
917 }
918 let (current, fired) = memoize_run::memoize_run_stmts(stmts, expr_arena, stmt_arena, interner);
919 if !fired {
920 return current;
921 }
922 mark_fired(Opt::Memo);
923 let current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
924 propagate::propagate_stmts(current, expr_arena, stmt_arena, interner)
925}
926
927pub fn optimize_program<'a>(
928 stmts: Vec<Stmt<'a>>,
929 expr_arena: &'a Arena<Expr<'a>>,
930 stmt_arena: &'a Arena<Stmt<'a>>,
931 interner: &mut Interner,
932 cfg: &OptimizationConfig,
933) -> Vec<Stmt<'a>> {
934 set_active_config(*cfg);
935 clear_lifted_closures();
936 crate::analysis::callgraph::install_lending_parameters(&stmts);
937 // De-desugar FIRST: under reference semantics the parser's place-write
938 // Splices fuse back to the direct nested writes every downstream pass
939 // (BTA, borrow-hoist, bounds elision) pattern-matches.
940 let stmts = splice_fuse::fuse_place_splices(stmts, expr_arena, stmt_arena, interner);
941 // Fold/build fusion on the program as written: a consumer of a datatype applied to what a builder builds of it
942 // compiles to one function that never builds it, before any pass inlines or specializes either function.
943 let stmts = if cfg.is_on(Opt::FoldFusion) {
944 let (fused, fired) =
945 fold_fusion::fold_fusion_stmts(stmts, expr_arena, stmt_arena, interner);
946 if fired {
947 mark_fired(Opt::FoldFusion);
948 }
949 fused
950 } else {
951 stmts
952 };
953 // A bubble sort's nest, before any loop pass reshapes it, sorts its window by one heap sort behind a guard.
954 let stmts = if cfg.is_on(Opt::SortNest) {
955 let (sorted, fired) = sort_nest::sort_nest_stmts(stmts, expr_arena, stmt_arena, interner);
956 if fired {
957 mark_fired(Opt::SortNest);
958 }
959 sorted
960 } else {
961 stmts
962 };
963 // A per-number search for a divisor up to its square root reads one sieve of the range, behind a size guard.
964 let stmts = if cfg.is_on(Opt::DivisorSieve) {
965 let (sieved, fired) =
966 divisor_sieve::divisor_sieve_stmts(stmts, expr_arena, stmt_arena, interner);
967 if fired {
968 mark_fired(Opt::DivisorSieve);
969 }
970 sieved
971 } else {
972 stmts
973 };
974 // A pure iteration run from every start of a range stops where it reaches a start already finished.
975 let stmts = if cfg.is_on(Opt::TraceMemo) {
976 let (memo, fired) = trace_memo::trace_memo_stmts(stmts, expr_arena, stmt_arena, interner);
977 if fired {
978 mark_fired(Opt::TraceMemo);
979 }
980 memo
981 } else {
982 stmts
983 };
984 // NOTE: no early tiny-fn inliner here — that is a RUN-PATH device
985 // (optimize_for_run skips supercompile for budget). This AOT pipeline
986 // inlines through supercompile at the end exactly like v1, so the PE
987 // machinery keeps its subjects.
988 let bta_cache = bta::analyze_with_sccs(&stmts, interner);
989 let mut current = stmts;
990 // Loop interchange on the raw affine nest, before the e-graph / IntStrength
991 // touch the indices: reorder an integer commutative-reduction nest toward
992 // the unit-stride-innermost order. Bit-identical and locality-improving only.
993 if cfg.is_on(Opt::Interchange) {
994 let (c, fired) =
995 loop_interchange::interchange_stmts(current, expr_arena, stmt_arena, interner);
996 current = c;
997 if fired {
998 mark_fired(Opt::Interchange);
999 }
1000 }
1001 if cfg.is_on(Opt::Specialize) {
1002 let mut variant_count: HashMap<Symbol, usize> = HashMap::new();
1003 let mut specialized_any = false;
1004 for _ in 0..16 {
1005 let folded = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
1006 let propagated = propagate::propagate_stmts(folded, expr_arena, stmt_arena, interner);
1007 let (specialized, changes) = partial_eval::specialize_stmts_with_state(
1008 propagated,
1009 expr_arena,
1010 stmt_arena,
1011 interner,
1012 &mut variant_count,
1013 Some(&bta_cache),
1014 );
1015 current = specialized;
1016 if changes == 0 {
1017 break;
1018 }
1019 specialized_any = true;
1020 }
1021 if specialized_any {
1022 mark_fired(Opt::Specialize);
1023 }
1024 }
1025 if cfg.is_on(Opt::Comptime) {
1026 current = run_traced(Opt::Comptime, current, |c| {
1027 let c = ctfe::ctfe_stmts(c, expr_arena, stmt_arena, interner);
1028 ctfe::tableize_stmts(c, expr_arena, stmt_arena, interner)
1029 });
1030 }
1031 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
1032 // Sparse conditional constant propagation: fold constants and prune
1033 // unreachable branches in one lattice sweep — the reachability half the
1034 // e-graph does not do. Runs on the folded PE residual, BEFORE the Architect,
1035 // so a dead branch (and any `Set` inside it that would otherwise poison a
1036 // variable) is gone before saturation / GVN / the recurrence passes see it.
1037 if cfg.is_on(Opt::Sccp) {
1038 current = run_traced(Opt::Sccp, current, |c| {
1039 sccp::sccp_stmts(c, expr_arena, stmt_arena, interner)
1040 });
1041 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
1042 current = propagate::propagate_stmts(current, expr_arena, stmt_arena, interner);
1043 }
1044 // Reflection symmetry-breaking: halve a bitmask counting search's first-row
1045 // enumeration (×2 + odd-n middle) when the kernel proves the reflection
1046 // invariance for all n. Runs on the clean specialized entry, before the
1047 // structural passes; the sub-counts it calls still get popcount-leaf +
1048 // recursion unrolling later. Fail-closed (kernel certificate gates it).
1049 if cfg.is_on(Opt::Symmetry) {
1050 current = run_traced(Opt::Symmetry, current, |c| {
1051 symmetry::break_symmetry_stmts(c, expr_arena, stmt_arena, interner)
1052 });
1053 }
1054 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
1055 // Fully unroll small constant-trip loops nested inside hot loops (nbody's
1056 // per-step force loops), then refold/repropagate so the substituted indices
1057 // collapse to constants (`item (3-1) of bx` → `bx[2]`) and the dead counter
1058 // scaffolding is cleaned up. LLVM then SROAs the `[f64; N]` arrays into
1059 // registers and vectorizes the straight-line body — the codegen it already
1060 // produces for top-level constant loops but refuses inside a runtime loop.
1061 #[cfg(feature = "codegen")]
1062 if cfg.is_on(Opt::Unroll) {
1063 let (unrolled, changed) = unroll::unroll_stmts(current, expr_arena, stmt_arena, interner);
1064 current = unrolled;
1065 if changed {
1066 mark_fired(Opt::Unroll);
1067 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
1068 current = propagate::propagate_stmts(current, expr_arena, stmt_arena, interner);
1069 }
1070 }
1071 // Group 4: direct closures lift to first-order functions BEFORE the
1072 // e-graph runs, so the Architect (and every later pass) sees plain
1073 // calls instead of heap closures.
1074 if cfg.is_on(Opt::Defunctionalize) {
1075 current = run_traced(Opt::Defunctionalize, current, |c| {
1076 defunctionalize::defunctionalize_stmts(c, expr_arena, stmt_arena, interner)
1077 });
1078 }
1079 // The Architect saturates every expression under kernel-certified
1080 // rewrites with Oracle-gated conditionals. GVN/LICM/closed-form STAY
1081 // until the e-graph's cross-statement runs (M13's SSA versioning)
1082 // subsume their capabilities — the structural suite pins them, and a
1083 // capability superset is the honest sprint-22 wiring.
1084 // Register-promote an invariant-indexed RMW element BEFORE the Architect:
1085 // the e-graph canonicalizes the `item IDX of C` read/write pair out of the
1086 // shape this pass recognizes, so it must run on the pre-saturation form.
1087 if cfg.is_on(Opt::RegPromote) {
1088 let (c, fired) = reg_promote::reg_promote_stmts(current, expr_arena, stmt_arena, interner);
1089 current = c;
1090 if fired {
1091 mark_fired(Opt::RegPromote);
1092 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
1093 current = propagate::propagate_stmts(current, expr_arena, stmt_arena, interner);
1094 }
1095 }
1096 if cfg.is_on(Opt::Saturate) {
1097 current = run_traced(Opt::Saturate, current, |c| {
1098 egraph::convert::egraph_stmts(c, expr_arena, stmt_arena, interner)
1099 });
1100 }
1101 if cfg.is_on(Opt::Cse) {
1102 current = run_traced(Opt::Cse, current, |c| {
1103 gvn::cse_stmts(c, expr_arena, stmt_arena, interner)
1104 });
1105 }
1106 if cfg.is_on(Opt::LoopHoist) {
1107 current = run_traced(Opt::LoopHoist, current, |c| {
1108 licm::licm_stmts(c, expr_arena, stmt_arena, interner)
1109 });
1110 }
1111 // Integer induction strength reduction on the post-LICM index arithmetic:
1112 // what LICM hoisted as invariant is gone, leaving the `coeff*j + base` form
1113 // this pass folds into an accumulator. Before ClosedForm so its accumulator
1114 // recurrences are visible to the recurrence solver.
1115 if cfg.is_on(Opt::IntStrength) {
1116 // AOT/Rust-codegen path: defer the square matmul nest to the codegen
1117 // tiler (`peephole::try_emit_tiled_inner`), whose L1 cache tiling beats
1118 // removing the index multiply and needs the nest's exact raw shape.
1119 let (c, fired) = int_induction_sr::int_induction_sr_stmts(
1120 current, expr_arena, stmt_arena, interner, true,
1121 );
1122 current = c;
1123 if fired {
1124 mark_fired(Opt::IntStrength);
1125 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
1126 current = propagate::propagate_stmts(current, expr_arena, stmt_arena, interner);
1127 }
1128 }
1129 if cfg.is_on(Opt::ClosedForm) {
1130 current = run_traced(Opt::ClosedForm, current, |c| {
1131 closed_form::closed_form_stmts(c, expr_arena, stmt_arena, interner)
1132 });
1133 }
1134 if cfg.is_on(Opt::Fuse) {
1135 current = run_traced(Opt::Fuse, current, |c| {
1136 deforest::deforest_stmts(c, expr_arena, stmt_arena, interner)
1137 });
1138 }
1139 // Guard-based loop index-set splitting: split a counted loop carrying a
1140 // top-level affine-monotone IV guard into a guard-false prefix (then-block
1141 // dropped → memcpy) and a guard-true suffix (then-block inlined, branch-free
1142 // → vectorizable unconditional load), behind a version guard that keeps the
1143 // original loop for an out-of-range threshold. fold+propagate immediately
1144 // after collapse the version guard / branches where statically resolvable,
1145 // and the suffix's literal-threshold IV init lets abstract_interp re-prove
1146 // the now-unconditional access in range. AOT-only (no SIMD payoff for the
1147 // interpreter), so it is not in optimize_for_run / optimize_for_projection.
1148 #[cfg(feature = "codegen")]
1149 {
1150 current = run_traced(Opt::LoopSplit, current, |c| {
1151 loop_split::loop_split_stmts(c, expr_arena, stmt_arena, interner, cfg)
1152 });
1153 current = fold::fold_stmts(current, expr_arena, stmt_arena, interner);
1154 current = propagate::propagate_stmts(current, expr_arena, stmt_arena, interner);
1155 }
1156 if cfg.is_on(Opt::Oracle) {
1157 current = run_traced(Opt::Oracle, current, |c| {
1158 abstract_interp::abstract_interp_stmts(c, expr_arena, stmt_arena)
1159 });
1160 }
1161 let dced = if cfg.is_on(Opt::DeadCode) {
1162 run_traced(Opt::DeadCode, current, |c| {
1163 dce::eliminate_dead_code(c, stmt_arena, expr_arena)
1164 })
1165 } else {
1166 current
1167 };
1168 let current = if cfg.is_on(Opt::Supercompile) {
1169 run_traced(Opt::Supercompile, dced, |c| {
1170 supercompile::supercompile_stmts(c, expr_arena, stmt_arena, interner)
1171 })
1172 } else {
1173 dced
1174 };
1175 // Popcount-leaf: collapse the second-to-last level of a bitmask counting
1176 // search (`row == n-1`, every remaining bit is one solution) into a single
1177 // `count_ones`. Runs BEFORE inline_recursive so the fast path is carried
1178 // into every unrolled clone. Pure structural rewrite (no kernel).
1179 let current = run_traced(Opt::Popcount, current, |c| {
1180 popcount_leaf::popcount_leaf_stmts(c, expr_arena, stmt_arena, interner, cfg)
1181 });
1182 // Bounded recursive inlining (recursion unrolling) runs LAST: flatten each
1183 // self-recursive function's own body k levels deep — the inline LLVM
1184 // refuses but gcc -O3 performs (the lever that lets compiled-LOGOS
1185 // n-queens match/beat C). Placed after the heavy analyses (e-graph,
1186 // supercompile) so they optimize the ORIGINAL body once and never pay to
1187 // re-analyze the k enlarged copies — each clone is already optimized.
1188 // fold+propagate+DCE then collapse the argument-binding temps the splice
1189 // introduces (`__rN_n = n`).
1190 let unrolled = if cfg.is_on(Opt::Unfold) {
1191 run_traced(Opt::Unfold, current, |c| {
1192 inline_recursive::inline_recursive_fns(c, expr_arena, stmt_arena, interner)
1193 })
1194 } else {
1195 current
1196 };
1197 let folded = fold::fold_stmts(unrolled, expr_arena, stmt_arena, interner);
1198 let propagated = propagate::propagate_stmts(folded, expr_arena, stmt_arena, interner);
1199 // O9 — bound-versioned loop nests (spectral_norm's vectorization): runs
1200 // LAST among the rewriters so nothing rebuilds its proven-raw-marked
1201 // clone nodes before codegen. Versioning is guard-based loop cloning, the
1202 // LoopSplit family; AOT-only like its sibling (the payoff is SIMD).
1203 // Range-aware helper specialization: symbolically inline pure integer helper calls
1204 // (`divModQ`/`divModM`/…) in a counted-accumulator loop under the counter's proven
1205 // `>= 0` range and fold the dead sign branches, turning the function-based term into
1206 // bare arithmetic. Runs FIRST so its inlined output flows through the accumulator
1207 // versioner (guard elision) and div-mod fusion below.
1208 #[cfg(feature = "codegen")]
1209 let propagated = if cfg.is_on(Opt::SpecializeLoop) {
1210 run_traced(Opt::SpecializeLoop, propagated, |c| {
1211 specialize_loop::specialize_loop_stmts(c, expr_arena, stmt_arena, interner)
1212 })
1213 } else {
1214 propagated
1215 };
1216 // Pass 1 — bounded-accumulator overflow-guard elision: proves a hot integer loop
1217 // stays i64-safe once its inputs fit a compile-time bound, versions it, and marks
1218 // the fast branch's arithmetic proven-raw so codegen drops the per-iteration
1219 // overflow guard. Runs BEFORE bound_version so the tighter accumulator bound
1220 // (`n <= 2e9`, marking the GROWING accumulator too) wins over bound_version's
1221 // coarser counter-only split (`n <= 2^62`, which cannot bound a growing sum and so
1222 // leaves its per-iteration guard); bound_version then skips the loop accum_bound
1223 // already versioned (its body arith is all proven-raw) and only splits the fallback.
1224 #[cfg(feature = "codegen")]
1225 let propagated = if cfg.is_on(Opt::AccumBound) {
1226 run_traced(Opt::AccumBound, propagated, |c| {
1227 accum_bound::accum_bound_stmts(c, expr_arena, stmt_arena, interner)
1228 })
1229 } else {
1230 propagated
1231 };
1232 #[cfg(feature = "codegen")]
1233 let propagated = if cfg.is_on(Opt::LoopSplit) {
1234 run_traced(Opt::LoopSplit, propagated, |c| {
1235 bound_version::bound_version_stmts(c, expr_arena, stmt_arena)
1236 })
1237 } else {
1238 propagated
1239 };
1240 // Div-mod fusion: restore the `a/b`+`a%b` CSE that rustc/LLVM won't do — bind the shared
1241 // quotient once and derive the remainder. Runs LAST among the rewriters (after the bounded-
1242 // loop versioners have marked the accumulator fast branch proven-raw) so its rewritten nodes
1243 // inherit those marks and stay bare-i64; AOT-only.
1244 #[cfg(feature = "codegen")]
1245 let propagated = if cfg.is_on(Opt::DivModFuse) {
1246 run_traced(Opt::DivModFuse, propagated, |c| {
1247 divmod_fuse::divmod_fuse_stmts(c, expr_arena, stmt_arena, interner)
1248 })
1249 } else {
1250 propagated
1251 };
1252 if cfg.is_on(Opt::DeadCode) {
1253 run_traced(Opt::DeadCode, propagated, |c| {
1254 dce::eliminate_dead_code(c, stmt_arena, expr_arena)
1255 })
1256 } else {
1257 propagated
1258 }
1259}