diff --git a/crates/celox-analysis/src/memory_ssa.rs b/crates/celox-analysis/src/memory_ssa.rs index 45a7fffac7f..39b4a803895 100644 --- a/crates/celox-analysis/src/memory_ssa.rs +++ b/crates/celox-analysis/src/memory_ssa.rs @@ -180,9 +180,25 @@ pub struct ClobberWalker { epochs: Vec, states: Vec, results: Vec>, + /// Whether a resolved access's walk met an unresolved cycle. + cyclic: Vec, epoch: u32, frames: Vec, - values: Vec, + /// Results with whether their walk met an unresolved cycle. + values: Vec<(ClobberResolution, bool)>, +} + +/// Clobbers of one alias query over one graph, kept across query sessions. +/// +/// It holds only accesses whose walk met no unresolved cycle. Such a walk +/// covers an acyclic part of the graph, which determines its result whatever +/// the session's start points, so a later session resolves the access to the +/// same result without walking it again. Accesses whose walk met a cycle +/// depend on the MemoryPhi being resolved and are walked again in each +/// session, as without the memo. +#[derive(Debug, Default)] +pub struct ClobberMemo { + results: fxhash::FxHashMap, } impl ClobberWalker { @@ -223,20 +239,40 @@ impl ClobberWalker { self.epochs.fill(0); self.epoch = 1; } + self.cyclic.resize(graph.nodes.len(), false); ClobberQuery { walker: self, graph, query, alias_oracle, + memo: None, } } + /// Like [`Self::query`], reusing and extending `memo`, which must only + /// ever be used with this graph and an equal query and alias oracle. + pub fn query_memoized<'a, D, Q, A>( + &'a mut self, + graph: &'a MemoryAccessGraph, + query: &'a Q, + alias_oracle: &'a A, + memo: &'a mut ClobberMemo, + ) -> ClobberQuery<'a, D, Q, A> + where + A: AliasOracle, + { + let mut session = self.query(graph, query, alias_oracle); + session.memo = Some(memo); + session + } + fn find_clobber( &mut self, nodes: &[MemoryAccessNode], start: usize, query: &Q, alias_oracle: &impl AliasOracle, + mut memo: Option<&mut ClobberMemo>, ) -> MemoryClobber { let current_epoch = self.epoch; self.frames.clear(); @@ -248,24 +284,32 @@ impl ClobberWalker { ResolveFrame::Enter(access) => { if self.epochs[access] == current_epoch && self.states[access] != 0 { match self.states[access] { - 1 => self.values.push(ClobberResolution::Cycle), - 2 => self.values.push( + 1 => self.values.push((ClobberResolution::Cycle, true)), + 2 => self.values.push(( self.results[access] .expect("a resolved clobber node retains its result"), - ), + self.cyclic[access], + )), _ => unreachable!("current-epoch clobber state is valid"), } continue; } self.epochs[access] = current_epoch; + if let Some(&result) = memo.as_ref().and_then(|memo| memo.results.get(&access)) + { + let result = ClobberResolution::Access(result); + self.states[access] = 2; + self.results[access] = Some(result); + self.cyclic[access] = false; + self.values.push((result, false)); + continue; + } self.states[access] = 1; self.results[access] = None; match &nodes[access] { MemoryAccessNode::LiveOnEntry => { let result = ClobberResolution::Access(access); - self.states[access] = 2; - self.results[access] = Some(result); - self.values.push(result); + self.resolve(access, result, false, &mut memo); } MemoryAccessNode::Definition { definition, @@ -273,9 +317,7 @@ impl ClobberWalker { } => { if alias_oracle.may_alias(definition, query) { let result = ClobberResolution::Access(access); - self.states[access] = 2; - self.results[access] = Some(result); - self.values.push(result); + self.resolve(access, result, false, &mut memo); } else { self.frames.push(ResolveFrame::FinishDefinition(access)); self.frames.push(ResolveFrame::Enter(previous.0)); @@ -296,7 +338,7 @@ impl ClobberWalker { } } ResolveFrame::FinishDefinition(access) => { - let result = self + let (result, cyclic) = self .values .pop() .expect("a MemoryDef predecessor produces one clobber result"); @@ -305,11 +347,10 @@ impl ClobberWalker { // resolved independently of the active MemoryPhi. self.states[access] = 0; self.results[access] = None; + self.values.push((result, cyclic)); } else { - self.states[access] = 2; - self.results[access] = Some(result); + self.resolve(access, result, cyclic, &mut memo); } - self.values.push(result); } ResolveFrame::FinishPhi { access, inputs } => { let first = self @@ -319,7 +360,9 @@ impl ClobberWalker { .expect("every MemoryPhi input produces one clobber result"); let mut common = None::; let mut diverged = false; - for result in self.values.drain(first..) { + let mut cyclic = false; + for (result, input_cyclic) in self.values.drain(first..) { + cyclic |= input_cyclic; if result == ClobberResolution::Cycle { continue; } @@ -334,14 +377,12 @@ impl ClobberWalker { } else { common.unwrap_or(ClobberResolution::Access(access)) }; - self.states[access] = 2; - self.results[access] = Some(result); - self.values.push(result); + self.resolve(access, result, cyclic, &mut memo); } } } - let resolution = self + let (resolution, _) = self .values .pop() .expect("one clobber query produces one result"); @@ -351,6 +392,24 @@ impl ClobberWalker { ClobberResolution::Cycle => MemoryClobber::Indeterminate, } } + + /// Record `access` as resolved to `result` in this session, and in `memo` + /// when its walk met no unresolved cycle. + fn resolve( + &mut self, + access: usize, + result: ClobberResolution, + cyclic: bool, + memo: &mut Option<&mut ClobberMemo>, + ) { + self.states[access] = 2; + self.results[access] = Some(result); + self.cyclic[access] = cyclic; + if let (false, ClobberResolution::Access(result), Some(memo)) = (cyclic, result, memo) { + memo.results.insert(access, result); + } + self.values.push((result, cyclic)); + } } /// Multi-point clobber query for one immutable alias query. Resolving a phi @@ -361,6 +420,7 @@ pub struct ClobberQuery<'a, D, Q, A> { graph: &'a MemoryAccessGraph, query: &'a Q, alias_oracle: &'a A, + memo: Option<&'a mut ClobberMemo>, } impl ClobberQuery<'_, D, Q, A> @@ -369,8 +429,13 @@ where { pub fn clobber(&mut self, start: MemoryAccessId) -> Option { (start.0 < self.graph.nodes.len()).then(|| { - self.walker - .find_clobber(&self.graph.nodes, start.0, self.query, self.alias_oracle) + self.walker.find_clobber( + &self.graph.nodes, + start.0, + self.query, + self.alias_oracle, + self.memo.as_deref_mut(), + ) }) } } @@ -1005,6 +1070,107 @@ mod tests { assert_eq!(analysis.graph.access_count(), 2); } + /// Sessions sharing a memo resolve every start exactly as fresh + /// sessions do, over random CFGs with loops, joins and disjoint, + /// overlapping and repeated stores. + #[test] + fn memoized_sessions_match_fresh_sessions() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = |bound: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % bound as u64) as usize + }; + let mut cases = 0; + let mut memo_calls = 0; + let mut fresh_calls = 0; + for _ in 0..400 { + let blocks = 1 + next(7); + let successors = (0..blocks) + .map(|block| { + let mut outgoing = Vec::new(); + if block + 1 < blocks { + outgoing.push(block + 1); + } + for _ in 0..next(3) { + outgoing.push(next(blocks)); + } + outgoing + }) + .collect::>(); + let Ok(cfg) = ControlFlowGraph::analyze(successors, 0) else { + continue; + }; + let events = (0..blocks) + .map(|block| { + (0..next(4)) + .map(|index| { + let writes = if next(3) == 0 { + vec![] + } else { + vec![exact(1, 4 * next(4) as i64, 4 * (1 + next(2)))] + }; + event((block, index), vec![], writes) + }) + .collect::>() + }) + .collect::>(); + let analysis = analyze(&cfg, &events); + let accesses = analysis.graph.access_count(); + let calls = std::cell::Cell::new(0usize); + let oracle = |definition: &Instruction, query: &MemoryEffect| { + calls.set(calls.get() + 1); + analysis.writes[definition] + .iter() + .copied() + .any(|write| effects_may_alias(write, *query)) + }; + for _ in 0..4 { + let query = exact(1, 4 * next(4) as i64, 4 * (1 + next(2))); + let sessions = (0..1 + next(6)) + .map(|_| { + (0..1 + next(4)) + .map(|_| MemoryAccessId(next(accesses))) + .collect::>() + }) + .collect::>(); + let mut fresh_walker = ClobberWalker::new(); + calls.set(0); + let fresh = sessions + .iter() + .map(|starts| { + let mut session = fresh_walker.query(&analysis.graph, &query, &oracle); + starts + .iter() + .map(|&start| session.clobber(start)) + .collect::>() + }) + .collect::>(); + fresh_calls += calls.get(); + let mut walker = ClobberWalker::new(); + let mut memo = ClobberMemo::default(); + calls.set(0); + let memoized = sessions + .iter() + .map(|starts| { + let mut session = + walker.query_memoized(&analysis.graph, &query, &oracle, &mut memo); + starts + .iter() + .map(|&start| session.clobber(start)) + .collect::>() + }) + .collect::>(); + memo_calls += calls.get(); + assert_eq!(memoized, fresh, "{sessions:?} {query:?} {events:?}"); + } + cases += 1; + } + assert!(cases > 200, "{cases}"); + assert!(memo_calls < fresh_calls, "{memo_calls} {fresh_calls}"); + } + #[test] fn custom_alias_domain_needs_no_memory_effect_types() { let cfg = ControlFlowGraph::analyze(vec![vec![]], 0).unwrap(); diff --git a/crates/celox-backend-x86/src/backend/native/regalloc/reload.rs b/crates/celox-backend-x86/src/backend/native/regalloc/reload.rs index b925852f893..50255234cc7 100644 --- a/crates/celox-backend-x86/src/backend/native/regalloc/reload.rs +++ b/crates/celox-backend-x86/src/backend/native/regalloc/reload.rs @@ -11,8 +11,8 @@ use std::fmt; use celox_analysis::memory::{MemoryEffect, MemoryLocation, effects_may_alias}; use celox_analysis::memory_ssa::{ - self, ClobberWalker, MemoryAccess, MemoryAccessEvent, MemoryAccessGraph, MemoryAccessId, - MemoryClobber, MemoryPointMap, + self, ClobberMemo, ClobberWalker, MemoryAccess, MemoryAccessEvent, MemoryAccessGraph, + MemoryAccessId, MemoryClobber, MemoryPointMap, }; use crate::HashMap; @@ -1221,6 +1221,9 @@ struct ReloadMemorySsa { block_ids: Vec, walker: ClobberWalker, clobber_cache: HashMap<(StateLoad, MemoryAccessId), MemoryAccessId>, + /// Clobbers already walked for each queried byte range, so queries from + /// different starts do not walk the same definitions again. + clobber_memos: HashMap<(i64, usize), ClobberMemo>, } impl ReloadMemorySsa { @@ -1273,6 +1276,10 @@ impl ReloadMemorySsa { let writes = &self.writes; let block_ids = &self.block_ids; let clobber_cache = &mut self.clobber_cache; + let memo = self + .clobber_memos + .entry((bytes.start, byte_len)) + .or_default(); let oracle = |definition: &MemoryDefinition, query: &MemoryEffect| { writes .get(definition.write_index..definition.write_end) @@ -1283,7 +1290,7 @@ impl ReloadMemorySsa { .any(|write| effects_may_alias(write, *query)) }) }; - let mut clobber_query = self.walker.query(graph, &query, &oracle); + let mut clobber_query = self.walker.query_memoized(graph, &query, &oracle, memo); let mut clobber_access = |start| { if let Some(&access) = clobber_cache.get(&(load, start)) { return Ok(access); @@ -2228,6 +2235,7 @@ fn build_reload_memory_ssa( writes, block_ids: func.blocks.iter().map(|block| block.id).collect(), walker: ClobberWalker::new(), + clobber_memos: HashMap::default(), clobber_cache: HashMap::default(), }) } diff --git a/crates/celox-sir-opt/src/optimizer/passes/analysis/control_region_feasibility.rs b/crates/celox-sir-opt/src/optimizer/passes/analysis/control_region_feasibility.rs index 626feadfd72..7f2b6958dbc 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/analysis/control_region_feasibility.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/analysis/control_region_feasibility.rs @@ -18,8 +18,8 @@ use super::sir_analysis::{UseSite, collect_uses, instruction_uses}; use super::state_ssa::StateSsa; use crate::ir::cfg::SirCfg; use crate::ir::{ - BinaryOp, BlockId, ExecutionUnit, RegionedAbsoluteAddr, RegisterId, SIRInstruction, SIROffset, - SIRTerminator, SIRValue, UnaryOp, + BinaryOp, BlockId, ExecutionUnit, RegionedAbsoluteAddr, RegisterId, RegisterType, + SIRInstruction, SIROffset, SIRTerminator, SIRValue, UnaryOp, }; use crate::{HashMap, HashSet}; @@ -2014,6 +2014,7 @@ pub(crate) fn plan_best_effect_case_dispatch( )) }); + let mut load_versions = LoadVersions::new(eu, &cfg); candidates .into_iter() .find_map(|(saving, _, origin, group)| { @@ -2030,6 +2031,7 @@ pub(crate) fn plan_best_effect_case_dispatch( &incoming_values, &predecessors, &cfg, + &mut load_versions, ) }) } @@ -2048,6 +2050,7 @@ fn build_effect_case_rewrite_plan( incoming_values: &HashMap>, predecessors: &HashMap>, cfg: &SirCfg, + load_versions: &mut LoadVersions<'_>, ) -> Option { let cross_block = cross_block_selector_closure( eu, @@ -2149,7 +2152,14 @@ fn build_effect_case_rewrite_plan( known_values: recipe.known_values.clone(), }; if recipe.non_dominating_control_merges.is_empty() { - if !loads_are_stable_at(eu, cfg, definitions, sink.0, &recipe.load_frontier) { + if !loads_are_stable_at( + eu, + cfg, + definitions, + load_versions, + sink.0, + &recipe.load_frontier, + ) { return None; } sink_cases.push(executable); @@ -2172,6 +2182,7 @@ fn build_effect_case_rewrite_plan( eu, cfg, definitions, + load_versions, insertion_block, &recipe.load_frontier, ) { @@ -2283,7 +2294,167 @@ fn recipe_is_available_at_entry( }) } +/// An exact static state location: address, bit offset and width. +type ExactLocation = (RegionedAbsoluteAddr, usize, usize); + +/// Whether a two-state exact access of `width` bits through a register of +/// type `ty` gives its location a valid slot type (see `StateSsa`). +fn exact_access_typed(ty: Option<&RegisterType>, width: usize) -> bool { + ty.is_some_and(|ty| width != 0 && ty.width() == width) +} + +/// Load versions of one execution unit, shared by the stability checks of +/// all its sink recipes. +/// +/// A recipe's loads are stable at a block when each still reads the state +/// version it read originally. Analyzing each recipe's loads separately +/// scans the whole unit once per recipe. State SSA versions an exact +/// location from that location's own definitions and kills, so one analysis +/// selecting every load of a region versions each location as an analysis +/// selecting fewer loads does. What depends on the selection is which +/// locations get a slot and whether their types are valid: +/// - The shared analysis leaves out the loads that make their location +/// invalid in every selection containing them. Such a load has no version +/// there, as in its recipe's own analysis, so the recipe is not stable. +/// - A static load gives its location a slot, which a packed load of the +/// same bits then also reads; `loads_are_stable_at` checks per recipe +/// that the recipe has such a static load. +struct LoadVersions<'a> { + eu: &'a ExecutionUnit, + cfg: &'a SirCfg, + regions: BTreeMap>, +} + +impl<'a> LoadVersions<'a> { + fn new(eu: &'a ExecutionUnit, cfg: &'a SirCfg) -> Self { + Self { + eu, + cfg, + regions: BTreeMap::new(), + } + } + + /// The shared versions of `region`, or `None` when its analysis fails. + fn region(&mut self, region: u32) -> Option<&StateSsa> { + let (eu, cfg) = (self.eu, self.cfg); + self.regions + .entry(region) + .or_insert_with(|| Self::analyze(eu, cfg, region)) + .as_ref() + } + + fn analyze( + eu: &ExecutionUnit, + cfg: &SirCfg, + region: u32, + ) -> Option { + let instructions = || { + cfg.block_ids + .iter() + .flat_map(|block| &eu.blocks[block].instructions) + }; + // An exact store without a valid type makes its location invalid in + // every selection, as does a load without one. + let invalid = instructions() + .filter_map(|instruction| match instruction { + SIRInstruction::Store( + address, + SIROffset::Static(bit_offset), + width, + source, + .., + ) if address.region == region + && !exact_access_typed(eu.register_map.get(source), *width) => + { + Some((*address, *bit_offset, *width)) + } + _ => None, + }) + .collect::>(); + let loads = instructions() + .filter_map(|instruction| match instruction { + SIRInstruction::Load( + destination, + address, + SIROffset::Static(bit_offset), + width, + ) if address.region == region => { + (exact_access_typed(eu.register_map.get(destination), *width) + && !invalid.contains(&(*address, *bit_offset, *width))) + .then_some(*destination) + } + SIRInstruction::Load(destination, address, SIROffset::PackedElements { .. }, _) + if address.region == region => + { + Some(*destination) + } + _ => None, + }) + .collect::>(); + StateSsa::analyze_selected_loads_two_state(eu, cfg, region, &loads).ok() + } +} + +/// Whether every load in `loads` still reads its original state version on +/// entry to `target`, as `loads_are_stable_at_by_analysis` decides, from +/// the unit's shared load versions. fn loads_are_stable_at( + eu: &ExecutionUnit, + cfg: &SirCfg, + definitions: &HashMap, + versions: &mut LoadVersions<'_>, + target: BlockId, + loads: &BTreeSet, +) -> bool { + let mut sites = Vec::with_capacity(loads.len()); + for ®ister in loads { + let Some(site) = definitions.get(®ister) else { + return false; + }; + let SIRInstruction::Load(_, address, offset, width) = + &eu.blocks[&site.block].instructions[site.index] + else { + return false; + }; + sites.push((register, site, *address, offset, *width)); + } + if sites + .iter() + .any(|(_, _, address, ..)| versions.region(address.region).is_none()) + { + return loads_are_stable_at_by_analysis(eu, cfg, definitions, target, loads); + } + // The locations an analysis of just these loads gives a slot. + let locations = sites + .iter() + .filter_map(|(_, _, address, offset, width)| match offset { + SIROffset::Static(bit_offset) => Some((*address, *bit_offset, *width)), + _ => None, + }) + .collect::>(); + sites + .iter() + .all(|(register, site, address, offset, width)| { + let (SIROffset::Static(bit_offset) | SIROffset::PackedElements { bit_offset, .. }) = + offset + else { + return false; + }; + if !locations.contains(&(*address, *bit_offset, *width)) { + return false; + } + versions.region(address.region).is_some_and(|state| { + state + .read_version(site.block, site.index, *register) + .is_some_and(|(slot, original)| { + state.entry_version(target, slot) == Some(original) + }) + }) + }) +} + +/// `loads_are_stable_at` by an analysis of just `loads`. +fn loads_are_stable_at_by_analysis( eu: &ExecutionUnit, cfg: &SirCfg, definitions: &HashMap, @@ -2405,6 +2576,160 @@ mod tests { ) } + /// Shared load versions decide every selection of loads as an analysis + /// of just those loads does, over random units with branches, a loop, + /// overlapping exact accesses, packed, dynamic and mistyped accesses. + #[test] + fn shared_load_versions_match_per_recipe_analysis() { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = |bound: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % bound as u64) as usize + }; + // 0 -> {1, 2} -> 3 -> {3, 4} + let successors = [vec![1, 2], vec![3], vec![3], vec![3, 4], vec![]]; + let mut checked = 0; + let mut stable = 0; + for _ in 0..300 { + let mut register_map = HashMap::default(); + let mut registers = 0; + let mut register = |ty: Option, map: &mut HashMap<_, _>| { + registers += 1; + let id = RegisterId(registers); + if let Some(ty) = ty { + map.insert(id, ty); + } + id + }; + let condition = register(Some(bit(1)), &mut register_map); + let index = register(Some(bit(2)), &mut register_map); + let mut loads = Vec::new(); + let blocks = successors + .iter() + .enumerate() + .map(|(block, successors)| { + let mut instructions = Vec::new(); + for _ in 0..next(5) { + let width = if next(10) == 0 { 0 } else { 4 * (1 + next(2)) }; + let bit_offset = 4 * next(3); + // Mostly well typed; sometimes the wrong width or no + // register type at all. + let ty = match next(8) { + 0 => None, + 1 => Some(bit(width + 1)), + 2 => Some(logic(width)), + _ => Some(bit(width)), + }; + let addr = address(next(2) as u32); + let value = register(ty, &mut register_map); + match next(6) { + 0 | 1 => instructions.push(SIRInstruction::Store( + addr, + SIROffset::Static(bit_offset), + width, + value, + Vec::new(), + Vec::new(), + )), + 2 => { + instructions.push(SIRInstruction::Load( + value, + addr, + SIROffset::PackedElements { + bit_offset, + element_width: 4, + }, + width, + )); + loads.push(value); + } + 3 if next(3) == 0 => { + instructions.push(SIRInstruction::Load( + value, + addr, + SIROffset::Dynamic(index), + width, + )); + loads.push(value); + } + _ => { + instructions.push(SIRInstruction::Load( + value, + addr, + SIROffset::Static(bit_offset), + width, + )); + loads.push(value); + } + } + } + let terminator = match successors.as_slice() { + [] => SIRTerminator::Return, + [target] => SIRTerminator::Jump(BlockId(*target), vec![]), + [then, otherwise] => SIRTerminator::Branch { + cond: condition, + true_block: (BlockId(*then), vec![]), + false_block: (BlockId(*otherwise), vec![]), + }, + _ => unreachable!(), + }; + ( + BlockId(block), + BasicBlock { + id: BlockId(block), + params: vec![], + instructions, + terminator, + }, + ) + }) + .collect(); + let eu = ExecutionUnit { + entry_block_id: BlockId(0), + blocks, + register_map, + }; + let cfg = SirCfg::analyze_structure(&eu).unwrap(); + let definitions = collect_definition_sites(&eu); + let mut versions = LoadVersions::new(&eu, &cfg); + for _ in 0..12 { + let selection = loads + .iter() + .copied() + .filter(|_| next(3) == 0) + .collect::>(); + for target in 0..successors.len() { + let target = BlockId(target); + let expected = loads_are_stable_at_by_analysis( + &eu, + &cfg, + &definitions, + target, + &selection, + ); + assert_eq!( + loads_are_stable_at( + &eu, + &cfg, + &definitions, + &mut versions, + target, + &selection + ), + expected, + "{selection:?} at {target:?} in {eu:?}" + ); + checked += 1; + stable += usize::from(expected && !selection.is_empty()); + } + } + } + assert!(checked > 10_000, "{checked}"); + assert!(stable > 100, "{stable}"); + } + #[test] fn exact_case_guard_requires_the_adjacent_one_bit_normalization_chain() { let selector = RegisterId(0); diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 3ac3ac1a18e..eb1e030dd2d 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -177,7 +177,7 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { simulate_sv(simulation, max_steps, &mut std::io::stdout().lock()) }}; } - match arguments.execution.backend { + match arguments.execution.backend() { runner::Backend::Native => execute!(build), runner::Backend::Cranelift => execute!(build_cranelift), runner::Backend::Interpreter => execute!(build_interpreter), diff --git a/crates/celox-vpi/src/bin/celox/runner.rs b/crates/celox-vpi/src/bin/celox/runner.rs index 802e60033c9..cb25cfc3b1a 100644 --- a/crates/celox-vpi/src/bin/celox/runner.rs +++ b/crates/celox-vpi/src/bin/celox/runner.rs @@ -30,8 +30,11 @@ macro_rules! report { #[derive(Args, Default)] pub(super) struct ExecutionArgs { - #[arg(long, value_enum, default_value = "native")] - pub backend: Backend, + /// Defaults to `tiered`, or to `native` when an option needs native code + /// (compile-only, native images, the build cache or IR dumps) and in + /// cross-codegen builds. + #[arg(long, value_enum)] + backend: Option, #[arg(long)] compile_only: bool, /// Write a pointer-free native image during compile-only mode. @@ -74,6 +77,26 @@ pub(super) struct ExecutionArgs { } impl ExecutionArgs { + pub(super) fn backend(&self) -> Backend { + self.backend.unwrap_or( + // A cross-codegen build only exports foreign native images. + if cfg!(any( + all(target_arch = "x86_64", feature = "arm64-codegen"), + all(target_arch = "aarch64", feature = "x86_64-codegen") + )) || self.compile_only + || self.native_image_output.is_some() + || self.native_image_input.is_some() + || self.build_cache_dir.is_some() + || self.dump_ir_dir.is_some() + || self.dump_ir_and_run + { + Backend::Native + } else { + Backend::Tiered + }, + ) + } + #[cfg(feature = "systemverilog")] pub(super) fn validate_sv(&self) -> Result<(), String> { if self.compile_only @@ -149,9 +172,8 @@ pub(super) enum RunError { TestFailed { message: String }, } -#[derive(Clone, Copy, Default, PartialEq, ValueEnum)] +#[derive(Clone, Copy, PartialEq, ValueEnum)] pub(super) enum Backend { - #[default] Native, Cranelift, Interpreter, @@ -182,6 +204,7 @@ pub(super) fn run( design: super::project::Design, max_steps: u64, ) -> Result<(), RunError> { + let backend = cli.backend(); let mut opts = Options { report: cli.report, require_compiled: cli.require_compiled, @@ -194,7 +217,7 @@ pub(super) fn run( }), test: design.top.clone(), opt_level: design.opt_level.unwrap_or(OptLevel::O2), - backend: cli.backend, + backend, four_state: design.four_state.unwrap_or(false), compile_only: cli.compile_only, native_image_output: cli.native_image_output, diff --git a/crates/celox-vpi/tests/run_cli.rs b/crates/celox-vpi/tests/run_cli.rs index e68b2bfb196..4c3a66abbf5 100644 --- a/crates/celox-vpi/tests/run_cli.rs +++ b/crates/celox-vpi/tests/run_cli.rs @@ -365,6 +365,25 @@ fn veryl_backends_share_cli_execution_and_opt_in_reports() { assert!(output.stdout.is_empty(), "{output:?}"); } +#[cfg(not(any( + all(target_arch = "x86_64", feature = "arm64-codegen"), + all(target_arch = "aarch64", feature = "x86_64-codegen") +)))] +#[test] +fn backend_defaults_to_tiered_unless_native_code_is_requested() { + let source = + "#[test(Top)] module Top { inst clk: $tb::clock_gen; initial { clk.next(4); $finish(); } }"; + let output = run(&[("top.veryl", source)], &["--report"]); + assert!(output.status.success(), "{output:?}"); + let report = String::from_utf8(output.stdout).unwrap(); + assert!(report.contains("backend=tiered "), "{report}"); + + let output = run(&[("top.veryl", source)], &["--report", "--compile-only"]); + assert!(output.status.success(), "{output:?}"); + let report = String::from_utf8(output.stdout).unwrap(); + assert!(report.contains("backend=native "), "{report}"); +} + #[cfg(feature = "systemverilog")] #[test] fn sv_defaults_to_two_state_and_four_state_is_explicit() { diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index 65123edabbd..ba8bae593a9 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -64,7 +64,8 @@ clock limit is needed. `--unlimited` removes the step/tick limit. Source languag `celox run` accepts `--threads N` (1–64, default 1) and `--four-state` for both languages. Both languages support `--backend native|tiered|interpreter|cranelift|wasm` -(default: native). Tiered starts interpreted and adopts compiled code at a scheduler +(default: tiered; native when `--compile-only`, a native image, `--build-cache-dir` or an +IR dump is requested). Tiered starts interpreted and adopts compiled code at a scheduler safe point while preserving pending events. For example: ```sh