Skip to main content

logicaffeine_language/
optimization.rs

1//! The registry of compiler optimization toggles.
2//!
3//! Every optimization the compiler can perform has exactly one row in
4//! [`REGISTRY`], naming it, giving it a human label and a `## No <Keyword>`
5//! decorator keyword, recording which execution paths it touches, whether it
6//! emits `unsafe` Rust, how it trades memory for speed, and its dependencies
7//! and conflicts with other optimizations.
8//!
9//! A live choice of which optimizations are on is an [`OptimizationConfig`] —
10//! an [`OptBits`] set, one bit per [`Opt`]. The default is "everything on"
11//! (tuned for speed); disabling everything yields plain, boring Rust.
12//!
13//! This lives in `logicaffeine_language` (not the compiler) because the parser
14//! maps `## No <Keyword>` decorators to [`Opt`]s, so the type must be visible
15//! here; the compiler and JIT see it transitively.
16
17use std::collections::BTreeMap;
18
19/// Execution-path tags (bitmask) recording where an optimization applies.
20pub mod path {
21    /// Ahead-of-time Rust codegen pipeline (`optimize_program`).
22    pub const AOT: u8 = 1 << 0;
23    /// Live run-path optimizer (`optimize_for_run`).
24    pub const RUN: u8 = 1 << 1;
25    /// Bytecode VM.
26    pub const VM: u8 = 1 << 2;
27    /// Forge JIT tier.
28    pub const JIT: u8 = 1 << 3;
29    /// Rust source emission (`codegen_program`).
30    pub const CODEGEN: u8 = 1 << 4;
31}
32
33/// How an optimization trades memory against speed.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum MemClass {
36    /// Neither clearly grows nor shrinks memory.
37    Neutral,
38    /// Spends memory (extra allocation, code growth, caches) to gain speed.
39    TradesMemForSpeed,
40    /// Shrinks memory (tighter representations, fewer allocations).
41    SavesMem,
42}
43
44/// How expensive an optimization pass is to RUN on the live path — the lever the
45/// tiered optimizer uses to decide WHEN (at which hotness tier) to pay for it.
46/// Orthogonal to [`MemClass`] (which is about the OUTPUT's memory cost). The derived
47/// `Ord` makes a tier gate a single comparison: `Cheap < Medium < Heavy` is exactly
48/// the tier-inclusion order T1 ⊂ T2 ⊂ T3.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
50pub enum OptCost {
51    /// A single structural sweep, no fixpoint (inline, DCE, TCO).
52    Cheap = 0,
53    /// A whole-function analysis or one bounded fixpoint (GVN, LICM, oracle,
54    /// fusion, the capped PE-light fixpoint).
55    Medium = 1,
56    /// A cloning / region-growing pass (the full PE fixpoint, unroll, scalarize,
57    /// recursion unfold, equality saturation).
58    Heavy = 2,
59}
60
61/// A hotness tier — how much optimization budget a unit has earned (HOTSWAP §4.1).
62/// Each tier pays for strictly more than the one below; `T3` with an all-on config
63/// reproduces today's whole-program `optimize_for_run`, bit-for-bit (the
64/// compatibility + soundness anchor). The mechanism that escalates a unit through
65/// the tiers (call/back-edge counters, thresholds) lives in the VM; this is just
66/// the policy the optimizer reads.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
68pub enum Tier {
69    /// Baseline: raw parse → bytecode, no optimization.
70    T0 = 0,
71    /// Warm: Cheap opts.
72    T1 = 1,
73    /// Hot: Cheap + Medium opts (PE-light).
74    T2 = 2,
75    /// Very-hot: every opt (PE-full, unroll, recursion unfold).
76    T3 = 3,
77}
78
79impl Tier {
80    /// The most expensive pass this tier will pay for; `None` ⇒ optimize nothing.
81    /// The inclusion order T1 ⊂ T2 ⊂ T3 falls straight out of [`OptCost`]'s `Ord`.
82    #[inline]
83    pub fn budget(self) -> Option<OptCost> {
84        match self {
85            Tier::T0 => None,
86            Tier::T1 => Some(OptCost::Cheap),
87            Tier::T2 => Some(OptCost::Medium),
88            Tier::T3 => Some(OptCost::Heavy),
89        }
90    }
91}
92
93/// Whether `opt` runs at `tier` under `cfg`: it must be enabled in the config AND
94/// cost no more than the tier's budget. The tier→opt-set mapping is therefore
95/// DERIVED from the registry, never hardcoded — adding an opt with a cost slots it
96/// into the right tier automatically (HOTSWAP §4.2).
97///
98/// This is pure policy. Run-path callers additionally AND in any
99/// `#[cfg(feature = "codegen")]` availability for the codegen-only passes
100/// (Affine/Unroll/Scalarize): those passes don't exist on targets without the
101/// feature, so tier-invariance is asserted per-platform, not across platforms.
102#[inline]
103pub fn admits(cfg: &OptimizationConfig, tier: Tier, opt: Opt) -> bool {
104    matches!(tier.budget(), Some(b) if opt.cost() <= b) && cfg.is_on(opt)
105}
106
107/// The number of [`Opt`] variants — the width of a [`PinSet`]. Derived from the
108/// last variant so it tracks the enum automatically (guarded by a test against
109/// `REGISTRY.len()`).
110pub const OPT_COUNT: usize = Opt::HintVersion as usize + 1;
111
112/// The 64-bit words an [`OptBits`] set holds: one bit per registered optimization.
113pub const OPT_WORDS: usize = OPT_COUNT.div_ceil(64);
114
115/// A set of optimizations, one bit per [`Opt`] (its discriminant), in as many 64-bit words as the registry
116/// needs. [`OptimizationConfig`] keeps the enabled set in one and [`FiredOptimizations`] the fired set, in the
117/// same layout, so the two relate bit for bit.
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
119pub struct OptBits([u64; OPT_WORDS]);
120
121impl OptBits {
122    /// The empty set.
123    pub const EMPTY: OptBits = OptBits([0; OPT_WORDS]);
124
125    const fn place(opt: Opt) -> (usize, u64) {
126        (opt as usize / 64, 1u64 << (opt as usize % 64))
127    }
128
129    /// Whether `opt` is in the set.
130    #[inline]
131    pub const fn contains(&self, opt: Opt) -> bool {
132        let (word, bit) = Self::place(opt);
133        self.0[word] & bit != 0
134    }
135
136    /// The set with `opt` added.
137    #[inline]
138    pub const fn with(mut self, opt: Opt) -> Self {
139        let (word, bit) = Self::place(opt);
140        self.0[word] |= bit;
141        self
142    }
143
144    /// The set with `opt` removed.
145    #[inline]
146    pub const fn without(mut self, opt: Opt) -> Self {
147        let (word, bit) = Self::place(opt);
148        self.0[word] &= !bit;
149        self
150    }
151
152    /// The optimizations in either set.
153    pub const fn union(mut self, other: OptBits) -> Self {
154        let mut i = 0;
155        while i < OPT_WORDS {
156            self.0[i] |= other.0[i];
157            i += 1;
158        }
159        self
160    }
161
162    /// The optimizations in both sets.
163    pub const fn intersection(mut self, other: OptBits) -> Self {
164        let mut i = 0;
165        while i < OPT_WORDS {
166            self.0[i] &= other.0[i];
167            i += 1;
168        }
169        self
170    }
171
172    /// The optimizations in this set and not in `other`.
173    pub const fn difference(mut self, other: OptBits) -> Self {
174        let mut i = 0;
175        while i < OPT_WORDS {
176            self.0[i] &= !other.0[i];
177            i += 1;
178        }
179        self
180    }
181
182    /// Whether the set is empty.
183    pub const fn is_empty(&self) -> bool {
184        let mut i = 0;
185        while i < OPT_WORDS {
186            if self.0[i] != 0 {
187                return false;
188            }
189            i += 1;
190        }
191        true
192    }
193}
194
195/// WHEN each allowed optimization runs, as opposed to WHICH are allowed
196/// ([`OptimizationConfig`]). The sibling policy of HOTSWAP §8: the bitset says what
197/// is permitted; this says at what hotness tier each permitted opt is paid for.
198/// Kept separate from `OptimizationConfig` (which is serialized / merged per-function
199/// / normalized) so tier state never pollutes the "which opts" bitset.
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201pub enum TierMode {
202    /// Units climb T0→T3 by hotness — the default.
203    Tiered,
204    /// Everything optimized upfront at T3 — today's behavior, the A/B baseline.
205    Eager,
206    /// Never optimize — every unit pinned at T0.
207    Baseline,
208}
209
210/// Call/back-edge counts at which a unit enters each tier (HOTSWAP §5). Defaults:
211/// don't optimize code that runs once (T1 at 8); amortize whole-function analyses
212/// only once recurring (T2 at 32); pay the cloning passes only on genuinely hot
213/// kernels (T3 at 100, aligned with the existing native-tier threshold).
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215pub struct TierThresholds {
216    pub t1: u32,
217    pub t2: u32,
218    pub t3: u32,
219}
220
221impl Default for TierThresholds {
222    fn default() -> Self {
223        Self {
224            t1: 8,
225            t2: 32,
226            t3: 100,
227        }
228    }
229}
230
231impl TierThresholds {
232    /// The tier a unit with `count` accumulated calls/back-edges has earned.
233    #[inline]
234    pub fn tier_for(self, count: u32) -> Tier {
235        if count >= self.t3 {
236            Tier::T3
237        } else if count >= self.t2 {
238            Tier::T2
239        } else if count >= self.t1 {
240            Tier::T1
241        } else {
242            Tier::T0
243        }
244    }
245
246    /// `LOGOS_TIER_THRESHOLDS="8,32,100"`, overridable per-rung by
247    /// `LOGOS_TIER_T1`/`T2`/`T3`.
248    pub fn from_env() -> Self {
249        Self::from_spec(
250            std::env::var("LOGOS_TIER_THRESHOLDS").ok().as_deref(),
251            std::env::var("LOGOS_TIER_T1").ok().as_deref(),
252            std::env::var("LOGOS_TIER_T2").ok().as_deref(),
253            std::env::var("LOGOS_TIER_T3").ok().as_deref(),
254        )
255    }
256
257    /// The pure, testable core of `from_env`.
258    pub fn from_spec(
259        combined: Option<&str>,
260        t1: Option<&str>,
261        t2: Option<&str>,
262        t3: Option<&str>,
263    ) -> Self {
264        let mut th = Self::default();
265        if let Some(c) = combined {
266            let parts: Vec<u32> = c.split(',').filter_map(|s| s.trim().parse().ok()).collect();
267            if parts.len() == 3 {
268                th = Self {
269                    t1: parts[0],
270                    t2: parts[1],
271                    t3: parts[2],
272                };
273            }
274        }
275        if let Some(v) = t1.and_then(|s| s.trim().parse().ok()) {
276            th.t1 = v;
277        }
278        if let Some(v) = t2.and_then(|s| s.trim().parse().ok()) {
279            th.t2 = v;
280        }
281        if let Some(v) = t3.and_then(|s| s.trim().parse().ok()) {
282            th.t3 = v;
283        }
284        th
285    }
286}
287
288/// A per-opt tier override (HOTSWAP §8 `## Tier <kw> <eager|t1|t2|t3|never>`).
289#[derive(Debug, Clone, Copy, PartialEq, Eq)]
290pub enum Pin {
291    /// Allowed by config but pinned off the tiering ladder — never run by tiering
292    /// (distinct from `## No <opt>`, which forbids it and cascades through normalize).
293    Never,
294    /// Run as soon as the unit is optimized at all (any tier ≥ T1), ignoring cost.
295    Eager,
296    /// Run once this tier is reached.
297    At(Tier),
298}
299
300/// Per-opt tier pins, indexed by [`Opt`] discriminant. `None` ⇒ use the cost-derived
301/// tier. `Copy` so [`HotswapConfig`] stays cheap to thread through the run path.
302#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303pub struct PinSet {
304    pins: [Option<Pin>; OPT_COUNT],
305}
306
307impl Default for PinSet {
308    fn default() -> Self {
309        Self::none()
310    }
311}
312
313impl PinSet {
314    /// No pins — every opt uses its cost-derived tier.
315    pub const fn none() -> Self {
316        Self {
317            pins: [None; OPT_COUNT],
318        }
319    }
320
321    #[inline]
322    pub fn get(&self, opt: Opt) -> Option<Pin> {
323        self.pins[opt as usize]
324    }
325
326    #[inline]
327    pub fn set(&mut self, opt: Opt, pin: Pin) {
328        self.pins[opt as usize] = Some(pin);
329    }
330
331    /// Copy every pin set in `other` over this set — `other` wins per-opt. Used to
332    /// overlay in-source `## Tier` decorators onto the ambient env pins (the
333    /// decorator, being explicit, takes precedence).
334    pub fn overlay(&mut self, other: &PinSet) {
335        for (slot, pin) in self.pins.iter_mut().zip(other.pins.iter()) {
336            if let Some(p) = pin {
337                *slot = Some(*p);
338            }
339        }
340    }
341}
342
343/// "*When* does each allowed opt run" — the sibling to [`OptimizationConfig`]
344/// (HOTSWAP §8). `mode` picks the escalation policy, `thresholds` the rungs,
345/// `force_tier` pins a fixed tier for deterministic tests, and `pins` overrides
346/// individual opts.
347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348pub struct HotswapConfig {
349    pub mode: TierMode,
350    pub thresholds: TierThresholds,
351    /// Forces a fixed tier regardless of hotness — the determinism lever for
352    /// differential tests (`LOGOS_FORCE_TIER`). `None` ⇒ derive from mode + count.
353    pub force_tier: Option<Tier>,
354    pub pins: PinSet,
355}
356
357impl Default for HotswapConfig {
358    fn default() -> Self {
359        // Eager by default — the §12.2 ratchet (see `from_spec`). Tiered is the locked
360        // destination, reached once it is proven not to regress.
361        Self {
362            mode: TierMode::Eager,
363            thresholds: TierThresholds::default(),
364            force_tier: None,
365            pins: PinSet::none(),
366        }
367    }
368}
369
370impl HotswapConfig {
371    /// The tier a unit with `count` accumulated calls/back-edges should run at,
372    /// under this config's mode (and any `force_tier` override).
373    #[inline]
374    pub fn effective_tier(&self, count: u32) -> Tier {
375        if let Some(t) = self.force_tier {
376            return t;
377        }
378        match self.mode {
379            TierMode::Baseline => Tier::T0,
380            TierMode::Eager => Tier::T3,
381            TierMode::Tiered => self.thresholds.tier_for(count),
382        }
383    }
384
385    /// This config's pin for `opt`, if any.
386    #[inline]
387    pub fn pin(&self, opt: Opt) -> Option<Pin> {
388        self.pins.get(opt)
389    }
390
391    /// The tier at which the run path optimizes UPFRONT, before the program executes.
392    /// `Eager` pays the full optimizer (T3, today's behavior); `Tiered`/`Baseline`
393    /// start at the baseline (T0) and rely on the native tier — and, later, per-function
394    /// re-optimization — to escalate hot code during the run, reclaiming the upfront
395    /// optimizer cost (HOTSWAP §12.1). `force_tier` overrides everything (test
396    /// determinism). Distinct from `effective_tier`, which maps a per-unit hotness
397    /// COUNT to a tier; this maps the program-level MODE to the upfront tier.
398    #[inline]
399    pub fn run_tier(&self) -> Tier {
400        if let Some(t) = self.force_tier {
401            return t;
402        }
403        match self.mode {
404            TierMode::Eager => Tier::T3,
405            TierMode::Tiered | TierMode::Baseline => Tier::T0,
406        }
407    }
408
409    /// Build from the environment — the single external entry point (HOTSWAP §8).
410    /// `LOGOS_HOTSWAP=off` forces Eager; `LOGOS_TIER_PROFILE` picks the preset;
411    /// `LOGOS_FORCE_TIER` pins a fixed tier; `LOGOS_TIER_PIN` sets per-opt pins.
412    pub fn from_env() -> Self {
413        Self::from_spec(
414            std::env::var("LOGOS_HOTSWAP").ok().as_deref(),
415            std::env::var("LOGOS_TIER_PROFILE").ok().as_deref(),
416            std::env::var("LOGOS_FORCE_TIER").ok().as_deref(),
417            TierThresholds::from_env(),
418            std::env::var("LOGOS_TIER_PIN").ok().as_deref(),
419        )
420    }
421
422    /// The pure, testable core of `from_env`.
423    pub fn from_spec(
424        hotswap: Option<&str>,
425        profile: Option<&str>,
426        force_tier: Option<&str>,
427        thresholds: TierThresholds,
428        pin_spec: Option<&str>,
429    ) -> Self {
430        // The headline escape hatch: kill tiering, optimize everything upfront.
431        // DEFAULT = Eager (today's behavior). The locked product default is Tiered,
432        // but the §12.2 RATCHET keeps Eager until the tiered path (P9/P10 per-function
433        // Axis-1) is proven >= Eager on the benchmark A/B — so the served number can
434        // only improve. Tiered/Baseline are opt-in via LOGOS_TIER_PROFILE until then.
435        let mode = if hotswap == Some("off") {
436            TierMode::Eager
437        } else {
438            match profile {
439                Some("tiered") => TierMode::Tiered,
440                Some("baseline") => TierMode::Baseline,
441                _ => TierMode::Eager,
442            }
443        };
444        let force_tier = force_tier.and_then(parse_tier);
445        let mut pins = PinSet::none();
446        if let Some(spec) = pin_spec {
447            apply_pin_spec(&mut pins, spec);
448        }
449        HotswapConfig {
450            mode,
451            thresholds,
452            force_tier,
453            pins,
454        }
455    }
456}
457
458/// Parse a tier token: `0|1|2|3`, `t0..t3`, or `baseline|warm|hot|veryhot`
459/// (case-insensitive). `None` for anything else.
460fn parse_tier(s: &str) -> Option<Tier> {
461    match s.trim().to_ascii_lowercase().as_str() {
462        "0" | "t0" | "baseline" => Some(Tier::T0),
463        "1" | "t1" | "warm" => Some(Tier::T1),
464        "2" | "t2" | "hot" => Some(Tier::T2),
465        "3" | "t3" | "veryhot" | "very_hot" => Some(Tier::T3),
466        _ => None,
467    }
468}
469
470/// Parse one pin value: `eager`, `never`, or a tier token (see `parse_tier`). The
471/// surface the `## Tier <opt> <value>` parser and `LOGOS_TIER_PIN` both resolve.
472pub fn pin_from_str(s: &str) -> Option<Pin> {
473    match s.trim().to_ascii_lowercase().as_str() {
474        "eager" => Some(Pin::Eager),
475        "never" => Some(Pin::Never),
476        other => parse_tier(other).map(Pin::At),
477    }
478}
479
480/// Apply a pin spec — `"specialize:eager,fuse:t1,unfold:never"` — to `pins`. The same
481/// keyword list as `LOGOS_OPT_OFF`; unknown keywords / values are skipped.
482fn apply_pin_spec(pins: &mut PinSet, spec: &str) {
483    for tok in spec.split([',', ';']) {
484        let tok = tok.trim();
485        if tok.is_empty() {
486            continue;
487        }
488        if let Some((kw, val)) = tok.split_once(':') {
489            if let (Some(opt), Some(pin)) = (by_keyword(kw.trim()), pin_from_str(val)) {
490                pins.set(opt, pin);
491            }
492        }
493    }
494}
495
496/// [`admits`] with per-opt pins applied: a pin overrides the cost-derived tier
497/// (HOTSWAP §8). A disabled opt (`!cfg.is_on`) never runs regardless of pin, so
498/// `## No <opt>` always wins over `## Tier <opt> eager`.
499#[inline]
500pub fn admits_pinned(cfg: &OptimizationConfig, hs: &HotswapConfig, tier: Tier, opt: Opt) -> bool {
501    if !cfg.is_on(opt) {
502        return false;
503    }
504    match hs.pin(opt) {
505        Some(Pin::Never) => false,
506        Some(Pin::Eager) => true,
507        Some(Pin::At(t)) => tier >= t,
508        None => matches!(tier.budget(), Some(b) if opt.cost() <= b),
509    }
510}
511
512/// Where a `## No <X>` decorator for this optimization may legitimately appear.
513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
514pub enum Scope {
515    /// Only meaningful program-wide (whole-program analyses).
516    ProgramOnly,
517    /// Meaningful both program-wide and on an individual function.
518    Both,
519}
520
521/// Every optimization the compiler can toggle. The discriminant is the bit
522/// index used by [`OptimizationConfig`], so the order here is stable and must
523/// not be reordered casually (it also defines conflict-resolution precedence:
524/// an earlier variant wins a conflict against a later one).
525#[derive(
526    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
527)]
528#[repr(u8)]
529pub enum Opt {
530    /// Automatic memoization of pure functions.
531    Memo = 0,
532    /// Tail-call optimization (self-tail-recursion → loop).
533    Tco = 1,
534    /// Peephole rewrites (swap, vec-fill, for-range, …).
535    Peephole = 2,
536    /// Read-only / mutable borrow inference: `&[T]` / `&mut [T]` / `&str` / `&Enum` params, and a loop that reads a
537    /// sequence it never writes through a shared borrow instead of a copy.
538    Borrow = 3,
539    /// Partial evaluation / polyvariant specialization.
540    Specialize = 4,
541    /// Compile-time function evaluation (CTFE).
542    Comptime = 5,
543    /// Inlining of tiny and leaf helper functions.
544    Inline = 6,
545    /// Bounded unrolling of recursive functions.
546    Unfold = 7,
547    /// Defunctionalization (closures → first-order functions).
548    Defunctionalize = 8,
549    /// Loop-invariant code motion (LICM).
550    LoopHoist = 9,
551    /// Loop unrolling of constant-trip loops.
552    Unroll = 10,
553    /// Guard-based loop index-set splitting (for vectorization).
554    LoopSplit = 11,
555    /// Accumulator-loop → closed-form recognition.
556    ClosedForm = 12,
557    /// Deforestation (producer/consumer stream fusion).
558    Fuse = 13,
559    /// Loop-carried common-subexpression hoisting.
560    LoopCse = 14,
561    /// Global value numbering / common-subexpression elimination.
562    Cse = 15,
563    /// Dead-code elimination.
564    DeadCode = 16,
565    /// Fixed-size sequence scalarization (SROA).
566    Scalarize = 17,
567    /// Affine offset-array deletion → closed-form indexing.
568    Affine = 18,
569    /// Array-of-structs interleaving of co-indexed sequences.
570    Interleave = 19,
571    /// De-`Rc`: unique-owned sequences become plain `Vec`.
572    Unbox = 20,
573    /// Hoisting borrow live-ranges out of loop nests.
574    HoistBorrows = 21,
575    /// `i64`→`i32` sequence element narrowing (codegen).
576    Narrow = 22,
577    /// `i64`→`i32` sequence element narrowing (VM).
578    NarrowVm = 23,
579    /// `i64`→`i32` map-key narrowing.
580    NarrowMap = 24,
581    /// Sparse map → dense direct-addressed array.
582    DenseMap = 25,
583    /// Element-type narrowing via abstract interpretation.
584    ElemType = 26,
585    /// Constant-divisor magic-reciprocal division.
586    FastDiv = 27,
587    /// Float induction-variable strength reduction.
588    FloatStrength = 28,
589    /// Abstract interpretation / oracle-fact production (interval analysis).
590    Oracle = 29,
591    /// Oracle-derived precise bounds-check guards.
592    OracleHints = 30,
593    /// Oracle-proven unchecked indexing (`get_unchecked`).
594    Unchecked = 31,
595    /// SIMD-vectorized search kernels.
596    Simd = 32,
597    /// Cascade folding of sequential comparisons.
598    Cascade = 33,
599    /// Indexed string-search codegen.
600    IndexString = 34,
601    /// Capacity-scaling buffer-fill simplification.
602    CapScale = 35,
603    /// Reflection symmetry breaking (bitmask search).
604    Symmetry = 36,
605    /// Popcount base-case collapse for bitmask search.
606    Popcount = 37,
607    /// Equality-saturation rewriting (e-graph).
608    Saturate = 38,
609    /// Supercompilation (heavy residual specialization, AOT only).
610    Supercompile = 39,
611    /// Sparse conditional constant propagation (Wegman–Zadeh): folds constants
612    /// AND prunes unreachable branches in one lattice sweep, catching constants
613    /// the iterated fold→propagate→deadcode pipeline structurally misses.
614    Sccp = 40,
615    /// Integer induction-variable strength reduction: a counted loop's affine
616    /// `coeff*j + base` index (base loop-invariant) becomes a seeded accumulator
617    /// advanced by `coeff*step`, removing the per-iteration multiply. Exact
618    /// (no runtime guard).
619    IntStrength = 41,
620    /// Aggregate-element register promotion: an invariant-indexed read-modify-
621    /// write array element is loaded into a scalar once, updated in a register
622    /// across the loop, and written back once — store-to-load forwarding LICM
623    /// cannot do (the element is written).
624    RegPromote = 42,
625    /// Loop interchange: reorder two adjacent nested counted loops to put the
626    /// unit-stride access innermost (the `ijk`→`ikj` matmul recipe). Fires only
627    /// on integer commutative-reduction nests, where any permutation is
628    /// bit-identical, and only toward better locality.
629    Interchange = 43,
630    /// Bounded-accumulator overflow-guard elision: version a hot integer loop that
631    /// provably stays `i64`-safe under a compile-time input bound (interval
632    /// inductive-invariant check), so its fast branch lowers to bare `i64` instead of
633    /// a per-iteration overflow-promotion guard; a huge input takes the unchanged
634    /// promoting branch (never an abort).
635    AccumBound = 44,
636    /// Div-mod fusion: rustc/LLVM does not CSE `a/b` against `a%b` (distinct `sdiv`/`srem`,
637    /// each its own magic-multiply for a constant divisor), so a loop computing both pays
638    /// two multiplies where gcc keeps the quotient and derives `r = a - q*b`. When one
639    /// statement holds both with the same side-effect-free operands, bind `q = a/b` once
640    /// and rewrite `a%b -> a - q*b` — the single-division shape, propagating proven-raw.
641    DivModFuse = 45,
642    /// Range-aware helper specialization: a counted-accumulator loop calls pure integer
643    /// helpers (`divModQ`/`divModM`/…) whose bodies branch on argument SIGN, but the loop
644    /// counter is provably `>= 0` and the divisor a positive constant, so those branches
645    /// are dead. This symbolically inlines the helper chain under the counter's range and
646    /// folds the dead branches, leaving bare arithmetic the div-mod fuser + accumulator
647    /// versioner then lower to a hand-C-quality loop. A call that isn't fully provable is
648    /// left untouched.
649    SpecializeLoop = 46,
650    /// Bignum by-reference arithmetic (clone elision): a reused promoted (`LogosInt`) operand in
651    /// a `+`/`-`/`*` is passed by VALUE to `logos_*_exact`, so a variable read twice (or read then
652    /// reassigned) `.clone()`s its heap magnitude every iteration. `LogosInt::{add,sub,mul}` are
653    /// already `(&self, &LogosInt)`, and `logos_mul_exact(a,b)` IS `a.into().mul(&b.into())`, so
654    /// the by-ref method is byte-identical minus the clone. Reused bignum vars are borrowed.
655    BignumByRef = 47,
656    /// In-place bignum scalar multiply: `Set acc to acc * <i64>` on a promoted accumulator (dead
657    /// last-use, native-int scalar) mutates `acc`'s heap `Vec` in place (`acc.mul_assign_i64(k)`)
658    /// instead of allocating a fresh product each iteration (the factorial hot loop).
659    BignumInPlace = 48,
660    /// Native-width bit intrinsics: the stdlib `rotateLeft`/`rotateRight`/`reverseBits`/
661    /// `reverseBytes` with a compile-time native word width (8/16/32) lower to a single Rust
662    /// intrinsic (`(x as uW).rotate_left(n)` / `.reverse_bits()` / `.swap_bytes()`) — one CPU
663    /// instruction (ROL/ROR, bit-reverse, BSWAP) — instead of a masked loop LLVM cannot recognize.
664    /// Fires at the call site AND on the const-specialized masked-rotate form the optimizer folds to.
665    BitIntrinsics = 49,
666    /// Text-bytes zero-copy view: a `Let sb be text_bytes(s)` binding used ONLY for reads
667    /// (`item i of sb`, `length of sb`, `for b in sb`) lowers to a borrowed `s.as_bytes()`
668    /// (`&[u8]`) instead of materializing a `Vec<i64>` byte-list (8x blow-up + `Rc<RefCell>`
669    /// box + a `.borrow()` and bounds check per byte). Reads cast the `u8` back to `i64`.
670    /// The whole text stdlib funnels every operation through `text_bytes`, so this removes
671    /// the dominant text-cluster read cost. Read-side half of the byte-list elimination.
672    TextBytesView = 50,
673    /// String accumulator reuse: `Set X to X combined with Y` (X a mutable owned `String`,
674    /// Y not mentioning X) mutates X's buffer in place via `X.push_str(&Y)` — amortized O(1)
675    /// growth — instead of `X = format!("{}{}", X, Y)`, which reallocates and copies the whole
676    /// accumulator every iteration (turning `repeatText` and any concat-accumulator loop into
677    /// O(N^2)). Fires on the SHAPE (self-append concat, target leftmost) so a user's own
678    /// accumulator loop benefits identically. General FBIP write-side string reuse.
679    StringAccumReuse = 51,
680    /// SIMD reduction: an integer accumulator loop summing `trunc(<liftable float in the counter>)`
681    /// over a counted range is lowered to an AVX2 four-lane `f64` reduction — the transcendental is
682    /// translated to `_mm256` intrinsics (branches → `blendv`), byte-identical to the scalar path
683    /// per lane, and the `i64` sum is associative so the reduce equals the sequential sum. Beats
684    /// scalar libm across the loop where LLVM refuses to auto-vectorize the `f64`→`i64` cast.
685    SimdReduce = 52,
686    /// Text write-side byte builder: a `Let out be a new Seq of Int` used ONLY as a byte builder
687    /// (`Push <i64> to out`) and consumed by `text_from_bytes(out)` lowers to a bare `Vec<u8>`
688    /// (`out.push((e) as u8)`) plus a direct `String::from_utf8(out)` — eliminating the
689    /// `Rc<RefCell<Vec<i64>>>` output (8x memory + per-push `borrow_mut` + no presize) AND the
690    /// separate `i64`->`u8` rebuild pass that `text_from_bytes` performed. Write-side half of the
691    /// byte-list elimination (twin of `TextBytesView`); fires on the SHAPE so any user byte-builder
692    /// benefits identically.
693    TextFromBytesBuilder = 53,
694    /// Text zero-copy sub-slice return: a fn that returns a CONTIGUOUS sub-slice of a borrowed Text
695    /// param (compute lo/hi by scans, then copy `item lo..hi of text_bytes(s)` into a builder and
696    /// `text_from_bytes(out)`) lowers to a borrowed `&'a str` return (`fn f<'a>(s: &'a str) -> &'a str
697    /// { &s[lo-1..hi] }`) when EVERY caller uses the result read-only (never binds/returns/pushes it).
698    /// Matches Rust `str::trim`/`strip_prefix` — an O(1) fat-pointer slice instead of an O(n) copy.
699    /// Requires the Text param already borrowed (Opt::Borrow); PREEMPTS the write-side builder on the
700    /// terminal Return (the slice supersedes building a Vec<u8>). The only ASYMPTOTIC text win.
701    TextSliceReturn = 54,
702    /// String concat reuse (Let-form): `Let X be A + B...` where A is a fresh OWNED `String` (a call
703    /// returning `String`) reuses A's buffer — `let mut X = A; X.push_str(&B)...` — instead of
704    /// `format!("{}{}", A, B)`, which allocates a NEW String and copies every operand. The `Let`-form
705    /// twin of `StringAccumReuse` (which handles `Set X to X + Y`). Construction-shared across the whole
706    /// text benchmark cluster (`repeatText(..) + base`), so it lifts trim/upper/lower/… toward Rust's
707    /// buffer-reuse (`"a".repeat(k) + &base`). Fires on the SHAPE; a user's `A + B` benefits identically.
708    StringConcatReuse = 55,
709    /// String repeat-idiom: `Let out be ""` + a counted loop whose sole body is `Set out to out + chunk`
710    /// (chunk loop-invariant) lowers to `let out = chunk.repeat(count)` — one presized alloc + memset,
711    /// matching Rust's `chunk.repeat(n)`, instead of `count` un-presized `push_str`es. Fires on the
712    /// SHAPE (a counted append of a fixed chunk), so `repeatText` and any user repeat-loop benefit.
713    StringRepeatLoop = 56,
714    /// ASCII-class bitmask: a pure `Int -> Bool` predicate whose true-set lies entirely in the byte
715    /// domain `[0,256)` (the `charIs*` family — range/equality checks over `c`) lowers to a branchless
716    /// 256-bit mask test `(0<=c<256) && (MASK[(c>>6)&3] >> (c&63)) & 1`, built by CTFE-evaluating the
717    /// predicate over `0..256`. Beats C's `ctype` table (the mask is an immediate/static — no memory
718    /// load). Fires on ANY such predicate, so a user's classifier collapses the same way.
719    AsciiClassMask = 57,
720    /// Power-of-two modulo/division strength reduction: `x % 2^k` → `x & (2^k-1)` and `x / 2^k` →
721    /// `x >> k` when `x` is proven non-negative (a loop counter from a `>= 0` start with a positive
722    /// step). rustc keeps sign-corrected `%`/`/` for a runtime i64 (several instructions that also
723    /// block auto-vectorization); the mask/shift is one op. Sound (for `x >= 0` they agree), general
724    /// (every ring-buffer/hash/index loop), and the measured lever that lets loops beat C.
725    StrengthReducePow2 = 58,
726    /// Branchless accumulate (predicate-guarded increment if-conversion): `if <cond> { X = X + k }`
727    /// (no else, X a plain integer accumulator, k a literal) → `X = X + (<cond> as i64) * k`. Removes
728    /// the data-dependent branch that blocks the loop vectorizer. Byte-identical (`cond ∈ {0,1}`, and
729    /// `cond` is evaluated exactly once either way). Pairs with a wide accumulator to beat C's count.
730    BranchlessAccumulate = 59,
731    /// Wide (i128) accumulator: a `Let X be 0` counting accumulator incremented ONLY by `+1` (guarded
732    /// or not) in a SINGLE counted loop with an i64 bound, read ONLY by `Show X`, widens to `i128` for
733    /// the loop — the plain i128 add has no overflow branch (unlike `logos_add_i64`), so the count
734    /// vectorizes. SOUND: X ≤ trip-count ≤ i64::MAX, so it fits i64 (narrow `as i64` at the sink is
735    /// exact) and i128 can't overflow. The lever that beats C's ctype-count loop (43ms vs 49ms).
736    WideAccumulator = 60,
737    /// Radix digit buffer (itoa): the base-N integer→text idiom (generate digits LSB-first into a
738    /// boxed `Seq`, reverse into a second boxed `Seq`, `text_from_bytes`) lowers to ONE fixed-size
739    /// stack `[u8; 64]` written BACK-TO-FRONT (the back-to-front write is the reversal), then one
740    /// `String` from the buffer tail — no heap Seq, no reversal copy. SOUND only when the loop
741    /// counter is a native i64 (never bignum-promotable) so the digit count is bounded ≤64. Beats
742    /// Go's strconv (measured 1.30x). Preempts `TextFromBytesBuilder` (it eliminates the `out`
743    /// byte-builder that pass would otherwise lower).
744    RadixDigitBuffer = 61,
745    /// Byte-slice return (the bytes-trim family): a fn taking a `Seq of Int` param that returns a
746    /// CONTIGUOUS `lo..=hi` sub-slice (scan, then copy `item lo..hi of xs` into `out`, `Return out`)
747    /// lowers to a borrowed `&'a [i64]` (`fn f<'a>(xs: &'a [i64], …) -> &'a [i64] { … &xs[lo-1..hi] }`)
748    /// — Go's O(1) `bytes.Trim` reslice instead of the O(n) build-copy. The bytes twin of
749    /// TextSliceReturn (a readonly Seq param is already `&[i64]`, so the sub-slice shares its
750    /// lifetime). Caller-gate drops any fn whose result escapes. Preempts OracleHints + Unchecked
751    /// (eliminates the indexed-copy loop those bounds-check opts would optimize). Requires Borrow.
752    ByteSliceReturn = 62,
753    /// Loop tiling: a band of counted loops runs in square tiles for cache locality, only where the dependence
754    /// test proves no run can tell the order apart (`optimize::dependence`), the nest versioned on the
755    /// preconditions that make it so (`optimize::version`). The order of every item's own updates is kept, so a
756    /// Real accumulation stays bit for bit.
757    Tile = 63,
758    /// Masked-chain narrowing: an integer chain of `+`, `-`, `*`, `&`, `|`, `^` and constant `<<` under a low-bit
759    /// mask `& (2^k - 1)`, `k <= 32`, whose every node the range oracle proves stays an i64, computes in 32-bit
760    /// wrapping arithmetic. That is exact: those operations' low `k` bits depend only on their operands' low `k`
761    /// bits. Narrowed, a masked LCG's unrolled steps become independent multiplies (by a, a², a³, a⁴) instead of one
762    /// serial 64-bit multiply chain.
763    MaskNarrow = 64,
764    /// A remainder by a constant `m > 0` of a value the range oracle bounds to `[0, 2m)`: `x - m` when `x >= m`, and
765    /// `x` otherwise, one compare and one subtract in place of a multiply-shift remainder (a value bounded below `m`
766    /// is its own remainder). A loop that carries a residue (`b = (a + b) % M`) has its remainder on the critical
767    /// path, so the subtraction bounds the loop instead of the division. On the bytecode path the VM compiler decides
768    /// it from the same oracle: a value below `m` compiles as itself, and one below `2m` keeps its magic remainder
769    /// marked `wrap`, which the VM and the C walker compute as the compare and subtract.
770    ModWrap = 65,
771    /// Branchless select: `If c: Set x to a. Otherwise: Set x to b.`, where both arms are integer arithmetic that
772    /// cannot trap and at least one keeps its exactness behind a guarded dual, computes both arms and lets `c` choose
773    /// (a conditional move, not a branch on `c`). The arms' guards are tested on their own before either arm; when one
774    /// fails, the original branch runs with its exact arithmetic. A data-dependent `c` (collatz's parity) no longer
775    /// mispredicts.
776    BranchlessSelect = 66,
777    /// Variant boxing: a variant of a recursive enum that holds the enum itself keeps all its fields in one box (the
778    /// variant's payload, a struct of them), where each recursive field had a box of its own; a variant with no
779    /// fields is a value with no allocation. A tree of `n` leaves allocates once per node rather than once per child,
780    /// a leaf included: OCaml's representation of a datatype.
781    VariantBox = 67,
782    /// Bit packing: a local `Seq of Bool` used only through item reads, item stores, pushes and its length is held one
783    /// bit per item (`LogosBits`), an eighth of the bytes of a `Vec<bool>`; a sieve's table of 10^8 flags fits the
784    /// cache its passes streamed through.
785    BitPack = 68,
786    /// Fold/build fusion: a function that only takes a datatype apart, applied to what a function builds of it, is
787    /// one function that never builds it (the builder's recursion, each construction replaced by the consumer's arm for
788    /// that variant). `check(bottomUpTree(d))` builds no tree, and the fused recursion is a shape the compiler
789    /// collapses.
790    FoldFusion = 69,
791    /// Sorting-nest collapse: a nest of passes of adjacent compare-exchanges over a sequence of Ints (bubble sort)
792    /// that has enough passes to sort its window is one in-place heap sort of the window, behind a hoisted check
793    /// that the passes suffice and the window lies inside the sequence; `n(n-1)/2` comparisons become `O(n log n)`.
794    SortNest = 70,
795    /// Divisor sieve: a search, for each number of a counted range, for a divisor no greater than its square root
796    /// (trial division) reads one sieve of the range, marked before the loop, behind a guard on the sieve's size;
797    /// `O(n sqrt n)` divisions become `O(n log log n)` marks.
798    DivisorSieve = 71,
799    /// Trace memoization: a pure iteration run from every start of a counted range, whose only effect adds a constant
800    /// to an accumulator, keeps what each finished start added in a table, and a trace that reaches a finished start
801    /// adds that start's sum and stops.
802    TraceMemo = 72,
803    /// Probe fusion: `If m contains k:` over a branch that reads `item k of m` reads the value once at the top of
804    /// the branch, and the test and the read are one lookup.
805    ProbeFuse = 73,
806    /// Strided fill: a loop that stores one value into a bit-packed `Seq of Bool` at a fixed stride, every store
807    /// proven to name an item and the stride at least 1, is one fill that writes each word once (a sieve crossing
808    /// off a small prime's multiples sets dozens of bits per word).
809    StrideFill = 74,
810    /// Hint versioning: the innermost loop whose bounds hints the Oracle could not discharge runs as two copies, one
811    /// that assumes every hint, chosen where every hint holds, and one that assumes none.
812    HintVersion = 75,
813}
814
815impl Opt {
816    /// This optimization's registry row.
817    pub fn meta(self) -> &'static OptMeta {
818        // Discriminants are 0..REGISTRY.len() in order, so index directly.
819        &REGISTRY[self as usize]
820    }
821
822    /// How expensive this optimization is to run — the lever the tiered optimizer
823    /// uses to decide which hotness tier pays for it.
824    #[inline]
825    pub fn cost(self) -> OptCost {
826        self.meta().cost
827    }
828}
829
830/// One row of the optimization registry — the complete static description of a
831/// single optimization. Adding an optimization means adding one [`Opt`] variant
832/// and one row here; nothing else hardcodes the list.
833#[derive(Debug, Clone, Copy)]
834pub struct OptMeta {
835    /// The optimization this row describes.
836    pub opt: Opt,
837    /// The `## No <Keyword>` decorator word (lowercase, single token).
838    pub keyword: &'static str,
839    /// Human-readable label for UIs.
840    pub label: &'static str,
841    /// Which group the UI files this under.
842    pub group: &'static str,
843    /// Whether this optimization is on in the default (all-on, speed) config.
844    pub default_on: bool,
845    /// Execution paths it affects (bitmask of [`path`] constants).
846    pub paths: u8,
847    /// Whether enabling it can emit `unsafe` Rust (disabled by the Safety profile).
848    pub emits_unsafe: bool,
849    /// Its memory/speed trade-off classification.
850    pub mem_class: MemClass,
851    /// How expensive the pass is to run — the hotness tier at which the tiered
852    /// optimizer starts paying for it (HOTSWAP §3). For every row,
853    /// `cost(requires) ≤ cost`, so a tier that admits this opt admits its deps.
854    pub cost: OptCost,
855    /// Optimizations that must be on for this one to apply; if any is off,
856    /// `normalize` turns this one off too.
857    pub requires: &'static [Opt],
858    /// Optimizations mutually exclusive with this one — GLOBAL exclusion (both on
859    /// → `normalize` disables the later-declared). Distinct from `preempts`.
860    pub conflicts: &'static [Opt],
861    /// Optimizations this one takes PRECEDENCE over, per instance: when both are
862    /// enabled, this one is tried/applied first for a given function/loop/array/
863    /// map, and the listed ones act as the fallback for the instances it did not
864    /// claim. Both stay enabled (unlike `conflicts`); the listed optimization
865    /// fires only where this one declined. Disabling THIS one is what can let a
866    /// preempted optimization surface — the edge the menu-tree walks.
867    pub preempts: &'static [Opt],
868    /// Where its decorator may appear.
869    pub scope: Scope,
870    /// Whether it changes the program's algorithm — see [`OptWork`].
871    pub work: OptWork,
872}
873
874/// What an optimization does to the WORK a program performs, as opposed to how fast it performs it.
875///
876/// Benchmarks compare languages running the same algorithm. An optimization that replaces the algorithm makes the
877/// comparison a different one — a fair demonstration of the compiler, and one a reader must be told about: every
878/// benchmark a [`OptWork::Less`] optimization fires on carries a note saying what the compiler did
879/// (`benchmarks/lib/benchmarks.tsv`, locked by `benchmark_collapse_lock`), and is left out of the same-algorithm
880/// geometric mean. Every registry row must say which it is, so a new pass cannot change a result unannounced.
881#[derive(Debug, Clone, Copy, PartialEq, Eq)]
882pub enum OptWork {
883    /// The same algorithm in cheaper machine code: the program's loops, recursion and data structures all still run.
884    Same,
885    /// A different, cheaper algorithm when it fires: memoized recursion, a loop or recursion replaced by its closed
886    /// form, a symmetric search cut in half, a map replaced by an array its keys index, a loop replaced by one
887    /// instruction, work moved to compile time.
888    Less,
889}
890
891use path::{AOT, CODEGEN, JIT, RUN, VM};
892use MemClass::{Neutral, SavesMem, TradesMemForSpeed};
893use OptCost::{Cheap, Heavy, Medium};
894use Scope::{Both, ProgramOnly};
895
896/// The complete optimization registry: exactly one row per [`Opt`], in
897/// discriminant order. Earlier rows win conflicts against later rows.
898pub static REGISTRY: &[OptMeta] = &[
899    OptMeta { opt: Opt::Memo, keyword: "memo", label: "Memoization", group: "Inlining & calls", default_on: true, paths: AOT | RUN | CODEGEN, emits_unsafe: false, mem_class: TradesMemForSpeed, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Less },
900    OptMeta { opt: Opt::Tco, keyword: "tco", label: "Tail-call optimization", group: "Inlining & calls", default_on: true, paths: AOT | RUN | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[Opt::Memo], scope: Both, work: OptWork::Same },
901    OptMeta { opt: Opt::Peephole, keyword: "peephole", label: "Peephole rewrites", group: "Peephole", default_on: true, paths: AOT | CODEGEN, emits_unsafe: true, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
902    // Borrow preempts Tco: a `&mut [T]` in-place recursion (quicksort's
903    // consume-alias shape) keeps its plain recursive calls — the pair-TCE
904    // rewrite would reassign the borrowed param.
905    OptMeta { opt: Opt::Borrow, keyword: "borrow", label: "Borrow inference", group: "Arrays & memory", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[], conflicts: &[], preempts: &[Opt::Tco], scope: Both, work: OptWork::Same },
906    OptMeta { opt: Opt::Specialize, keyword: "specialize", label: "Partial evaluation", group: "Inlining & calls", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: TradesMemForSpeed, cost: Medium, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
907    OptMeta { opt: Opt::Comptime, keyword: "comptime", label: "Compile-time evaluation (CTFE)", group: "Inlining & calls", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: Neutral, cost: Medium, requires: &[], conflicts: &[], preempts: &[Opt::Supercompile], scope: Both, work: OptWork::Less },
908    OptMeta { opt: Opt::Inline, keyword: "inline", label: "Function inlining", group: "Inlining & calls", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: TradesMemForSpeed, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
909    OptMeta { opt: Opt::Unfold, keyword: "unfold", label: "Recursion unrolling", group: "Inlining & calls", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: TradesMemForSpeed, cost: Heavy, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
910    OptMeta { opt: Opt::Defunctionalize, keyword: "defunctionalize", label: "Defunctionalization", group: "Inlining & calls", default_on: true, paths: AOT, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
911    OptMeta { opt: Opt::LoopHoist, keyword: "loophoist", label: "Loop-invariant code motion", group: "Loops", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: Neutral, cost: Medium, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
912    OptMeta { opt: Opt::Unroll, keyword: "unroll", label: "Loop unrolling", group: "Loops", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: TradesMemForSpeed, cost: Heavy, requires: &[], conflicts: &[], preempts: &[Opt::Interleave], scope: Both, work: OptWork::Same },
913    OptMeta { opt: Opt::LoopSplit, keyword: "loopsplit", label: "Loop index-set splitting", group: "Loops", default_on: true, paths: AOT, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
914    // NOTE: ClosedForm naturally preempts Memo (a recursion it solves has no
915    // self-calls left when the run-path memoizer runs right after it, so Memo
916    // declines), but NO witness program exhibits both on the same function, so
917    // the edge is left UNDECLARED — the corpus-observed-edges lock forbids
918    // declaring a precedence nothing exercises (it would be a phantom).
919    OptMeta { opt: Opt::ClosedForm, keyword: "closedform", label: "Closed-form loop recognition", group: "Loops", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: Neutral, cost: Medium, requires: &[], conflicts: &[], preempts: &[Opt::Peephole], scope: Both, work: OptWork::Less },
920    OptMeta { opt: Opt::Fuse, keyword: "fuse", label: "Deforestation (stream fusion)", group: "Loops", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: SavesMem, cost: Medium, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
921    OptMeta { opt: Opt::LoopCse, keyword: "loopcse", label: "Loop-carried CSE", group: "Loops", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: Neutral, cost: Medium, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
922    OptMeta { opt: Opt::Cse, keyword: "cse", label: "Common-subexpression elimination (GVN)", group: "Redundancy", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: Neutral, cost: Medium, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
923    OptMeta { opt: Opt::DeadCode, keyword: "deadcode", label: "Dead-code elimination", group: "Redundancy", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
924    OptMeta { opt: Opt::Scalarize, keyword: "scalarize", label: "Array scalarization (SROA)", group: "Arrays & memory", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: TradesMemForSpeed, cost: Heavy, requires: &[Opt::Cse], conflicts: &[], preempts: &[Opt::HoistBorrows, Opt::Interleave, Opt::Unbox], scope: Both, work: OptWork::Same },
925    OptMeta { opt: Opt::Affine, keyword: "affine", label: "Affine array → closed form", group: "Arrays & memory", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: SavesMem, cost: Medium, requires: &[Opt::Unbox], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
926    // AoS interleaving is mutually exclusive with Unroll/Scalarize only at RUNTIME
927    // (the codegen regime gate skips it when a co-indexed array has any constant
928    // index access — i.e. once it has been unrolled/scalarized), NOT at config
929    // level. All three stay enabled by default; the gate arbitrates per program.
930    OptMeta { opt: Opt::Interleave, keyword: "interleave", label: "Array-of-structs interleaving", group: "Arrays & memory", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Heavy, requires: &[Opt::Scalarize], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
931    OptMeta { opt: Opt::Unbox, keyword: "unbox", label: "De-Rc (Vec instead of Rc<RefCell>)", group: "Arrays & memory", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
932    OptMeta { opt: Opt::HoistBorrows, keyword: "hoistborrows", label: "Borrow hoisting", group: "Arrays & memory", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[Opt::HintVersion], scope: ProgramOnly, work: OptWork::Same },
933    OptMeta { opt: Opt::Narrow, keyword: "narrow", label: "i32 sequence narrowing (codegen)", group: "Number representation", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[Opt::Unbox], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
934    OptMeta { opt: Opt::NarrowVm, keyword: "narrowvm", label: "i32 sequence narrowing (VM)", group: "Number representation", default_on: true, paths: VM | RUN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
935    OptMeta { opt: Opt::NarrowMap, keyword: "narrowmap", label: "i32 map-key narrowing", group: "Number representation", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
936    OptMeta { opt: Opt::DenseMap, keyword: "densemap", label: "Dense direct-addressed map", group: "Number representation", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: TradesMemForSpeed, cost: Cheap, requires: &[], conflicts: &[], preempts: &[Opt::NarrowMap], scope: ProgramOnly, work: OptWork::Less },
937    OptMeta { opt: Opt::ElemType, keyword: "elemtype", label: "Element-type narrowing", group: "Number representation", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: SavesMem, cost: Medium, requires: &[Opt::Oracle], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
938    OptMeta { opt: Opt::FastDiv, keyword: "fastdiv", label: "Magic-reciprocal division", group: "Number representation", default_on: true, paths: AOT | VM | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
939    OptMeta { opt: Opt::FloatStrength, keyword: "floatstrength", label: "Float induction strength reduction", group: "Number representation", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: Neutral, cost: Medium, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
940    OptMeta { opt: Opt::Oracle, keyword: "oracle", label: "Abstract interpretation (oracle facts)", group: "Bounds & checks", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: Neutral, cost: Medium, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
941    OptMeta { opt: Opt::OracleHints, keyword: "oraclehints", label: "Oracle bounds-check guards", group: "Bounds & checks", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Medium, requires: &[Opt::Oracle], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
942    OptMeta { opt: Opt::Unchecked, keyword: "unchecked", label: "Oracle-proven unchecked indexing", group: "Bounds & checks", default_on: true, paths: AOT | JIT | CODEGEN, emits_unsafe: true, mem_class: Neutral, cost: Medium, requires: &[Opt::Oracle], conflicts: &[], preempts: &[Opt::HintVersion], scope: Both, work: OptWork::Same },
943    OptMeta { opt: Opt::Simd, keyword: "simd", label: "SIMD search kernels", group: "Strings & SIMD", default_on: true, paths: AOT | CODEGEN, emits_unsafe: true, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[Opt::BranchlessAccumulate], scope: ProgramOnly, work: OptWork::Same },
944    OptMeta { opt: Opt::Cascade, keyword: "cascade", label: "Cascade folding", group: "Strings & SIMD", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
945    OptMeta { opt: Opt::IndexString, keyword: "indexstring", label: "Indexed string search", group: "Strings & SIMD", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[Opt::StringAccumReuse], scope: ProgramOnly, work: OptWork::Same },
946    OptMeta { opt: Opt::CapScale, keyword: "capscale", label: "Capacity-scaling buffer fill", group: "Strings & SIMD", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
947    OptMeta { opt: Opt::Symmetry, keyword: "symmetry", label: "Symmetry breaking", group: "Search-space", default_on: true, paths: AOT, emits_unsafe: false, mem_class: Neutral, cost: Heavy, requires: &[Opt::Specialize], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Less },
948    OptMeta { opt: Opt::Popcount, keyword: "popcount", label: "Popcount leaf collapse", group: "Search-space", default_on: true, paths: AOT, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Less },
949    OptMeta { opt: Opt::Saturate, keyword: "saturate", label: "Equality saturation (e-graph)", group: "Search-space", default_on: true, paths: AOT, emits_unsafe: false, mem_class: Neutral, cost: Heavy, requires: &[], conflicts: &[], preempts: &[Opt::BignumInPlace], scope: Both, work: OptWork::Same },
950    OptMeta { opt: Opt::Supercompile, keyword: "supercompile", label: "Supercompilation", group: "Search-space", default_on: true, paths: AOT, emits_unsafe: false, mem_class: TradesMemForSpeed, cost: Heavy, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
951    OptMeta { opt: Opt::Sccp, keyword: "sccp", label: "Sparse conditional constant propagation", group: "Redundancy", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: Neutral, cost: Medium, requires: &[], conflicts: &[], preempts: &[Opt::Supercompile], scope: Both, work: OptWork::Same },
952    // IntStrength and LoopSplit COMPOSE, not preempt: on the AOT path IntStrength
953    // DEFERS the square matmul nest to the codegen tiler (LoopSplit family), whose
954    // L1 cache tiling beats removing the index multiply and needs the nest's raw
955    // shape (`int_induction_sr::is_square_triple_nest`). No precedence edge — both
956    // fire, on the loops each is best for.
957    OptMeta { opt: Opt::IntStrength, keyword: "intstrength", label: "Integer induction strength reduction", group: "Number representation", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: Neutral, cost: Medium, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
958    OptMeta { opt: Opt::RegPromote, keyword: "regpromote", label: "Aggregate-element register promotion", group: "Arrays & memory", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: Neutral, cost: Medium, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
959    OptMeta { opt: Opt::Interchange, keyword: "interchange", label: "Loop interchange", group: "Loops", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: Neutral, cost: Heavy, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
960    OptMeta { opt: Opt::AccumBound, keyword: "accumbound", label: "Bounded-accumulator overflow-guard elision", group: "Loops", default_on: true, paths: AOT, emits_unsafe: false, mem_class: Neutral, cost: Medium, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
961    OptMeta { opt: Opt::DivModFuse, keyword: "divmodfuse", label: "Div-mod fusion (shared quotient for a/b + a%b)", group: "Loops", default_on: true, paths: AOT, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
962    OptMeta { opt: Opt::SpecializeLoop, keyword: "specializeloop", label: "Range-aware helper specialization in counted loops", group: "Loops", default_on: true, paths: AOT | RUN, emits_unsafe: false, mem_class: Neutral, cost: Medium, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
963    OptMeta { opt: Opt::BignumByRef, keyword: "bignumbyref", label: "Bignum by-ref arithmetic (clone elision)", group: "Bignum", default_on: true, paths: AOT, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
964    OptMeta { opt: Opt::BignumInPlace, keyword: "bignuminplace", label: "In-place bignum scalar multiply (mul_assign_i64)", group: "Bignum", default_on: true, paths: AOT, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[Opt::BignumByRef], scope: Both, work: OptWork::Same },
965    OptMeta { opt: Opt::BitIntrinsics, keyword: "bitintrinsics", label: "Native-width bit intrinsics (rotate/reverse/byteswap)", group: "Bits", default_on: true, paths: AOT, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
966    OptMeta { opt: Opt::TextBytesView, keyword: "textbytesview", label: "Text-bytes zero-copy &[u8] view (no Vec<i64> byte-list)", group: "Text", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
967    OptMeta { opt: Opt::StringAccumReuse, keyword: "stringaccumreuse", label: "String accumulator in-place push_str (no per-concat realloc)", group: "Text", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
968    OptMeta { opt: Opt::SimdReduce, keyword: "simdreduce", label: "AVX2 SIMD reduction of a transcendental accumulator loop", group: "Math", default_on: true, paths: AOT | CODEGEN, emits_unsafe: true, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
969    OptMeta { opt: Opt::TextFromBytesBuilder, keyword: "textfrombytesbuilder", label: "Text write-side byte builder (Vec<u8>, no Vec<i64> + no rebuild)", group: "Text", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
970    OptMeta { opt: Opt::TextSliceReturn, keyword: "textslicereturn", label: "Text zero-copy sub-slice return (&str, no build-copy)", group: "Text", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[Opt::Borrow], conflicts: &[], preempts: &[Opt::TextFromBytesBuilder], scope: ProgramOnly, work: OptWork::Same },
971    OptMeta { opt: Opt::StringConcatReuse, keyword: "stringconcatreuse", label: "String concat buffer reuse (Let X be A+B -> move+push_str, no format! realloc)", group: "Text", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
972    OptMeta { opt: Opt::StringRepeatLoop, keyword: "stringrepeatloop", label: "String repeat idiom (counted push_str loop -> chunk.repeat(n), presized)", group: "Text", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[], conflicts: &[], preempts: &[Opt::StringAccumReuse], scope: ProgramOnly, work: OptWork::Same },
973    OptMeta { opt: Opt::AsciiClassMask, keyword: "asciiclassmask", label: "ASCII-class predicate to branchless 256-bit mask (beats ctype LUT)", group: "Strings & SIMD", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
974    OptMeta { opt: Opt::StrengthReducePow2, keyword: "strengthreducepow2", label: "Power-of-two %/÷ to mask/shift on non-negative operands (unblocks vectorization)", group: "Arithmetic", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[Opt::ModWrap], scope: ProgramOnly, work: OptWork::Same },
975    OptMeta { opt: Opt::BranchlessAccumulate, keyword: "branchlessaccumulate", label: "Predicate-guarded increment if-conversion (branchless, vectorizable count)", group: "Arithmetic", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
976    OptMeta { opt: Opt::WideAccumulator, keyword: "wideaccumulator", label: "i128 widening of a bounded counting accumulator (plain add vectorizes, beats C)", group: "Arithmetic", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
977    OptMeta { opt: Opt::RadixDigitBuffer, keyword: "radixdigitbuffer", label: "itoa stack digit buffer (one [u8;64] back-to-front, no boxed Seq + no reversal, beats Go strconv)", group: "Text", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[], conflicts: &[], preempts: &[Opt::TextFromBytesBuilder, Opt::HoistBorrows], scope: ProgramOnly, work: OptWork::Same },
978    OptMeta { opt: Opt::ByteSliceReturn, keyword: "byteslicereturn", label: "Bytes zero-copy sub-slice return (&[i64], no build-copy)", group: "Bytes", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[Opt::Borrow], conflicts: &[], preempts: &[Opt::OracleHints, Opt::Unchecked], scope: ProgramOnly, work: OptWork::Same },
979    OptMeta { opt: Opt::Tile, keyword: "tile", label: "Loop tiling", group: "Loops", default_on: true, paths: AOT | CODEGEN, emits_unsafe: true, mem_class: Neutral, cost: Medium, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
980    OptMeta { opt: Opt::MaskNarrow, keyword: "masknarrow", label: "Masked integer chain at the mask's width (32-bit wrapping under & (2^k-1), k <= 32)", group: "Arithmetic", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[Opt::StrengthReducePow2], scope: Both, work: OptWork::Same },
981    OptMeta { opt: Opt::ModWrap, keyword: "modwrap", label: "Remainder of a value below twice its constant divisor as one conditional subtraction", group: "Arithmetic", default_on: true, paths: AOT | VM | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
982    OptMeta { opt: Opt::BranchlessSelect, keyword: "branchlessselect", label: "Two-armed integer assignment as a select of both guarded arms (no branch on the condition)", group: "Arithmetic", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
983    OptMeta { opt: Opt::VariantBox, keyword: "variantbox", label: "Recursive enum variant boxed whole (one box per node; a fieldless variant allocates nothing)", group: "Arrays & memory", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: ProgramOnly, work: OptWork::Same },
984    OptMeta { opt: Opt::BitPack, keyword: "bitpack", label: "Local Seq of Bool held one bit per item (an eighth of the memory; a sieve fits the cache)", group: "Arrays & memory", default_on: true, paths: AOT | CODEGEN, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[Opt::Unbox], conflicts: &[], preempts: &[Opt::HoistBorrows], scope: ProgramOnly, work: OptWork::Same },
985    OptMeta { opt: Opt::FoldFusion, keyword: "foldfuse", label: "A consumer of a datatype applied to what a builder builds of it, as one function that never builds it", group: "Inlining & calls", default_on: true, paths: AOT, emits_unsafe: false, mem_class: SavesMem, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
986    OptMeta { opt: Opt::SortNest, keyword: "sortnest", label: "A nest of adjacent compare-exchanges that sorts a window, as one in-place heap sort", group: "Loops", default_on: true, paths: AOT, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Less },
987    OptMeta { opt: Opt::DivisorSieve, keyword: "divisorsieve", label: "A per-number search for a divisor up to its square root, as one sieve of the range", group: "Loops", default_on: true, paths: AOT, emits_unsafe: false, mem_class: TradesMemForSpeed, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Less },
988    // TraceMemo preempts Peephole: the counted loop over starts it rewrites into a guarded walk of the table is
989    // no longer the `While i <= n` shape the peephole lowers to a range.
990    OptMeta { opt: Opt::TraceMemo, keyword: "tracememo", label: "A pure iteration run from every start of a range, stopped where it reaches a start already finished", group: "Loops", default_on: true, paths: AOT, emits_unsafe: false, mem_class: TradesMemForSpeed, cost: Cheap, requires: &[], conflicts: &[], preempts: &[Opt::Peephole], scope: Both, work: OptWork::Less },
991    OptMeta { opt: Opt::ProbeFuse, keyword: "probefuse", label: "A map's membership test and the reads of the same key under it, as one lookup", group: "Redundancy", default_on: true, paths: AOT, emits_unsafe: false, mem_class: Neutral, cost: Cheap, requires: &[], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
992    OptMeta { opt: Opt::StrideFill, keyword: "stridefill", label: "A loop storing one value into a bit-packed Seq of Bool at a fixed stride, as a fill that writes each word once", group: "Arrays & memory", default_on: true, paths: AOT, emits_unsafe: true, mem_class: Neutral, cost: Medium, requires: &[Opt::BitPack, Opt::Unchecked], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
993    OptMeta { opt: Opt::HintVersion, keyword: "hintversion", label: "The innermost loop with bounds hints as a copy that assumes them where they all hold and a copy that assumes none", group: "Bounds & checks", default_on: true, paths: AOT, emits_unsafe: true, mem_class: Neutral, cost: Medium, requires: &[Opt::OracleHints], conflicts: &[], preempts: &[], scope: Both, work: OptWork::Same },
994];
995
996/// Look up an optimization by its decorator keyword (case-insensitive).
997pub fn by_keyword(word: &str) -> Option<Opt> {
998    let w = word.to_ascii_lowercase();
999    REGISTRY.iter().find(|m| m.keyword == w).map(|m| m.opt)
1000}
1001
1002/// Produce a copy of `src` with a file-level `## No <keyword>` decorator inserted
1003/// (just before `## Main`, where the parser folds it into the program-wide config)
1004/// for each disabled-optimization keyword. This is what the benchmarks UI shows on
1005/// the Logos source when a toggle is flipped off; compiling the result applies the
1006/// same config the toggle represents.
1007pub fn decorate_source(src: &str, disabled_keywords: &[&str]) -> String {
1008    if disabled_keywords.is_empty() {
1009        return src.to_string();
1010    }
1011    let decorators: String = disabled_keywords
1012        .iter()
1013        .map(|kw| format!("## No {kw}\n"))
1014        .collect();
1015    match src.find("## Main") {
1016        Some(idx) => format!("{}{}{}", &src[..idx], decorators, &src[idx..]),
1017        None => format!("{src}{decorators}"),
1018    }
1019}
1020
1021/// Produce a copy of `src` with a file-level `## Tier <keyword> <value>` decorator
1022/// inserted (just before `## Main`, where the parser collects program-level tier
1023/// pins) for each `(keyword, value)` pair. The tiering analog of [`decorate_source`]:
1024/// the benchmarks UI injects these to pin an optimization to a tier exactly as it
1025/// injects `## No <X>` to disable one. `value` is one of `eager|t1|t2|t3|never`.
1026pub fn decorate_tiers(src: &str, pins: &[(&str, &str)]) -> String {
1027    if pins.is_empty() {
1028        return src.to_string();
1029    }
1030    let decorators: String = pins
1031        .iter()
1032        .map(|(kw, val)| format!("## Tier {kw} {val}\n"))
1033        .collect();
1034    match src.find("## Main") {
1035        Some(idx) => format!("{}{}{}", &src[..idx], decorators, &src[idx..]),
1036        None => format!("{src}{decorators}"),
1037    }
1038}
1039
1040/// Why `normalize` flipped an optimization off.
1041#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1042pub enum Reason {
1043    /// A required optimization was off.
1044    DependencyOff(Opt),
1045    /// A conflicting optimization (declared earlier) was on.
1046    ConflictWith(Opt),
1047}
1048
1049/// What `normalize` changed, so a UI can explain auto-disabled toggles.
1050#[derive(Debug, Clone, Default, PartialEq, Eq)]
1051pub struct NormalizeReport {
1052    /// Optimizations turned off by normalization, with the reason.
1053    pub auto_disabled: Vec<(Opt, Reason)>,
1054}
1055
1056impl NormalizeReport {
1057    /// Whether normalization changed anything.
1058    pub fn is_empty(&self) -> bool {
1059        self.auto_disabled.is_empty()
1060    }
1061}
1062
1063/// A live choice of which optimizations are enabled — one bit per [`Opt`].
1064///
1065/// The default is every optimization on (the speed-tuned baseline). Clearing
1066/// all bits yields plain, boring Rust.
1067#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
1068pub struct OptimizationConfig {
1069    enabled: OptBits,
1070}
1071
1072impl Default for OptimizationConfig {
1073    fn default() -> Self {
1074        Self::all_on()
1075    }
1076}
1077
1078impl OptimizationConfig {
1079    /// Every default-on optimization enabled (the speed baseline).
1080    pub fn all_on() -> Self {
1081        let mut enabled = OptBits::EMPTY;
1082        for m in REGISTRY {
1083            if m.default_on {
1084                enabled = enabled.with(m.opt);
1085            }
1086        }
1087        Self { enabled }
1088    }
1089
1090    /// No optimizations enabled — the "boring Rust" config.
1091    pub const fn all_off() -> Self {
1092        Self {
1093            enabled: OptBits::EMPTY,
1094        }
1095    }
1096
1097    /// Whether a given optimization is on.
1098    #[inline]
1099    pub const fn is_on(&self, opt: Opt) -> bool {
1100        self.enabled.contains(opt)
1101    }
1102
1103    /// Turn an optimization on or off.
1104    #[inline]
1105    pub fn set(&mut self, opt: Opt, on: bool) {
1106        self.enabled = if on {
1107            self.enabled.with(opt)
1108        } else {
1109            self.enabled.without(opt)
1110        };
1111    }
1112
1113    /// Turn an optimization off (builder style).
1114    pub fn disable(mut self, opt: Opt) -> Self {
1115        self.set(opt, false);
1116        self
1117    }
1118
1119    /// Turn an optimization on (builder style).
1120    pub fn enable(mut self, opt: Opt) -> Self {
1121        self.set(opt, true);
1122        self
1123    }
1124
1125    /// Turn `opt` on together with the transitive closure of what it `requires`.
1126    ///
1127    /// The complement of [`normalize`](Self::normalize)'s dependency-closure
1128    /// (which turns *dependents* off when a requirement goes off): enabling a
1129    /// leaf must pull its whole requires-chain on, or `normalize` would just turn
1130    /// the leaf back off. This is the on-direction of the UI's toggle-linking.
1131    pub fn enable_with_requires(&mut self, opt: Opt) {
1132        let mut visited = OptBits::EMPTY;
1133        let mut stack = vec![opt];
1134        while let Some(o) = stack.pop() {
1135            if visited.contains(o) {
1136                continue;
1137            }
1138            visited = visited.with(o);
1139            self.set(o, true);
1140            for &req in o.meta().requires {
1141                stack.push(req);
1142            }
1143        }
1144    }
1145
1146    /// Whether every optimization is off.
1147    pub const fn is_all_off(&self) -> bool {
1148        self.enabled.is_empty()
1149    }
1150
1151    /// The enabled set. Relates an [`OptimizationConfig`] to a [`FiredOptimizations`] set bit for bit.
1152    pub const fn bits(&self) -> OptBits {
1153        self.enabled
1154    }
1155
1156    /// Combine a program-level config with a function's per-function overrides:
1157    /// an optimization is on for the function only if it is on in both.
1158    pub const fn merged(&self, func: &OptimizationConfig) -> OptimizationConfig {
1159        OptimizationConfig {
1160            enabled: self.enabled.intersection(func.enabled),
1161        }
1162    }
1163
1164    /// The keywords of every optimization currently off (registry order).
1165    pub fn disabled_keywords(&self) -> impl Iterator<Item = &'static str> + '_ {
1166        REGISTRY
1167            .iter()
1168            .filter(move |m| !self.is_on(m.opt))
1169            .map(|m| m.keyword)
1170    }
1171
1172    /// Resolve conflicts and dependencies, returning what was auto-disabled.
1173    ///
1174    /// Conflicts: when two mutually exclusive optimizations are both on, the
1175    /// one declared earlier in [`REGISTRY`] wins and the later is disabled.
1176    /// Dependencies: any optimization whose `requires` set is not fully on is
1177    /// disabled (transitively, to a fixed point).
1178    pub fn normalize(&mut self) -> NormalizeReport {
1179        let mut report = NormalizeReport::default();
1180        if self.is_all_off() {
1181            return report;
1182        }
1183
1184        // Conflict resolution: earlier-declared optimization wins.
1185        for m in REGISTRY {
1186            if !self.is_on(m.opt) {
1187                continue;
1188            }
1189            for &other in m.conflicts {
1190                if (other as u8) < (m.opt as u8) && self.is_on(other) {
1191                    self.set(m.opt, false);
1192                    report
1193                        .auto_disabled
1194                        .push((m.opt, Reason::ConflictWith(other)));
1195                    break;
1196                }
1197            }
1198        }
1199
1200        // Dependency closure: disable anything whose requirement is off.
1201        loop {
1202            let mut changed = false;
1203            for m in REGISTRY {
1204                if !self.is_on(m.opt) {
1205                    continue;
1206                }
1207                for &req in m.requires {
1208                    if !self.is_on(req) {
1209                        self.set(m.opt, false);
1210                        report
1211                            .auto_disabled
1212                            .push((m.opt, Reason::DependencyOff(req)));
1213                        changed = true;
1214                        break;
1215                    }
1216                }
1217            }
1218            if !changed {
1219                break;
1220            }
1221        }
1222
1223        report
1224    }
1225
1226    /// Build a config from the environment, the single external entry point.
1227    ///
1228    /// - `LOGOS_OPT=off` (or `LOGOS_NO_OPTIMIZE=1`) disables everything.
1229    /// - `LOGOS_OPT_PROFILE=speed|memory|safety` selects a base profile.
1230    /// - `LOGOS_OPT_OFF="scalarize,unroll,…"` disables the listed keywords.
1231    ///
1232    /// The result is normalized.
1233    pub fn from_env() -> Self {
1234        let opt = std::env::var("LOGOS_OPT").ok();
1235        let no_opt = std::env::var("LOGOS_NO_OPTIMIZE").ok();
1236        let profile = std::env::var("LOGOS_OPT_PROFILE").ok();
1237        let off = std::env::var("LOGOS_OPT_OFF").ok();
1238        let master_off = opt.as_deref() == Some("off") || no_opt.as_deref() == Some("1");
1239        Self::from_spec(master_off, profile.as_deref(), off.as_deref())
1240    }
1241
1242    /// The pure, testable core of `from_env`. `master_off` disables everything;
1243    /// `profile` picks the base preset (speed by default); `off_list` is a
1244    /// comma/space/`;`-separated list of keywords to disable. The result is
1245    /// normalized.
1246    pub fn from_spec(master_off: bool, profile: Option<&str>, off_list: Option<&str>) -> Self {
1247        if master_off {
1248            return Self::all_off();
1249        }
1250
1251        let mut cfg = match profile {
1252            Some("memory") => Profile::Memory.config(),
1253            Some("safety") => Profile::Safety.config(),
1254            _ => Profile::Speed.config(),
1255        };
1256
1257        if let Some(list) = off_list {
1258            for tok in list.split([',', ' ', ';']) {
1259                let tok = tok.trim();
1260                if tok.is_empty() {
1261                    continue;
1262                }
1263                if let Some(opt) = by_keyword(tok) {
1264                    cfg.set(opt, false);
1265                }
1266            }
1267        }
1268
1269        cfg.normalize();
1270        cfg
1271    }
1272
1273    /// Build a config from a keyword→enabled map (e.g. UI toggles), returning
1274    /// the normalized config and the optimizations normalization forced off.
1275    pub fn from_toggles(toggles: &BTreeMap<String, bool>) -> (Self, Vec<Opt>) {
1276        let mut cfg = Self::all_on();
1277        for m in REGISTRY {
1278            if let Some(&on) = toggles.get(m.keyword) {
1279                cfg.set(m.opt, on);
1280            }
1281        }
1282        let before = cfg.enabled;
1283        let report = cfg.normalize();
1284        let _ = before;
1285        let forced = report.auto_disabled.iter().map(|(opt, _)| *opt).collect();
1286        (cfg, forced)
1287    }
1288}
1289
1290/// The benchmark-visible execution backend whose optimization decisions are
1291/// being traced. This is deliberately independent of [`path`]: `path` says
1292/// where an optimization is allowed statically, while this identifies the
1293/// concrete lowering that was asked to consume the optimized program.
1294#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1295pub enum OptimizationBackend {
1296    RustAot,
1297    CAst,
1298    CBytecode,
1299    TreeWalker,
1300    Vm,
1301    Jit,
1302}
1303
1304/// An explicit backend escape hatch taken while lowering. A fallback is data,
1305/// never a silent control-flow edge: benchmark tooling can ratchet this list to
1306/// zero without pretending the fallback backend performed the requested work.
1307#[derive(Debug, Clone, PartialEq, Eq)]
1308pub struct OptimizationFallback {
1309    pub from: OptimizationBackend,
1310    pub to: OptimizationBackend,
1311    pub reason: String,
1312}
1313
1314/// A supported optimization that a backend deliberately chose not to apply.
1315///
1316/// This is distinct from [`OptimizationFallback`]: a decline stays on the
1317/// requested backend and records a cost-model, proof, or capability decision;
1318/// a fallback changes the backend that executes the program. Keeping the two
1319/// channels separate lets benchmark ratchets reject silent backend changes
1320/// without also rejecting an explicitly justified profitability decision.
1321#[derive(Debug, Clone, PartialEq, Eq)]
1322pub struct OptimizationDecline {
1323    pub backend: OptimizationBackend,
1324    pub opt: Opt,
1325    pub reason: String,
1326}
1327
1328/// Stage-separated optimization evidence for one backend compile/run.
1329///
1330/// `optimizer` contains shared IR/AST transformations. `lowering` contains
1331/// choices that fired only while the selected backend emitted or compiled its
1332/// target. Keeping these sets separate is the ratchet: a shared pass reaching C
1333/// can no longer be mistaken for the C emitter actually preserving/consuming
1334/// its optimized form.
1335#[derive(Debug, Clone, PartialEq, Eq)]
1336pub struct BackendOptimizationTrace {
1337    pub backend: OptimizationBackend,
1338    pub optimizer: FiredOptimizations,
1339    pub lowering: FiredOptimizations,
1340    pub declines: Vec<OptimizationDecline>,
1341    pub fallbacks: Vec<OptimizationFallback>,
1342}
1343
1344impl BackendOptimizationTrace {
1345    /// Compatibility union used by the original single-bitset trace API.
1346    pub fn all_fired(&self) -> FiredOptimizations {
1347        let mut all = self.optimizer;
1348        all.merge(&self.lowering);
1349        all
1350    }
1351}
1352
1353/// Which optimizations actually FIRED during a single compile — one bit per
1354/// [`Opt`], the same bit layout as [`OptimizationConfig`]. An optimization is
1355/// "fired" when it actually changed the program or emitted its optimized form
1356/// for this compile, as distinct from merely being *enabled*. Populated only
1357/// while a firing trace is active (see `logicaffeine_compile`'s traced compile
1358/// entry points); the normal compile path never records into it.
1359#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1360pub struct FiredOptimizations {
1361    fired: OptBits,
1362}
1363
1364impl FiredOptimizations {
1365    /// An empty set — nothing fired.
1366    pub const fn new() -> Self {
1367        Self {
1368            fired: OptBits::EMPTY,
1369        }
1370    }
1371
1372    /// Build from a set of fired optimizations.
1373    pub const fn from_bits(fired: OptBits) -> Self {
1374        Self { fired }
1375    }
1376
1377    /// Record that `opt` fired.
1378    #[inline]
1379    pub fn mark(&mut self, opt: Opt) {
1380        self.fired = self.fired.with(opt);
1381    }
1382
1383    /// Whether `opt` fired.
1384    #[inline]
1385    pub const fn fired(&self, opt: Opt) -> bool {
1386        self.fired.contains(opt)
1387    }
1388
1389    /// Whether nothing fired.
1390    pub const fn is_empty(&self) -> bool {
1391        self.fired.is_empty()
1392    }
1393
1394    /// The fired set.
1395    pub const fn bits(&self) -> OptBits {
1396        self.fired
1397    }
1398
1399    /// Fold another set's fired bits into this one.
1400    pub fn merge(&mut self, other: &FiredOptimizations) {
1401        self.fired = self.fired.union(other.fired);
1402    }
1403
1404    /// The optimizations that fired, in registry order.
1405    pub fn opts(&self) -> Vec<Opt> {
1406        REGISTRY
1407            .iter()
1408            .filter(|m| self.fired(m.opt))
1409            .map(|m| m.opt)
1410            .collect()
1411    }
1412
1413    /// The decorator keywords of the optimizations that fired, in registry order.
1414    pub fn keywords(&self) -> Vec<&'static str> {
1415        REGISTRY
1416            .iter()
1417            .filter(|m| self.fired(m.opt))
1418            .map(|m| m.keyword)
1419            .collect()
1420    }
1421}
1422
1423/// Why an optimization appears in a program's [`relationship_tree`].
1424#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1425pub enum OptRole {
1426    /// It fired for this program.
1427    Fired,
1428    /// A `requires`-parent pulled in so a fired/preempted descendant has its
1429    /// dependency shown — it did not itself fire (e.g. `oracle` for a program
1430    /// that fires `unchecked` but produces no oracle-folded constant).
1431    Enabler,
1432    /// It had a candidate site but a higher-precedence optimization claimed it
1433    /// (a `preempts` loser) — it is enabled, and would fire if its winner were
1434    /// turned off. The "skipped because they don't play nice together" node.
1435    Preempted,
1436}
1437
1438/// One node of a program's optimization relationship tree: an optimization that
1439/// is *in play* for that program, with its nesting depth and its edges.
1440#[derive(Debug, Clone)]
1441pub struct OptNode {
1442    /// The optimization.
1443    pub opt: Opt,
1444    /// Nesting depth (0 = root) for tree indentation — under its `requires`-parent
1445    /// or its per-program dependency parent.
1446    pub depth: usize,
1447    /// Why it is in play.
1448    pub role: OptRole,
1449    /// Whether any in-play optimization depends on this one (drives the chevron).
1450    pub has_children: bool,
1451    /// What it requires (static, from the registry).
1452    pub requires: Vec<Opt>,
1453    /// What it takes precedence over (static, from the registry).
1454    pub preempts: Vec<Opt>,
1455    /// The winners that beat this optimization on THIS program (from the trace).
1456    pub preempted_by: Vec<Opt>,
1457    /// The optimizations this one only fired because of, on THIS program (the
1458    /// emergent dependencies the all-on evaluation revealed — distinct from the
1459    /// universal `requires`).
1460    pub depends_on: Vec<Opt>,
1461}
1462
1463/// The complete optimization chain for one program, derived deterministically
1464/// from a single all-optimizations-on evaluation plus the static registry graph —
1465/// no differential toggling in the hot path. `fired` is the set that fired;
1466/// `preempted` is the `(winner, loser)` BLOCKER pairs that occurred; `dependencies`
1467/// is the `(dependent, dep)` per-program DEPENDENCY pairs (one optimization only
1468/// fired because another was on) — all three come from the baked per-program graph
1469/// (`compile::optimization_graph`).
1470///
1471/// The in-play set is `fired ∪ {losers} ∪ {dependency endpoints} ∪ closure` over
1472/// the parent relation, where a node's parents are its static `requires` PLUS its
1473/// per-program dependencies: every opt that fired, every opt skipped because a
1474/// higher-precedence one claimed it, and the parents they hang under (so the tree
1475/// never orphans a child). Each node is placed by a depth-first walk along that
1476/// combined parent relation, parents before children. Closures over the fixed
1477/// 40-row registry — O(n²), and the same for identical input.
1478pub fn relationship_tree(
1479    fired: &[Opt],
1480    preempted: &[(Opt, Opt)],
1481    dependencies: &[(Opt, Opt)],
1482) -> Vec<OptNode> {
1483    let n = REGISTRY.len();
1484    let idx = |o: Opt| o as usize;
1485
1486    // A node's parents for nesting: its static `requires` PLUS the per-program
1487    // dependencies it only fired because of.
1488    let parents_of = |y: usize| -> Vec<usize> {
1489        let yopt = REGISTRY[y].opt;
1490        let mut ps: Vec<usize> = REGISTRY[y].requires.iter().map(|&r| idx(r)).collect();
1491        for &(dep, on) in dependencies {
1492            if dep == yopt {
1493                ps.push(idx(on));
1494            }
1495        }
1496        ps.sort_unstable();
1497        ps.dedup();
1498        ps
1499    };
1500
1501    // 1. The in-play set: seed with fired + blockers' losers + dependency
1502    //    endpoints, then pull in the transitive parent-closure.
1503    let mut want = vec![false; n];
1504    for &o in fired {
1505        want[idx(o)] = true;
1506    }
1507    for &(_, loser) in preempted {
1508        want[idx(loser)] = true;
1509    }
1510    for &(dep, on) in dependencies {
1511        want[idx(dep)] = true;
1512        want[idx(on)] = true;
1513    }
1514    loop {
1515        let mut changed = false;
1516        for i in 0..n {
1517            if want[i] {
1518                for p in parents_of(i) {
1519                    if !want[p] {
1520                        want[p] = true;
1521                        changed = true;
1522                    }
1523                }
1524            }
1525        }
1526        if !changed {
1527            break;
1528        }
1529    }
1530
1531    // 2. Role for each in-play opt: Fired wins over Preempted wins over Enabler
1532    //    (an opt that fired somewhere but was preempted on one instance is still
1533    //    Fired — the per-instance loss is shown as a live annotation, not a role).
1534    let fired_set: Vec<bool> = {
1535        let mut v = vec![false; n];
1536        for &o in fired {
1537            v[idx(o)] = true;
1538        }
1539        v
1540    };
1541    let loser_set: Vec<bool> = {
1542        let mut v = vec![false; n];
1543        for &(_, l) in preempted {
1544            v[idx(l)] = true;
1545        }
1546        v
1547    };
1548    let role_of = |i: usize| {
1549        if fired_set[i] {
1550            OptRole::Fired
1551        } else if loser_set[i] {
1552            OptRole::Preempted
1553        } else {
1554            OptRole::Enabler
1555        }
1556    };
1557
1558    // 3. Depth-first order along the combined parent relation: roots are in-play
1559    //    opts with no in-play parent; children are in-play opts that hang under the
1560    //    current one (require it, or depend on it for this program).
1561    let parent_in_want = |i: usize| parents_of(i).iter().any(|&p| want[p]);
1562    let mut order: Vec<(usize, usize)> = Vec::new();
1563    let mut visited = vec![false; n];
1564    let roots: Vec<usize> = (0..n).filter(|&i| want[i] && !parent_in_want(i)).collect();
1565    let mut stack: Vec<(usize, usize)> = roots.iter().rev().map(|&i| (i, 0usize)).collect();
1566    while let Some((i, depth)) = stack.pop() {
1567        if visited[i] {
1568            continue;
1569        }
1570        visited[i] = true;
1571        order.push((i, depth));
1572        let kids: Vec<usize> = (0..n)
1573            .filter(|&j| want[j] && !visited[j] && parents_of(j).contains(&i))
1574            .collect();
1575        for &k in kids.iter().rev() {
1576            stack.push((k, depth + 1));
1577        }
1578    }
1579    // Any in-play opt not reached by the walk (defensive; multi-parent diamonds
1580    // are already handled by `visited`) is appended at depth 0.
1581    for i in 0..n {
1582        if want[i] && !visited[i] {
1583            order.push((i, 0));
1584        }
1585    }
1586
1587    // 4. Materialize the nodes.
1588    order
1589        .into_iter()
1590        .map(|(i, depth)| {
1591            let opt = REGISTRY[i].opt;
1592            let has_children = (0..n).any(|j| want[j] && parents_of(j).contains(&i));
1593            let preempted_by: Vec<Opt> = preempted
1594                .iter()
1595                .filter(|&&(_, l)| l == opt)
1596                .map(|&(w, _)| w)
1597                .collect();
1598            let depends_on: Vec<Opt> = dependencies
1599                .iter()
1600                .filter(|&&(d, _)| d == opt)
1601                .map(|&(_, x)| x)
1602                .collect();
1603            OptNode {
1604                opt,
1605                depth,
1606                role: role_of(i),
1607                has_children,
1608                requires: REGISTRY[i].requires.to_vec(),
1609                preempts: REGISTRY[i].preempts.to_vec(),
1610                preempted_by,
1611                depends_on,
1612            }
1613        })
1614        .collect()
1615}
1616
1617/// A named optimization preset.
1618#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1619pub enum Profile {
1620    /// Everything on (the default).
1621    Speed,
1622    /// Drop optimizations that spend memory for speed.
1623    Memory,
1624    /// Drop optimizations that can emit `unsafe` Rust.
1625    Safety,
1626}
1627
1628impl Profile {
1629    /// The (normalized) config this profile produces.
1630    pub fn config(self) -> OptimizationConfig {
1631        let mut cfg = OptimizationConfig::all_on();
1632        match self {
1633            Profile::Speed => {}
1634            Profile::Memory => {
1635                for m in REGISTRY {
1636                    if m.mem_class == MemClass::TradesMemForSpeed {
1637                        cfg.set(m.opt, false);
1638                    }
1639                }
1640            }
1641            Profile::Safety => {
1642                for m in REGISTRY {
1643                    if m.emits_unsafe {
1644                        cfg.set(m.opt, false);
1645                    }
1646                }
1647            }
1648        }
1649        cfg.normalize();
1650        cfg
1651    }
1652}
1653
1654#[cfg(test)]
1655#[path = "../../logicaffeine_tests/unit/logicaffeine_language/optimization/tests.rs"]
1656mod tests;