diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index c5e36c0a10e..ed9a71b7f0d 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -349,30 +349,30 @@ chapter-16/16.17--expect.sv 2state fail chapter-16/16.17--expect.sv 4state fail chapter-16/16.2--assert-final-uvm.sv 2state fail chapter-16/16.2--assert-final-uvm.sv 4state fail -chapter-16/16.2--assert-final.sv 2state fail -chapter-16/16.2--assert-final.sv 4state fail +chapter-16/16.2--assert-final.sv 2state pass +chapter-16/16.2--assert-final.sv 4state pass chapter-16/16.2--assert-uvm.sv 2state fail chapter-16/16.2--assert-uvm.sv 4state fail chapter-16/16.2--assert.sv 2state pass chapter-16/16.2--assert.sv 4state pass chapter-16/16.2--assert0-uvm.sv 2state fail chapter-16/16.2--assert0-uvm.sv 4state fail -chapter-16/16.2--assert0.sv 2state fail -chapter-16/16.2--assert0.sv 4state fail -chapter-16/16.2--assume-final.sv 2state fail -chapter-16/16.2--assume-final.sv 4state fail +chapter-16/16.2--assert0.sv 2state pass +chapter-16/16.2--assert0.sv 4state pass +chapter-16/16.2--assume-final.sv 2state pass +chapter-16/16.2--assume-final.sv 4state pass chapter-16/16.2--assume-uvm.sv 2state fail chapter-16/16.2--assume-uvm.sv 4state fail chapter-16/16.2--assume.sv 2state pass chapter-16/16.2--assume.sv 4state pass -chapter-16/16.2--assume0.sv 2state fail -chapter-16/16.2--assume0.sv 4state fail -chapter-16/16.2--cover-final.sv 2state fail -chapter-16/16.2--cover-final.sv 4state fail +chapter-16/16.2--assume0.sv 2state pass +chapter-16/16.2--assume0.sv 4state pass +chapter-16/16.2--cover-final.sv 2state pass +chapter-16/16.2--cover-final.sv 4state pass chapter-16/16.2--cover.sv 2state pass chapter-16/16.2--cover.sv 4state pass -chapter-16/16.2--cover0.sv 2state fail -chapter-16/16.2--cover0.sv 4state fail +chapter-16/16.2--cover0.sv 2state pass +chapter-16/16.2--cover0.sv 4state pass chapter-16/16.7--sequence-and-range-uvm.sv 2state fail chapter-16/16.7--sequence-and-range-uvm.sv 4state fail chapter-16/16.7--sequence-and-uvm.sv 2state fail diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index e96f8bbb7fb..f53a2af7176 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -4393,10 +4393,10 @@ fn build_comb_observer_capture_paths( | RuntimeEventKind::Finish | RuntimeEventKind::Stop ); - let fatal_error_code = sites[observer.site_id as usize] - .kind - .is_fatal() - .then_some(observer.site_id as i64); + // A deferred `$fatal` ends the simulation when it matures. + let fatal_error_code = (sites[observer.site_id as usize].kind.is_fatal() + && sites[observer.site_id as usize].deferred.is_none()) + .then_some(observer.site_id as i64); let pre_lower_nodes = observer_pre_lower_nodes(observer, arena); for idx in &order_after { comb_blocks[idx.0] @@ -4449,10 +4449,10 @@ fn build_comb_observer_capture_paths( | RuntimeEventKind::Finish | RuntimeEventKind::Stop ); - let member_fatal_error_code = sites[member.site_id as usize] - .kind - .is_fatal() - .then_some(member.site_id as i64); + // A deferred `$fatal` ends the simulation when it matures. + let member_fatal_error_code = (sites[member.site_id as usize].kind.is_fatal() + && sites[member.site_id as usize].deferred.is_none()) + .then_some(member.site_id as i64); let member_expr = match member .loop_runner .or(member.guard) diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index 6043ddcbc9a..40a2bdbbc5c 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -388,52 +388,201 @@ pub fn multi_store_only_candidates( /// [`multi_store_candidates`] with the written key of each instruction /// given by `key`, for callers that count only some kinds of writes. +/// +/// The blocks are condensed into strongly connected components once; each +/// component then knows the keys written in it or downstream of it, so a +/// write is a candidate if its key is written again later in its block, or +/// in a block reachable from it. Candidates come in the order of their +/// first such write, by block id and then position. pub fn multi_write_candidates( unit: &ExecutionUnit, key: impl Fn(&SIRInstruction) -> Option, ) -> Vec { - let writes = |block: &celox_sir::BasicBlock| -> Vec> { - block.instructions.iter().map(&key).collect() - }; - let block_writes: crate::HashMap>> = unit - .blocks - .iter() - .map(|(&id, block)| (id, writes(block))) - .collect(); let mut blocks: Vec<_> = unit.blocks.keys().copied().collect(); blocks.sort_unstable(); - let mut candidates: Vec = Vec::new(); - for &start in &blocks { - for (position, written) in block_writes[&start].iter().enumerate() { - let Some(written) = written else { - continue; - }; - if candidates.contains(written) { + let index: crate::HashMap = blocks + .iter() + .enumerate() + .map(|(position, &block)| (block, position)) + .collect(); + let mut key_ids: crate::HashMap = crate::HashMap::default(); + let mut keys: Vec = Vec::new(); + let mut write_counts: Vec = Vec::new(); + let writes: Vec> = blocks + .iter() + .map(|block| { + unit.blocks[block] + .instructions + .iter() + .filter_map(&key) + .map(|written| { + let id = *key_ids.entry(written).or_insert_with_key(|written| { + keys.push(written.clone()); + write_counts.push(0); + keys.len() - 1 + }); + write_counts[id] += 1; + id + }) + .collect() + }) + .collect(); + let edges: Vec> = blocks + .iter() + .map(|block| { + successors(&unit.blocks[block].terminator) + .into_iter() + .filter_map(|successor| index.get(&successor).copied()) + .collect() + }) + .collect(); + let (component_of, components) = strongly_connected_components(&edges); + let cyclic: Vec = components + .iter() + .map(|members| members.len() > 1 || edges[members[0]].contains(&members[0])) + .collect(); + + // A key written once is rewritten only around a loop; the others are + // looked up in per-component bit sets, a chunk of keys at a time so the + // sets stay small. + let tracked: Vec = (0..keys.len()).filter(|&id| write_counts[id] > 1).collect(); + let mut bit_of = vec![usize::MAX; keys.len()]; + for (bit, &id) in tracked.iter().enumerate() { + bit_of[id] = bit; + } + let mut reached: Vec> = writes + .iter() + .enumerate() + .map(|(block, written)| vec![cyclic[component_of[block]]; written.len()]) + .collect(); + const CHUNK_WORDS: usize = 64; + const CHUNK_BITS: usize = CHUNK_WORDS * 64; + for chunk_start in (0..tracked.len()).step_by(CHUNK_BITS) { + let in_chunk = |id: usize| { + let bit = bit_of[id]; + (bit != usize::MAX && bit >= chunk_start && bit < chunk_start + CHUNK_BITS) + .then(|| bit - chunk_start) + }; + // Components come sinks first, so each one's successors are done. + let mut downstream = vec![[0u64; CHUNK_WORDS]; components.len()]; + for (component, members) in components.iter().enumerate() { + let mut set = [0u64; CHUNK_WORDS]; + for &block in members { + for &id in &writes[block] { + if let Some(bit) = in_chunk(id) { + set[bit / 64] |= 1 << (bit % 64); + } + } + for &successor in &edges[block] { + let below = component_of[successor]; + if below != component { + for (word, other) in set.iter_mut().zip(&downstream[below]) { + *word |= other; + } + } + } + } + downstream[component] = set; + } + for (block, written) in writes.iter().enumerate() { + let component = component_of[block]; + if cyclic[component] { continue; } - let rewritten = |block: &celox_sir::BlockId, from: usize| { - block_writes[block][from..] - .iter() - .any(|other| other.as_ref() == Some(written)) - }; - let mut found = rewritten(&start, position + 1); - let mut seen = crate::HashSet::default(); - let mut work = successors(&unit.blocks[&start].terminator); - while !found && let Some(block) = work.pop() { - if !seen.insert(block) || !unit.blocks.contains_key(&block) { + for (position, &id) in written.iter().enumerate() { + let Some(bit) = in_chunk(id) else { continue; - } - found = rewritten(&block, 0); - work.extend(successors(&unit.blocks[&block].terminator)); + }; + reached[block][position] = edges[block].iter().any(|&successor| { + downstream[component_of[successor]][bit / 64] & (1 << (bit % 64)) != 0 + }); } - if found { - candidates.push(written.clone()); + } + } + + let mut is_candidate = vec![false; keys.len()]; + let mut candidates: Vec = Vec::new(); + let mut remaining: crate::HashMap = crate::HashMap::default(); + for (block, written) in writes.iter().enumerate() { + remaining.clear(); + for &id in written { + *remaining.entry(id).or_default() += 1; + } + for (position, &id) in written.iter().enumerate() { + let left = remaining.get_mut(&id).expect("counted above"); + *left -= 1; + if !is_candidate[id] && (*left > 0 || reached[block][position]) { + is_candidate[id] = true; + candidates.push(keys[id].clone()); } } } candidates } +/// Tarjan's strongly connected components of the graph whose node `n` has +/// the successors `edges[n]`: the component of every node, and the members +/// of every component, listed so that a component comes after all the +/// components reachable from it. +fn strongly_connected_components(edges: &[Vec]) -> (Vec, Vec>) { + const UNVISITED: usize = usize::MAX; + let count = edges.len(); + let mut order = vec![UNVISITED; count]; + let mut low = vec![0; count]; + let mut on_stack = vec![false; count]; + let mut component_of = vec![UNVISITED; count]; + let mut components: Vec> = Vec::new(); + let mut stack: Vec = Vec::new(); + let mut next_order = 0; + // Explicit call stack of (node, index of its next edge to follow). + let mut calls: Vec<(usize, usize)> = Vec::new(); + for root in 0..count { + if order[root] != UNVISITED { + continue; + } + calls.push((root, 0)); + order[root] = next_order; + low[root] = next_order; + next_order += 1; + stack.push(root); + on_stack[root] = true; + while let Some(&mut (node, ref mut next_edge)) = calls.last_mut() { + if let Some(&successor) = edges[node].get(*next_edge) { + *next_edge += 1; + if order[successor] == UNVISITED { + order[successor] = next_order; + low[successor] = next_order; + next_order += 1; + stack.push(successor); + on_stack[successor] = true; + calls.push((successor, 0)); + } else if on_stack[successor] { + low[node] = low[node].min(order[successor]); + } + continue; + } + calls.pop(); + if let Some(&(parent, _)) = calls.last() { + low[parent] = low[parent].min(low[node]); + } + if low[node] == order[node] { + let mut members = Vec::new(); + loop { + let member = stack.pop().expect("the root is on the stack"); + on_stack[member] = false; + component_of[member] = components.len(); + members.push(member); + if member == node { + break; + } + } + components.push(members); + } + } + } + (component_of, components) +} + /// Surround every store or commit in `unit` whose destination `watch_for` /// maps to a counted signal with the code that counts its occurrences. pub fn instrument_unit( @@ -1132,7 +1281,7 @@ pub fn declare_pending_slots( mod tests { use celox_sir::{SIRBuilder, SIRInstruction, SIROffset, SIRTerminator, SIRValue}; - use super::multi_store_candidates; + use super::{multi_store_candidates, multi_write_candidates, successors, write_destination}; /// Store a constant to `address` at the open block. fn store(b: &mut SIRBuilder, address: u32) { @@ -1222,4 +1371,189 @@ mod tests { store(&mut b, 4); assert!(candidates(&mut b).is_empty()); } + + /// The direct search [`multi_write_candidates`] replaced: a walk over + /// the reachable blocks from every write. + fn candidates_by_walk(unit: &celox_sir::ExecutionUnit) -> Vec { + let key = |instruction: &SIRInstruction| write_destination(instruction).copied(); + let mut blocks: Vec<_> = unit.blocks.keys().copied().collect(); + blocks.sort_unstable(); + let mut candidates: Vec = Vec::new(); + for &start in &blocks { + for (position, written) in unit.blocks[&start].instructions.iter().enumerate() { + let Some(written) = key(written) else { + continue; + }; + if candidates.contains(&written) { + continue; + } + let rewritten = |block: &celox_sir::BlockId, from: usize| { + unit.blocks[block].instructions[from..] + .iter() + .any(|other| key(other) == Some(written)) + }; + let mut found = rewritten(&start, position + 1); + let mut seen = crate::HashSet::default(); + let mut work = successors(&unit.blocks[&start].terminator); + while !found && let Some(block) = work.pop() { + if !seen.insert(block) || !unit.blocks.contains_key(&block) { + continue; + } + found = rewritten(&block, 0); + work.extend(successors(&unit.blocks[&block].terminator)); + } + if found { + candidates.push(written); + } + } + } + candidates + } + + /// A random unit: sparse block ids, forward and backward edges (loops), + /// edges to missing blocks, returns, and stores, commits and other + /// instructions over a few addresses. + fn random_unit(seed: u64) -> celox_sir::ExecutionUnit { + use celox_sir::{BasicBlock, BlockId, RegisterId, SIRSwitchCase}; + let state = std::cell::Cell::new(seed); + let next = |bound: u64| { + state.set( + state + .get() + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407), + ); + (state.get() >> 33) % bound + }; + let count = 1 + next(30) as usize; + let addresses = 1 + next(12) as u32; + let back_edges = next(4); + let id = |n: usize| BlockId(n * 3 + 1); + let mut blocks = crate::HashMap::default(); + for n in 0..count { + let mut instructions = Vec::new(); + for _ in 0..next(5) { + let address = next(addresses as u64) as u32; + instructions.push(match next(4) { + 0 => SIRInstruction::Imm(RegisterId(0), SIRValue::new(1u8)), + 1 => SIRInstruction::Commit( + address, + address, + SIROffset::Static(0), + 1, + Vec::new(), + ), + _ => SIRInstruction::Store( + address, + SIROffset::Static(0), + 1, + RegisterId(0), + Vec::new(), + Vec::new(), + ), + }); + } + let target = || { + let roll = next(10); + if roll == 0 { + BlockId(0) + } else if roll <= back_edges { + id(next(n as u64 + 1) as usize) + } else { + id((n + 1 + next(4) as usize).min(count)) + } + }; + let terminator = match next(5) { + 0 => SIRTerminator::Return, + 1 | 2 => SIRTerminator::Jump(target(), Vec::new()), + 3 => SIRTerminator::Branch { + cond: RegisterId(0), + true_block: (target(), Vec::new()), + false_block: (target(), Vec::new()), + }, + _ => SIRTerminator::Switch { + selector: RegisterId(0), + cases: (0..3u8) + .map(|value| SIRSwitchCase { + value: value.into(), + target: target(), + }) + .collect(), + default: target(), + }, + }; + blocks.insert( + id(n), + BasicBlock { + id: id(n), + params: Vec::new(), + instructions, + terminator, + }, + ); + } + celox_sir::ExecutionUnit { + entry_block_id: id(0), + blocks, + register_map: Default::default(), + } + } + + #[test] + fn candidates_match_a_walk_from_every_write() { + for seed in 0..5000 { + let unit = random_unit(seed); + let fast = multi_write_candidates(&unit, |instruction| { + write_destination(instruction).copied() + }); + assert_eq!(fast, candidates_by_walk(&unit), "seed {seed}:\n{unit}"); + } + } + + #[test] + fn candidates_beyond_one_chunk_of_keys_are_found() { + // Two blocks storing 10000 addresses each, the second only the + // even ones: more keys than one chunk of the bit sets holds. + use celox_sir::{BasicBlock, BlockId, RegisterId}; + let stores = |addresses: &mut dyn Iterator| { + addresses + .map(|address| { + SIRInstruction::Store( + address, + SIROffset::Static(0), + 1, + RegisterId(0), + Vec::new(), + Vec::new(), + ) + }) + .collect::>() + }; + let mut blocks = crate::HashMap::default(); + for (id, instructions, terminator) in [ + ( + 0, + stores(&mut (0..10000)), + SIRTerminator::Jump(BlockId(1), Vec::new()), + ), + (1, stores(&mut (0..10000).step_by(2)), SIRTerminator::Return), + ] { + blocks.insert( + BlockId(id), + BasicBlock { + id: BlockId(id), + params: Vec::new(), + instructions, + terminator, + }, + ); + } + let unit = celox_sir::ExecutionUnit { + entry_block_id: BlockId(0), + blocks, + register_map: Default::default(), + }; + let found = multi_store_candidates(&unit, |address| Some(*address)); + assert_eq!(found, (0..10000).step_by(2).collect::>()); + } } diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index a7e271a6439..c90490b61c3 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -4561,7 +4561,14 @@ pub(crate) fn attach_instance_glue( observer.activation_group += site_base; module.comb_observers.push(observer); } - module.runtime_event_sites.extend(comb_sites); + module + .runtime_event_sites + .extend(comb_sites.into_iter().map(|mut site| { + if let Some(celox_design::DeferredSite::Action { queue, .. }) = &mut site.deferred { + *queue += site_base; + } + site + })); for id in created { module .variables @@ -5276,6 +5283,12 @@ fn lower_comb_processes( .expect("a counter for every sensitivity atom") }) .collect(); + // A deferred action waits in the queue of its process. + if let Some(celox_design::DeferredSite::Action { queue, .. }) = + &mut comb.sites[(observer.site_id - base) as usize].deferred + { + *queue = base; + } observers.push(observer); } sites.append(&mut comb.sites); diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 9a4c532d84d..27fabd04104 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3581,6 +3581,15 @@ impl<'p, 'a> Comb<'p, 'a> { } self.effect_sensitivity.extend(observed.iter().copied()); let site_id = self.site_base + self.sites.len() as u32; + // The action of a deferred assertion waits in the queue of its + // process, which lowering names by the process's activation group + // (IEEE 1800-2023 16.4). A deferred `$fatal` ends the simulation + // when it matures, not while combinational logic settles. + let deferred = assertion_site + .map(|assertion| assertion.deferral) + .filter(|®ion| region != celox_design::AssertionDeferral::None) + .map(|region| celox_design::DeferredSite::Action { queue: 0, region }); + let fatal = kind.is_fatal() && deferred.is_none(); // Inside a run-time loop the event is emitted once per iteration by // the loop's runner (see `fold_loop`). let captured_in_loop = if let Some(effects) = &mut self.loop_effects { @@ -3592,7 +3601,7 @@ impl<'p, 'a> Comb<'p, 'a> { SystemTaskKind::Print(..) | SystemTaskKind::Control(_) ), args: captured.clone(), - fatal_error_code: kind.is_fatal().then_some(i64::from(site_id)), + fatal_error_code: fatal.then_some(i64::from(site_id)), }); true } else { @@ -3605,7 +3614,7 @@ impl<'p, 'a> Comb<'p, 'a> { scope: None, location: report_location(site), assertion: assertion_site.cloned(), - deferred: None, + deferred, arg_widths, arg_signed, arg_is_string, diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 3220791f75c..d399b4a9628 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -297,6 +297,27 @@ impl<'p, 'a> Ff<'p, 'a> { let Some(id) = self.m.id(lvalue.name()) else { return; }; + let variable = self.m.var(id); + let constant = match lvalue { + sv::ir::LValue::Ident(_) => None, + sv::ir::LValue::Select { msb, lsb, .. } => sv::typecheck::eval_const_expr_with_types( + msb, + self.m.constants, + self.m.parameter_types, + ) + .zip(sv::typecheck::eval_const_expr_with_types( + lsb, + self.m.constants, + self.m.parameter_types, + )) + .and_then(|(msb, lsb)| constant_select_write(variable, msb, lsb)), + }; + // An empty constant write is not a dynamic write of the whole + // variable. Keep it out of publication and latch-coverage targets. + if matches!(constant, Some((None, _))) { + return; + } + let constant = constant.and_then(|(access, _)| access); if blocking { self.working.insert(id); } else { @@ -305,7 +326,6 @@ impl<'p, 'a> Ff<'p, 'a> { if self.m.is_hidden(id) { return; } - let variable = self.m.var(id); // A run-time bit select within one array element writes only that // element (see `write`); a run-time element may be any of them. let element_write = dynamic_array_element_lvalue( @@ -329,20 +349,6 @@ impl<'p, 'a> Ff<'p, 'a> { .flatten() .and_then(|write| write.window) .unwrap_or(BitAccess::new(0, variable.width - 1)); - let constant = match lvalue { - sv::ir::LValue::Ident(_) => None, - sv::ir::LValue::Select { msb, lsb, .. } => sv::typecheck::eval_const_expr_with_types( - msb, - self.m.constants, - self.m.parameter_types, - ) - .zip(sv::typecheck::eval_const_expr_with_types( - lsb, - self.m.constants, - self.m.parameter_types, - )) - .and_then(|(msb, lsb)| constant_select_write(variable, msb, lsb)?.0), - }; if constant.is_none() { // `write` takes the same order: a constant range, then one // run-time element, then a read-modify-write of the variable. @@ -3970,6 +3976,7 @@ impl<'p, 'a> Ff<'p, 'a> { let width = self.m.var(id).width; self.targets.push((id, BitAccess::new(0, width - 1))); } + let flush_site = self.deferred_flush_site(body); if self.exec_block(body)? { self.b.seal_block(SIRTerminator::Return); } @@ -4131,6 +4138,13 @@ impl<'p, 'a> Ff<'p, 'a> { false_block: (done, vec![]), }); self.b.switch_to_block(execute); + // Each run is a resume of the process (IEEE 1800-2023 16.4.2). + if let Some(site_id) = flush_site { + self.b.emit(SIRInstruction::RuntimeEvent { + site_id, + args: Vec::new(), + }); + } self.b.inline_execution_unit(&body_unit); if !always_comb { // @* is not waiting during its body. Its own writes cannot wake diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index 19ffd8e1567..94ba20cf12e 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -137,6 +137,12 @@ pub trait SimBackend { None } fn set_comb_capture_event_enabled(&mut self, _active_sites: &[bool]) {} + /// Which runtime event sites are enabled for combinational capture, by + /// the host before an evaluation or by the evaluation for observers + /// whose inputs it changed. Empty for a backend without capture. + fn comb_capture_event_enabled(&self) -> Vec { + Vec::new() + } fn stable_region_size(&self) -> usize; fn layout(&self) -> &MemoryLayout; /// The heap that handle slots in this backend's state refer to. diff --git a/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs b/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs index d01cd58a92e..b149afc12cd 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs @@ -8,17 +8,9 @@ impl BodyBuilder<'_, '_, '_> { keyword: &str, header: &AssertionHeader, ) -> Result { - let AssertionHeader::Immediate { - condition, - deferred, - .. - } = header - else { + let AssertionHeader::Immediate { condition, .. } = header else { return Err(unsupported("concurrent assertion")); }; - if keyword == "cover" && deferred.is_some() { - return Err(unsupported("deferred immediate cover")); - } if !matches!(keyword, "assert" | "assume" | "cover") { return Err(unsupported("immediate assertion keyword")); } diff --git a/crates/celox-sv-analyzer/src/ast/selects.rs b/crates/celox-sv-analyzer/src/ast/selects.rs index c0c475936f4..7126968f141 100644 --- a/crates/celox-sv-analyzer/src/ast/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/selects.rs @@ -88,7 +88,7 @@ pub(super) fn lvalue_from_indices( packed_dimensions: &PackedDimensions, ) -> Converted { if let Some((array_offset, packed_indices)) = - flatten_variable_select(state, &name, &indices, packed_dimensions) + flatten_variable_select(&name, &indices, packed_dimensions) { if !packed_indices.is_empty() { if let Some((msb, lsb)) = @@ -186,6 +186,43 @@ pub(super) fn lvalue_from_indices( Ok(LValue::Ident(name)) } +/// Fold the invalid-element sentinel emitted by `flatten_variable_select`. +/// Keep the selected integral type even in an unselected conditional arm: +/// both operands determine the conditional width and signedness (11.4.11). +pub(super) fn invalid_unpacked_read( + state: &AnalysisState, + lhs: &LValue, + dimensions: &PackedDimensions, +) -> Option { + let LValue::Select { + name, + msb, + lsb, + signed, + .. + } = lhs + else { + return None; + }; + let variable = dimensions.get(name)?; + if variable.unpacked.is_empty() || variable.real || variable.string || variable.class.is_some() + { + return None; + } + let full_width = lvalue_expr_type(state, &LValue::Ident(name.clone()), dimensions)?.width; + let msb = eval_ast_const_expr(state, msb, &dimensions.const_env)?; + let lsb = eval_ast_const_expr(state, lsb, &dimensions.const_env)?; + if msb < lsb || lsb < i128::try_from(full_width).ok()? { + return None; + } + let width = usize::try_from(msb.checked_sub(lsb)?) + .ok()? + .checked_add(1)?; + let signing = if *signed { "s" } else { "" }; + let digit = if variable.is_2state { "0" } else { "x" }; + Some(Expr::Literal(format!("{width}'{signing}b{digit}"))) +} + /// Shared syntax-independent assignment range flattening and array metadata. pub(super) fn lvalue_from_range( state: &AnalysisState, @@ -348,7 +385,6 @@ pub(super) fn indexed_range_values( } fn flatten_variable_select( - state: &AnalysisState, name: &str, indices: &[ConstExpr], packed_dimensions: &PackedDimensions, @@ -360,15 +396,9 @@ fn flatten_variable_select( let mut offset = ConstExpr::Literal("0".to_string()); let mut valid = None; for (index, value) in indices[..selected_unpacked_count].iter().enumerate() { - if const_expr_is_out_of_range( - state, - value, - &dimensions.unpacked[index].left, - &dimensions.unpacked[index].right, - &packed_dimensions.const_env, - ) { - return None; - } + // Constant and runtime invalid indices have the same semantics: + // read the element type's default value and ignore writes (7.4.5). + // Route both through the guard below instead of rejecting constants. let dimension = &dimensions.unpacked[index]; let descending = ConstExpr::Binary { left: Box::new(dimension.left.clone()), @@ -483,7 +513,7 @@ fn unpacked_select_range_metadata( ) { return None; } - let (_, packed_indices) = flatten_variable_select(state, name, indices, packed_dimensions)?; + let (_, packed_indices) = flatten_variable_select(name, indices, packed_dimensions)?; if !packed_indices.is_empty() { return None; } @@ -554,8 +584,7 @@ fn flatten_unpacked_select_range( ) { return None; } - let (array_offset, packed_indices) = - flatten_variable_select(state, name, indices, packed_dimensions)?; + let (array_offset, packed_indices) = flatten_variable_select(name, indices, packed_dimensions)?; if !packed_indices.is_empty() { return None; } @@ -642,8 +671,7 @@ fn flatten_select_range( packed_dimensions, ); } - let (array_offset, packed_indices) = - flatten_variable_select(state, name, indices, packed_dimensions)?; + let (array_offset, packed_indices) = flatten_variable_select(name, indices, packed_dimensions)?; let dimension = dimensions.packed.get(packed_indices.len())?; if const_expr_is_out_of_range( state, diff --git a/crates/celox-sv-analyzer/src/ast/statements.rs b/crates/celox-sv-analyzer/src/ast/statements.rs index 9ff4406572a..f256a9694e1 100644 --- a/crates/celox-sv-analyzer/src/ast/statements.rs +++ b/crates/celox-sv-analyzer/src/ast/statements.rs @@ -163,6 +163,9 @@ pub(super) fn expr_from_lvalue( lhs: &LValue, packed_dimensions: &PackedDimensions, ) -> Expr { + if let Some(value) = selects::invalid_unpacked_read(state, lhs, packed_dimensions) { + return value; + } let (base, array_slice_width, array_slice_reversed, signed) = match lhs { LValue::Ident(name) => return Expr::Ident(name.clone()), LValue::Select { diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/immediate_assertions.rs b/crates/celox-sv-analyzer/src/source_tree/tests/immediate_assertions.rs index f7af1518363..8475ff2012a 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/immediate_assertions.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/immediate_assertions.rs @@ -199,7 +199,7 @@ fn native_assertion_action_scopes_and_unsupported_classes_keep_existing_behavior }; assert_ne!(pass, fail); for (statement, diagnostic) in [ - ("cover #0(a);", "deferred immediate cover"), + ("cover #0(a) y=1;", "deferred assertion action"), ("assert property(a);", "concurrent assertion"), ] { let tree = parsed(statement); diff --git a/crates/celox-sv-analyzer/src/syntax.rs b/crates/celox-sv-analyzer/src/syntax.rs index c3607469349..9fde61ea7ba 100644 --- a/crates/celox-sv-analyzer/src/syntax.rs +++ b/crates/celox-sv-analyzer/src/syntax.rs @@ -172,17 +172,19 @@ mod tests { } #[test] - fn module_deferred_assertions_parse_but_require_execution_support() { + /// A deferred assertion as a module item is the same assertion in an + /// `always_comb` (IEEE 1800-2023 16.4.3), labeled or not. + fn module_deferred_assertions_are_always_comb_processes() { for keyword in ["assert", "assume", "cover"] { for deferral in ["#0", "final"] { - let code = format!("module M; logic a=1; {keyword} {deferral} (a!=0); endmodule"); - let path = Path::new("module-deferred.sv"); - parse_source(&code, path).unwrap(); - let error = crate::analyze_source(&code, path).unwrap_err(); - assert!( - matches!(error, AnalyzerError::Unsupported(ref reason) if reason == "module deferred immediate assertion"), - "{error}" - ); + for label in ["", "a1: "] { + let code = format!( + "module M; logic a=1; {label}{keyword} {deferral} (a!=0); endmodule" + ); + let path = Path::new("module-deferred.sv"); + parse_source(&code, path).unwrap(); + crate::analyze_source(&code, path).unwrap(); + } } } } diff --git a/crates/celox-sv-syntax/src/parser/declarations.rs b/crates/celox-sv-syntax/src/parser/declarations.rs index 607f5e0fc67..e04eddb87d0 100644 --- a/crates/celox-sv-syntax/src/parser/declarations.rs +++ b/crates/celox-sv-syntax/src/parser/declarations.rs @@ -782,16 +782,36 @@ impl Parser<'_> { frames.push(frame); continue; } + // A deferred immediate assertion as a module item is the same + // assertion in an `always_comb` (IEEE 1800-2023 16.4.3). + let deferred_assertion = |at: usize| { + matches!(self.nth(at), "assert" | "assume" | "cover") + && matches!(self.nth(at + 1), "#" | "final") + }; + // A module item, also in a generate region or block. + let static_deferred = frame.item_start + && frame.delimiters.is_empty() + && frame + .scopes + .iter() + .all(|scope| matches!(*scope, "endgenerate" | "end" | "endcase")) + && (deferred_assertion(0) || self.nth(1) == ":" && deferred_assertion(2)); if frame.item_start && frame.delimiters.is_empty() && !frame .scopes .iter() .any(|scope| matches!(*scope, "endproperty" | "endsequence")) - && matches!( - self.peek(), - "initial" | "always" | "always_comb" | "always_latch" | "always_ff" | "final" - ) + && (static_deferred + || matches!( + self.peek(), + "initial" + | "always" + | "always_comb" + | "always_latch" + | "always_ff" + | "final" + )) { let parameters = self.parameter_declarations.len(); let aliases = self.type_aliases.len(); @@ -799,7 +819,11 @@ impl Parser<'_> { let times = self.time_declarations.len(); let assigns = self.assign_statements.len(); let start = self.at; - let id = self.procedure()?; + let id = if static_deferred { + self.static_deferred_assertion()? + } else { + self.procedure()? + }; frame.unit.procedures.push(id); frame.record(self, start, BodyItemKind::Procedure(id))?; frame.unit.parameter_declarations.extend( diff --git a/crates/celox-sv-syntax/src/parser/procedures.rs b/crates/celox-sv-syntax/src/parser/procedures.rs index 7d872398e62..bd513df2ce0 100644 --- a/crates/celox-sv-syntax/src/parser/procedures.rs +++ b/crates/celox-sv-syntax/src/parser/procedures.rs @@ -137,6 +137,22 @@ impl Parser<'_> { Ok(id) } + /// A deferred immediate assertion as a module item: an `always_comb` + /// procedure whose body is the assertion (IEEE 1800-2023 16.4.3). + pub(super) fn static_deferred_assertion(&mut self) -> Result { + let start = self.at; + let body = self.statement_machine()?; + let id = ProcedureId(self.procedures.len()); + let authored_statements = self.body_membership(&[body]); + self.procedures.push(Procedure { + kind: ProcedureKind::AlwaysComb, + body, + authored_statements, + tokens: self.range(start), + }); + Ok(id) + } + /// Capture syntax ownership before execution graph transformations. This /// flat membership also keeps deeply nested scopes independent of Rust's /// call stack; opaque statement children remain their own captured scope. diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index c047f060e8c..f0cc4becf0d 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -2799,14 +2799,20 @@ fn specparam_retains_its_body_item_boundary() { } #[test] -fn module_deferred_assertions_do_not_become_final_procedures() { +/// A deferred assertion as a module item is an `always_comb` procedure +/// (IEEE 1800-2023 16.4.3), never a `final` one. +fn module_deferred_assertions_become_always_comb_procedures() { for keyword in ["assert", "assume", "cover"] { for deferral in ["#0", "final"] { let native = parse(&format!("module M; {keyword} {deferral} (1); endmodule")); - assert!(native.procedures.is_empty()); - assert!( - matches!(&native.body_item(native.units[0].items[0]).kind, BodyItemKind::Unconverted { category, .. } if category == keyword) - ); + let [procedure] = &native.procedures[..] else { + panic!("{:?}", native.procedures) + }; + assert_eq!(procedure.kind, ProcedureKind::AlwaysComb); + assert!(matches!( + &native.statement(procedure.body).kind, + StatementKind::Assertion { keyword: k, .. } if k == keyword + )); } } } diff --git a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest index 36ba67285b4..65c69699a08 100644 --- a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest +++ b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest @@ -1959,6 +1959,177 @@ (run_until 1) (assert_eq s0 0) (assert_eq s1 0x42) (assert_eq s2 0)) +(case generated_pipeline_with_unselected_invalid_array_element + ; IEEE 1800-2023 7.4.5 and 11.4.11: an invalid element in the unused + ; conditional arm must not prevent elaboration or change the result type. + (source "generated_pipeline.sv" #" + module Asc #(parameter N=0)(input logic clk, rst, input logic [7:0] d, + output logic [7:0] q); + if (N>0) begin : pipe + logic [7:0] r[3:N+2]; + for(genvar n=0;n cycle 1) (* (- cycle 1) 17) 0)) + (assert_eq b2 (? (> cycle 1) (* (- cycle 1) 17) 0)) + (assert_eq a4 (? (> cycle 3) (* (- cycle 3) 17) 0)) + (assert_eq b4 (? (> cycle 3) (* (- cycle 3) 17) 0)))) + +(case constant_invalid_unpacked_indices_read_defaults_and_ignore_writes + ; IEEE 1800-2023 7.4.5, Table 7-1. Invalid inner indices must never + ; wrap into a neighboring element, in either declaration direction. + (four_state) + (source "constant_invalid_array_indices.sv" #" + module Top(input logic clk, input logic [7:0] d, + output logic [7:0] above, below, inner, row, + output logic [7:0] written, written_ff, + output logic [128:0] wide); + logic [7:0] a[3:4]; + logic [7:0] b[4:3]; + logic [7:0] matrix[0:1][0:2]; + logic [7:0] w[3:4], f[3:4]; + logic [128:0] wide_array[2]; + assign wide=wide_array[2]; + always_comb begin + a[3]=d; a[4]=~d; + b[3]=d; b[4]=~d; + for (int i=0;i<2;i++) for (int j=0;j<3;j++) matrix[i][j]=d; + w[3]=d; w[4]=~d; + w[2]=8'hff; w[5]=8'hff; + end + always_ff @(posedge clk) begin + f[3]<=d; f[4]<=~d; + f[2]<=8'hff; f[5]<=8'hff; + end + assign below=a[2]; + assign above=b[5]; + assign inner=matrix[0][3]; + assign row=matrix[2][0]; + assign written=w[3]^w[4]; + assign written_ff=f[3]^f[4]; + endmodule + "#) + (top Top) + (for value (list 0x12 0xa5 0xff) + (modify (set d value)) + (assert_eq below (fourstate 255 255)) + (assert_eq above (fourstate 255 255)) + (assert_eq inner (fourstate 255 255)) + (assert_eq row (fourstate 255 255)) + (let wide_mask (- (<< 1 129) 1)) + (assert_eq wide (fourstate wide_mask wide_mask)) + (assert_eq written 255) + (tick clk) + (assert_eq written_ff 255))) + +(case generated_pipeline_with_unselected_invalid_array_element_four_state + ; IEEE 1800-2023 7.4.5 and 11.4.11: an invalid element in the unused + ; conditional arm must not prevent elaboration or change the result type. + (four_state) + (source "generated_pipeline.sv" #" + module Asc #(parameter N=0)(input logic clk, rst, input logic [7:0] d, + output logic [7:0] q); + if (N>0) begin : pipe + logic [7:0] r[3:N+2]; + for(genvar n=0;n cycle 1) (* (- cycle 1) 17) 0)) + (assert_eq b2 (? (> cycle 1) (* (- cycle 1) 17) 0)) + (assert_eq a4 (? (> cycle 3) (* (- cycle 3) 17) 0)) + (assert_eq b4 (? (> cycle 3) (* (- cycle 3) 17) 0)))) + +(case invalid_unpacked_elements_preserve_type_in_conditionals + ; Both conditional operands contribute width and signedness even when + ; a constant condition selects the other operand (11.4.11, 11.8.2). + (four_state) + (source "invalid_array_element_types.sv" #" + module Top(output logic [15:0] mixed_sign, both_signed, + output logic [31:0] width); + logic [15:0] u[1]; + logic signed [15:0] s[1]; + assign mixed_sign=1'b1 ? 8'sh80 : u[-1]; + assign both_signed=1'b1 ? 8'sh80 : s[-1]; + assign width=$bits(1'b1 ? 8'sh80 : u[-1]); + endmodule + "#) + (top Top) + (assert_eq mixed_sign 0x0080) + (assert_eq both_signed 0xff80) + (assert_eq width 16)) + (case generated_pipeline_with_explicit_generate_branches ; Separate FF producers may share one array. Removing a task's staging ; must preserve publication of elements computed by other tasks (10.4.2). diff --git a/crates/celox/src/backend/interp.rs b/crates/celox/src/backend/interp.rs index 1101a082e15..d3651da5bc6 100644 --- a/crates/celox/src/backend/interp.rs +++ b/crates/celox/src/backend/interp.rs @@ -1965,6 +1965,13 @@ impl SimBackend for InterpBackend { } } + fn comb_capture_event_enabled(&self) -> Vec { + self.comb_capture_enabled + .iter() + .map(|&enabled| enabled != 0) + .collect() + } + fn stable_region_size(&self) -> usize { self.layout.total_size } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index b452f9474b6..269dbefb940 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -3467,6 +3467,13 @@ impl super::super::SimBackend for NativeBackend { } } + fn comb_capture_event_enabled(&self) -> Vec { + self.comb_capture_enabled + .iter() + .map(|&enabled| enabled != 0) + .collect() + } + fn stable_region_size(&self) -> usize { self.compiled.layout.total_size } diff --git a/crates/celox/src/backend/runtime.rs b/crates/celox/src/backend/runtime.rs index e8f5ba4a1db..87b312090ad 100644 --- a/crates/celox/src/backend/runtime.rs +++ b/crates/celox/src/backend/runtime.rs @@ -1422,6 +1422,13 @@ impl super::SimBackend for JitBackend { self.set_comb_capture_event_enabled(active_sites); } + fn comb_capture_event_enabled(&self) -> Vec { + self.comb_capture_enabled + .iter() + .map(|&enabled| enabled != 0) + .collect() + } + fn stable_region_size(&self) -> usize { self.stable_region_size() } diff --git a/crates/celox/src/backend/tiered.rs b/crates/celox/src/backend/tiered.rs index bff1dcf143e..ef541fac47e 100644 --- a/crates/celox/src/backend/tiered.rs +++ b/crates/celox/src/backend/tiered.rs @@ -1690,6 +1690,20 @@ impl SimBackend for TieredBackend { } } + fn comb_capture_event_enabled(&self) -> Vec { + match &self.phase { + Phase::Interpreting(Some(interp)) => interp.comb_capture_event_enabled(), + Phase::Compiled(CompiledTier::Jit(jit)) => jit.comb_capture_event_enabled(), + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + Phase::Compiled(CompiledTier::Native(native)) => native.comb_capture_event_enabled(), + Phase::Interpreting(None) => unreachable!("promoted backend left no interpreter"), + } + } + fn stable_region_size(&self) -> usize { match &self.phase { Phase::Interpreting(Some(interp)) => interp.stable_region_size(), diff --git a/crates/celox/src/backend/wasm_runtime.rs b/crates/celox/src/backend/wasm_runtime.rs index 4dceda752f0..26e5c70b1a2 100644 --- a/crates/celox/src/backend/wasm_runtime.rs +++ b/crates/celox/src/backend/wasm_runtime.rs @@ -121,6 +121,9 @@ impl super::traits::SimBackend for WasmBackend { fn set_comb_capture_event_enabled(&mut self, active_sites: &[bool]) { WasmBackend::set_comb_capture_event_enabled(self, active_sites) } + fn comb_capture_event_enabled(&self) -> Vec { + WasmBackend::comb_capture_event_enabled(self) + } fn stable_region_size(&self) -> usize { WasmBackend::stable_region_size(self) } @@ -705,6 +708,16 @@ impl WasmBackend { } } + pub fn comb_capture_event_enabled(&self) -> Vec { + let enabled_base = self.layout.merged_total_size + self.layout.runtime_event_buffer_size; + let enabled_len = self.layout.runtime_event_site_layouts.len(); + let mem = self.memory.data(&self.store); + mem[enabled_base..enabled_base + enabled_len] + .iter() + .map(|&enabled| enabled != 0) + .collect() + } + pub fn stable_region_size(&self) -> usize { self.layout.total_size } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 59740d44036..9ff42deb8cc 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -433,6 +433,7 @@ impl Simulation { // Only a timed simulation ends at an RTL `$finish`; a bare // `Simulator`, ticks included, leaves that to the host. simulator.finish_sites = simulator.schedule.finish_sites; + simulator.timed = true; simulator.skip_runtime_finish(); state.initialize_declarations(&mut simulator)?; Ok(Self { @@ -683,9 +684,44 @@ impl Simulation { if self.reports.fail_on.is_some() { return self.watched_step(); } + // With nothing scheduled, the step ends the slot too. + self.end_idle_slot(self.state.next_event_time().unwrap_or(u64::MAX))?; self.step_until(u64::MAX) } + /// A slot with nothing due is over when a run leaves its time. In a + /// design with deferred assertions, logic that host writes or the + /// initial settle left dirty settles there, and the actions waiting from + /// any settle at that time mature, so that a deferred `$fatal` ends the + /// run at that time. + #[inline] + fn end_idle_slot(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { + if !self.simulator.deferred_assertions + || end_time <= self.state.time() + || self.state.next_event_time() == Some(self.state.time()) + { + return Ok(()); + } + self.settle_idle_slot() + } + + #[cold] + #[inline(never)] + fn settle_idle_slot(&mut self) -> Result<(), RuntimeErrorCode> { + let result = if self.simulator.dirty { + let result = self.simulator.eval_comb_checked(); + self.simulator.dirty = false; + result + } else { + Ok(()) + }; + if let Err(error) = result.and_then(|()| self.simulator.mature_deferred_assertions()) { + self.flush_error_output(); + return Err(error); + } + Ok(()) + } + /// [`Self::step`] while [`Self::set_fail_on`] is set: a slot that only /// settles host writes is watched before the step goes on to the next /// time. @@ -765,15 +801,31 @@ impl Simulation { /// that wake no process, at the current time, and watch its reports. A /// watched run does this before it moves to a later time. fn watch_settle(&mut self) -> Result<(), RuntimeErrorCode> { - if !self.simulator.dirty { + // The run leaves the time or ends at it: the slot is over, and the + // deferred actions waiting from any settle at that time mature + // before the reports are watched. + let mature = self.simulator.deferred_assertions + && self.state.next_event_time() != Some(self.state.time()); + if !self.simulator.dirty && !mature { return Ok(()); } - if let Err(error) = self.simulator.eval_comb_checked() { + if self.simulator.dirty { + if let Err(error) = self.simulator.eval_comb_checked() { + self.flush_error_output(); + return Err(error); + } + self.simulator.dirty = false; + } + let matured = if mature { + self.simulator.mature_deferred_assertions() + } else { + Ok(()) + }; + self.watch_reports(); + if let Err(error) = matured { self.flush_error_output(); return Err(error); } - self.simulator.dirty = false; - self.watch_reports(); Ok(()) } @@ -831,8 +883,12 @@ impl Simulation { self.reports.failure = None; // With reports to watch, step one slot at a time; the run below // then only advances the time. - if self.reports.fail_on.is_some() && !self.watched_steps(end_time, u64::MAX)? { - return Ok(()); + if self.reports.fail_on.is_some() { + if !self.watched_steps(end_time, u64::MAX)? { + return Ok(()); + } + } else { + self.end_idle_slot(end_time)?; } let reached = match self.shadow.take() { None => self.state.run_until(&mut self.simulator, end_time)?, @@ -871,6 +927,15 @@ impl Simulation { if self.time() != last || self.is_finished() || self.is_stopped() { return Ok(()); } + // Leaving `last` ends its slot. + if self.reports.fail_on.is_some() { + self.watch_settle()?; + if self.reports.failure.is_some() { + return Ok(()); + } + } else { + self.end_idle_slot(time)?; + } self.state.advance_time(&mut self.simulator.backend, time); if let Some(shadow) = &mut self.shadow { shadow @@ -900,6 +965,7 @@ impl Simulation { self.run_until(end_time)?; return Ok(!self.state.is_stopped()); } + self.end_idle_slot(end_time)?; let mut steps = 0; while let Some(next_time) = self.state.next_event_time() { if next_time > end_time { @@ -948,6 +1014,16 @@ impl Simulation { /// Takes the runtime events (`$display`, messages, `$finish`, ...) the /// design emitted since the last call, in emission order. pub fn drain_runtime_events(&mut self) -> Vec { + // A slot with nothing more due is over, also before the first step: + // the initial settle of combinational logic belongs to time zero. + // A fatal action is drained as a fatal report. + if self.simulator.deferred_assertions + && self.state.next_event_time() != Some(self.state.time()) + { + // Lazily settled logic runs in the slot too. + self.simulator.settle_for_runtime_event_drain(); + let _ = self.simulator.mature_deferred_assertions(); + } let mut events = std::mem::take(&mut self.reports.events); events.extend(self.simulator.drain_runtime_events()); events diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index d70605ce91b..abae66ea6c2 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -153,6 +153,13 @@ mod host { /// The design has deferred assertions, whose actions mature at the /// end of each time slot. pub(crate) deferred_assertions: bool, + /// The activation groups of combinational processes with deferred + /// assertions, with a site of each: running the process again + /// flushes its queue (IEEE 1800-2023 16.4.2). + comb_deferred_groups: Vec<(u32, usize)>, + /// A timed simulation owns this simulator: a time slot ends when its + /// scheduler says so, not when combinational logic settles. + pub(crate) timed: bool, /// Identity of the state layout, computed on first checkpoint use. pub(super) checkpoint_fingerprint: std::sync::OnceLock, /// State objects as state files name them, built on first use. @@ -430,9 +437,7 @@ mod host { { let site = *site_id as u32; match *deferred { - celox_design::DeferredSite::FlushPoint => { - self.deferred.waiting.retain(|&(queue, ..)| queue != site); - } + celox_design::DeferredSite::FlushPoint => self.flush(site), celox_design::DeferredSite::Action { queue, region } => { self.deferred.waiting.push((queue, region, event)); } @@ -452,6 +457,13 @@ mod host { self.push_ready(event, capacity); } + /// Discard the actions waiting in queue `queue`. + fn flush(&mut self, queue: u32) { + self.deferred + .waiting + .retain(|&(waiting, ..)| waiting != queue); + } + /// The time slot ends: queue the waiting actions, those of the /// Observed region (`#0`) before those of the Postponed region /// (`final`), up to the first fatal one, which it returns, or @@ -1017,6 +1029,19 @@ mod host { } else { Vec::new() }; + let mut comb_deferred_groups: Vec<(u32, usize)> = Vec::new(); + for observer in &program.runtime_schema.comb_observers { + if matches!( + sites[observer.site_id as usize].deferred, + Some(celox_design::DeferredSite::Action { .. }) + ) && !comb_deferred_groups + .iter() + .any(|&(group, _)| group == observer.activation_group) + { + comb_deferred_groups + .push((observer.activation_group, observer.site_id as usize)); + } + } let mut sim = Self { backend, program, @@ -1037,6 +1062,8 @@ mod host { ..Default::default() })), deferred_assertions: !deferred_sites.is_empty(), + comb_deferred_groups, + timed: false, components: Default::default(), component_simulation: None, runtime_event_read_seq: Arc::new(AtomicU64::new(0)), @@ -1263,10 +1290,26 @@ mod host { !self.runtime_event_drain_active.load(Ordering::Acquire), "cannot use Simulator::drain_runtime_events while a RuntimeEventDrain is active", ); + self.settle_for_runtime_event_drain(); + // A fatal action is drained as a fatal report. + let _ = self.end_untimed_slot(); + self.collect_formatted_runtime_events(ctx) + } + + /// Settle dirty combinational logic before its events are drained. + pub(crate) fn settle_for_runtime_event_drain(&mut self) { if self.dirty { self.eval_comb_for_runtime_event_drain().unwrap(); } - self.collect_formatted_runtime_events(ctx) + } + + /// Without a scheduler, a host call is a time slot: mature the + /// deferred assertions it ran. + fn end_untimed_slot(&mut self) -> Result<(), RuntimeErrorCode> { + if self.timed { + return Ok(()); + } + self.mature_deferred_assertions() } pub(crate) fn drain_runtime_events_deferred_with_context( @@ -1735,6 +1778,7 @@ mod host { self.dirty = true; if self.runtime_event_drain_active.load(Ordering::Acquire) { self.eval_comb_for_runtime_event_drain()?; + self.end_untimed_slot()?; } Ok(()) } @@ -1742,6 +1786,8 @@ mod host { pub(super) fn settle_dirty_for_runtime_event_drain(&mut self) { if self.runtime_event_drain_active.load(Ordering::Acquire) { self.eval_comb_for_runtime_event_drain().unwrap(); + // A fatal action is drained as a fatal report. + let _ = self.end_untimed_slot(); } } @@ -1798,8 +1844,14 @@ mod host { &self.comb_observer_snapshots, self.comb_observer_initial_eval, ); + if !self.comb_deferred_groups.is_empty() { + self.flush_comb_deferred(&active_sites); + } self.backend.set_comb_capture_event_enabled(&active_sites); let eval_result = self.backend.eval_comb(); + if !self.comb_deferred_groups.is_empty() { + self.flush_comb_rerun_deferred(&active_sites); + } self.comb_observer_reads .snapshot(&self.backend, &mut snapshots); let runtime_events = self.peek_backend_runtime_events_from(runtime_event_start_seq); @@ -1816,6 +1868,34 @@ mod host { (eval_result, runtime_events) } + /// The combinational processes that run again flush the actions of + /// their deferred assertions, after the events issued before. + #[cold] + fn flush_comb_deferred(&mut self, active_sites: &[bool]) { + self.stash_runtime_events(); + let mut pending = self.pending_host_events.lock().unwrap(); + for &(group, site) in &self.comb_deferred_groups { + if active_sites[site] { + pending.flush(group); + } + } + } + + /// A combinational process that runs again because the evaluation + /// changed its inputs, which the backend enables it for, flushes the + /// actions waiting from before the evaluation. Its new actions are + /// still in the backend's buffer. + #[cold] + fn flush_comb_rerun_deferred(&mut self, active_sites: &[bool]) { + let enabled = self.backend.comb_capture_event_enabled(); + let mut pending = self.pending_host_events.lock().unwrap(); + for &(group, site) in &self.comb_deferred_groups { + if !active_sites[site] && enabled.get(site).copied().unwrap_or(false) { + pending.flush(group); + } + } + } + pub(super) fn snapshot_all_comb_observers( &self, ) -> Vec { @@ -1832,7 +1912,8 @@ mod host { .runtime_schema .runtime_event_sites .get(*site_id)?; - if !site.kind.is_fatal() { + // A deferred `$fatal` ends the simulation when it matures. + if !site.kind.is_fatal() || site.deferred.is_some() { return None; } Some(RuntimeErrorCode::Runtime { @@ -2586,7 +2667,7 @@ mod host { pub fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { self.eval_comb_checked()?; self.dirty = false; - Ok(()) + self.end_untimed_slot() } /// Returns a raw pointer to the backend memory and its total size in bytes. diff --git a/crates/celox/tests/diagnostic_policy.rs b/crates/celox/tests/diagnostic_policy.rs index 49eb9853ce8..ffbc6bc5658 100644 --- a/crates/celox/tests/diagnostic_policy.rs +++ b/crates/celox/tests/diagnostic_policy.rs @@ -604,14 +604,15 @@ mod inferred_latch { #[test] fn out_of_bounds_state_writes_do_not_expand_diagnostic_masks() { let source = "module Top(output logic [7:0] q); logic [7:0] a[2]; always_comb begin q=$time; a[-1]=$time; a[2147483647]=$time; end endmodule"; - let error = Simulator::from_sv_sources(vec![(source, Path::new("oob_state.sv"))], "Top") - .diagnostic_policy(policy("inferred_latch", DiagnosticLevel::Warn)) - .build_interpreter() - .unwrap_err(); - assert!( - error.to_string().contains("outside its declared range"), - "{error}" - ); + // Invalid unpacked writes are ignored (IEEE 1800-2023 7.4.5). + // Their offsets must not enlarge coverage masks or create a latch. + for level in [DiagnosticLevel::Error, DiagnosticLevel::Warn] { + let sim = Simulator::from_sv_sources(vec![(source, Path::new("oob_state.sv"))], "Top") + .diagnostic_policy(policy("inferred_latch", level)) + .build_interpreter() + .unwrap(); + assert!(sim.warnings().is_empty(), "{:?}", sim.warnings()); + } } } diff --git a/crates/celox/tests/frontends/systemverilog/indexed_select.rs b/crates/celox/tests/frontends/systemverilog/indexed_select.rs index f1816a8b4ab..6350b87d6f7 100644 --- a/crates/celox/tests/frontends/systemverilog/indexed_select.rs +++ b/crates/celox/tests/frontends/systemverilog/indexed_select.rs @@ -370,6 +370,34 @@ fn continuous_part_selects_partly_outside_drive_the_bits_inside() { assert_eq!(sim.get(r), 0x5au8.into()); } +sv_backends! { + fn generated_pipeline_with_unselected_invalid_array_element(sim) { + @case "indexed_select::generated_pipeline_with_unselected_invalid_array_element"; + } + fn generated_pipeline_with_unselected_invalid_array_element_four_state(sim) { + @case "indexed_select::generated_pipeline_with_unselected_invalid_array_element_four_state"; + } + fn invalid_unpacked_elements_preserve_type_in_conditionals(sim) { + @case "indexed_select::invalid_unpacked_elements_preserve_type_in_conditionals"; + } + fn constant_invalid_unpacked_indices_read_defaults_and_ignore_writes(sim) { + @case "indexed_select::constant_invalid_unpacked_indices_read_defaults_and_ignore_writes"; + } +} + +// Icarus 13.0 returns X here, contrary to IEEE 1800-2023 7.4.5 Table 7-1. +// Keep this regression local, like the partial continuous-select check above. +sv_backends! { + fn constant_invalid_two_state_unpacked_read(sim) { + @setup { + let source = "module Top(output logic [7:0] q); bit [7:0] b[1]; assign q=b[1]; endmodule"; + } + @build Simulator::from_sv_sources(vec![(source, Path::new("invalid_bit_element.sv"))], "Top").four_state(true); + let q=sim.signal("q"); + assert_eq!(sim.get_four_state(q), (BigUint::default(), BigUint::default())); + } +} + sv_backends! { fn generated_pipeline_with_explicit_generate_branches(sim) { @case "indexed_select::generated_pipeline_with_explicit_generate_branches"; diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 3b4348a8717..12e3dbdbd08 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -5300,25 +5300,6 @@ fn rejects_constructs_that_are_not_yet_lowered() { module Top(input logic [1:0] a); Child child[0:-1](.a(a)); endmodule "#, ), - ( - "index 2 of `values` outside its declared range", - r#" - module Top(output logic y); - logic [7:0] values [0:1][0:2]; - assign y = values[0][3]; - endmodule - "#, - ), - ( - "index 2 of `values` outside its declared range", - r#" - module Top(output logic y); - localparam J = 3; - logic [7:0] values [0:1][0:2]; - assign y = values[0][J]; - endmodule - "#, - ), ( "combinational expression", r#" @@ -5667,15 +5648,6 @@ fn rejects_constructs_that_are_not_yet_lowered() { endmodule "#, ), - ( - "index 2 of `values` outside its declared range", - r#" - module Top(output logic y); - logic [7:0] values [0:1][0:2]; - assign y = values[1][3]; - endmodule - "#, - ), ( "systemverilog inout port", r#" diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 28c62e18b39..e56ff78d97a 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -1404,12 +1404,14 @@ fn readmem_diagnostics_identify_task_and_requested_range() { } } +/// The action of a deferred cover, like that of a deferred assertion, is +/// one subroutine call (IEEE 1800-2023 16.4). #[test] -fn rejects_deferred_cover_instead_of_discarding_its_semantics() { +fn rejects_deferred_cover_actions_other_than_a_task_call() { for timing in ["#0", "final"] { let source = format!("module Top(output logic y); initial cover {timing} (1) y = 1; endmodule"); - assert!(build_error(&source).contains("deferred immediate cover")); + assert!(build_error(&source).contains("deferred assertion action")); } } diff --git a/crates/celox/tests/sv_deferred_assertions.rs b/crates/celox/tests/sv_deferred_assertions.rs index a92d9a44e6f..bffd145a554 100644 --- a/crates/celox/tests/sv_deferred_assertions.rs +++ b/crates/celox/tests/sv_deferred_assertions.rs @@ -1,6 +1,6 @@ #![cfg(feature = "systemverilog")] -//! The actions of deferred immediate assertions in processes wait in the -//! process's deferred assertion report queue: `#0` ones mature in the +//! The actions of deferred immediate assertions wait in the deferred +//! assertion report queue of their process: `#0` ones mature in the //! Observed region, `final` ones in the Postponed region, and a flush point //! of the process discards those still waiting (IEEE 1800-2023 16.4). use celox::{AssertionDeferral, Report, RuntimeEvent, Severity}; @@ -124,6 +124,160 @@ macro_rules! deferred { ); } + /// Combinational processes run again when a source changes; the + /// second run flushes the failure of the first (IEEE 1800-2023 + /// 16.4.2). A module item is the same assertion in an + /// `always_comb` (16.4.3). + #[test] + fn rerunning_a_combinational_process_flushes_waiting_actions() { + let glitch = "initial begin #1 a = 1; #0 b = 1; end"; + for assertion in [ + "always_comb d: assert #0 (a == b) else $error(\"d\");", + "always_comb d: assert final (a == b) else $error(\"d\");", + "always @(a or b) d: assert #0 (a == b) else $error(\"d\");", + "d: assert #0 (a == b) else $error(\"d\");", + "d: assume final (a == b) else $error(\"d\");", + ] { + assert_eq!(run(&format!(" {assertion}\n {glitch}"), 1), vec![], "{assertion}"); + let mut reports = run(&format!(" {assertion}\n initial #1 a = 1;"), 1); + assert_eq!(reports.len(), 1, "{assertion}: {reports:?}"); + assert_eq!(reports.remove(0).0, "d", "{assertion}"); + } + } + + /// A process also runs again when the evaluation itself changes + /// one of its inputs, here `y` through the continuous assignment + /// from `x`, and that run flushes the earlier failure too. + #[test] + fn reruns_from_changes_within_an_evaluation_flush_waiting_actions() { + let body = " bit y;\n assign y = ~x;\n \ + always_comb d: assert #0 (a == y) else $error(\"d\");\n \ + initial begin x = 1; #1 a = 1; #0 x = 0; end"; + assert_eq!(run(body, 1), vec![]); + } + + /// A module item in a generate region or a generate block is a + /// deferred assertion as well. + #[test] + fn module_assertions_in_generate_scopes_are_deferred() { + for item in [ + "generate d: assert #0 (a == b) else $error(\"d\"); endgenerate", + "if (1) begin : g d: assert #0 (a == b) else $error(\"d\"); end", + "for (genvar i = 0; i < 1; i++) begin : g\n d: assert #0 (a == b) else $error(\"d\");\n end", + "case (1) 1: begin : g d: assert #0 (a == b) else $error(\"d\"); end endcase", + ] { + assert_eq!( + run(&format!(" {item}\n initial begin #1 a = 1; #0 b = 1; end"), 1), + vec![], + "{item}" + ); + let reports = run(&format!(" {item}\n initial #1 a = 1;"), 1); + assert_eq!(reports.len(), 1, "{item}: {reports:?}"); + } + } + + /// A run watching reports matures the actions of a settle that + /// no step ran before it checks them, and stops there. + #[test] + fn fail_on_sees_actions_of_settles_without_steps() { + let mut sim = simulation(" always_comb d: assert #0 (a) else $error(\"d\");"); + sim.set_fail_on(Some(Severity::Error)); + sim.run_until(10).unwrap(); + assert_eq!(sim.time(), 0); + assert_eq!(sim.failure().map(|report| report.message.clone()), Some(b"d".to_vec())); + } + + /// A run leaving a slot with nothing due ends it, so a deferred + /// `$fatal` of its settle ends the run there, also without + /// `set_fail_on`, by `run_until` or by `step`. + #[test] + fn a_deferred_fatal_of_an_idle_slot_ends_the_run() { + for (body, step) in [ + (" always_comb assert #0 (a) else $fatal(1, \"failed\");", false), + (" always_comb assert #0 (a) else $fatal(1, \"failed\");\n initial #5 $display(\"later\");", true), + ] { + let mut sim = simulation(body); + let result = if step { sim.step().map(|_| ()) } else { sim.run_until(10) }; + assert!(result.is_err(), "{body}"); + assert_eq!(sim.time(), 0, "{body}"); + } + // Also when a settle at that time already ran, by + // `eval_comb` or by a run to the current time. + let body = " always_comb assert #0 (a) else $fatal(1, \"failed\");"; + for settle in [false, true] { + let mut sim = simulation(body); + if settle { + sim.eval_comb().unwrap(); + } else { + sim.run_until(0).unwrap(); + } + assert!(sim.run_until(10).is_err(), "eval_comb: {settle}"); + assert_eq!(sim.time(), 0, "eval_comb: {settle}"); + } + // `advance_to` leaves the slot too. + let mut sim = simulation(body); + assert!(sim.advance_to(1).is_err()); + assert_eq!(sim.time(), 0); + // A step with nothing scheduled, after a settle or not. + for settle in [false, true] { + let mut sim = simulation(body); + if settle { + sim.eval_comb().unwrap(); + } + assert!(sim.step().is_err(), "step after eval_comb: {settle}"); + } + } + + /// A run watching reports also checks the actions of a settle + /// that already ran at the time it leaves. + #[test] + fn fail_on_sees_actions_of_earlier_settles() { + let mut sim = simulation(" always_comb d: assert #0 (a) else $error(\"d\");"); + sim.eval_comb().unwrap(); + sim.set_fail_on(Some(Severity::Error)); + sim.run_until(10).unwrap(); + assert_eq!(sim.time(), 0); + assert_eq!(sim.failure().map(|report| report.message.clone()), Some(b"d".to_vec())); + } + + /// A design without events may never step; the initial settle + /// of combinational logic belongs to time zero, whose slot is + /// over once nothing more is due. + #[test] + fn actions_of_the_initial_settle_mature_without_a_step() { + let mut sim = simulation(" d: assume #0 (a) else $error(\"d\");"); + sim.run_until(0).unwrap(); + assert_eq!( + summary(sim.drain_runtime_events()), + vec![("d".to_owned(), Some(AssertionDeferral::Observed))] + ); + } + + /// A deferred cover reports its pass action when it matures. + #[test] + fn deferred_cover_reports_when_it_matures() { + let cover = " c: cover #0 (a != b) $info(\"c\");\n "; + assert_eq!(run(&format!("{cover}initial begin #1 a = 1; #0 b = 1; end"), 1), vec![]); + assert_eq!( + run(&format!("{cover}initial #1 a = 1;"), 1), + vec![("c".to_owned(), Some(AssertionDeferral::Observed))] + ); + } + + /// A deferred `$fatal` of a combinational process ends the + /// simulation when it matures, not while combinational logic + /// settles. + #[test] + fn a_combinational_deferred_fatal_ends_the_simulation_when_it_matures() { + let mut sim = simulation( + " always_comb f: assert final (a == b) else $fatal(1, \"boom\");\n \ + initial begin #1 a = 1; #0 b = 1; #1 a = 0; end", + ); + sim.run_until(1).unwrap(); + assert!(sim.run_until(5).is_err()); + assert_eq!(sim.time(), 2); + } + /// A deferred `$fatal` ends the simulation when it matures, at /// the end of its time slot. #[test] @@ -289,6 +443,87 @@ fn deferred_actions_mature_at_the_end_of_edges_and_derived_ticks() { assert_eq!(labels, ["o", "d", "o", "o", "d", "o", "o", "d", "o"]); } +/// Without a scheduler, a settle of combinational logic ends the host +/// call's time slot. +#[test] +fn combinational_deferred_actions_mature_when_logic_settles() { + let source = "module Top(input bit a);\n \ + always_comb d: assert #0 (a) else $error(\"d\");\n\ + endmodule"; + let mut sim = + celox::Simulator::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + .build() + .unwrap(); + assert_eq!( + summary(sim.drain_runtime_events()), + vec![("d".to_owned(), Some(AssertionDeferral::Observed))] + ); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 1u8)).unwrap(); + assert_eq!(summary(sim.drain_runtime_events()), vec![]); +} + +/// A drain returns a deferred `$fatal` of combinational logic as a fatal +/// report. +#[test] +fn draining_a_combinational_deferred_fatal_returns_its_report() { + let source = "module Top(input bit a);\n \ + always_comb assert #0 (a) else $fatal(1, \"failed\");\n\ + endmodule"; + let mut sim = + celox::Simulator::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + .build() + .unwrap(); + let events = sim.drain_runtime_events(); + assert!( + matches!( + events.as_slice(), + [RuntimeEvent::Report(Report { severity: Severity::Fatal, message, .. })] + if message == b"failed" + ), + "{events:?}" + ); +} + +/// A tick is one time slot: the settle before its flip-flops does not end +/// it, so the settle after them flushes what failed in between. +#[test] +fn a_tick_flushes_actions_of_the_settle_before_its_flip_flops() { + let source = "module Top(input bit clk);\n \ + bit q;\n \ + always_ff @(posedge clk) q <= 1'b1;\n \ + always_comb assert #0 (!clk || q) else $error(\"failed\");\n\ + endmodule"; + let mut sim = + celox::Simulator::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + .build() + .unwrap(); + assert_eq!(summary(sim.drain_runtime_events()), vec![]); + // The host write leaves the logic to settle before the flip-flops. + let q = sim.signal("q"); + sim.set(q, 0u8); + let clk = sim.event("clk"); + sim.tick(clk).unwrap(); + assert_eq!(summary(sim.drain_runtime_events()), vec![]); +} + +/// The first drain of a simulation settles its combinational logic before +/// the slot matures, and returns what failed. +#[test] +fn a_first_drain_returns_actions_of_the_initial_settle() { + let source = "module Top;\n bit a;\n \ + d: assert #0 (a) else $error(\"d\");\n\ + endmodule"; + let mut sim = + celox::Simulation::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + .build() + .unwrap(); + assert_eq!( + summary(sim.drain_runtime_events()), + vec![("d".to_owned(), Some(AssertionDeferral::Observed))] + ); +} + #[test] fn deferred_actions_are_one_display_or_severity_task_call() { let source = "module Top; bit a;\n \ diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 779e2e7260e..04c403a1f49 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -43,7 +43,7 @@ synthesis and is tested at the design level. | Combinational processes | `always_comb`, `always @*`, blocking `always_latch`, block-local variables, sequential and dependent blocking assignments, reads of a variable before the process writes it (its previous value) | | Sequential processes | `always_ff @(posedge clk)`, `always @(posedge clk or negedge rst_n)` and the like, blocking and nonblocking assignments, concatenated targets, four-state clock and reset signals, one asynchronous reset shared by several clock domains, processes at both edges of one clock or reset, and one signal as the clock of some processes and the asynchronous reset of others (a timed `Simulation` runs every edge; `Simulator::tick` is the rising edge of its event only) | | Initial blocks | `initial` blocks and variable declaration initializers (`logic [7:0] v = 8'h5a;`, also of interface members); initializers take effect before the `initial` blocks. One whose writes have constant values, with constant `if` / `for` and `$readmemh` / `$readmemb`, defines the initial state. Any other, such as one that reads design state or calls a system task, runs as a process from time zero in a timed `Simulation`; a `Simulator` does not run processes, so building one for such a design fails with `SimulatorErrorKind::ProcessRequiresSimulation` | -| Statements | `if` / `else`, `case`, `casez`, `casex`, `case ... inside`, `unique` / `priority`, `for`, `while`, `do ... while`, `repeat`, `forever` and `foreach` (unrolled when the trip count is constant, otherwise executed at run time), `break` / `continue` / `return`, immediate assertions | +| Statements | `if` / `else`, `case`, `casez`, `casex`, `case ... inside`, `unique` / `priority`, `for`, `while`, `do ... while`, `repeat`, `forever` and `foreach` (unrolled when the trip count is constant, otherwise executed at run time), `break` / `continue` / `return`, immediate and deferred immediate assertions | | Functions | `function` and `task` with `input`, `output` and `inout` arguments, `return` or assignment to the function name, local variables and `localparam`s, selected and composite assignments; calls are inlined. Calls with constant arguments in constant expressions (parameters, ranges) are evaluated during elaboration | ### Timing controls {#timing-controls} @@ -601,12 +601,6 @@ ignored, as 24.7 specifies, with a compilation warning function of a module. Calls in function declarations are diagnosed even when the function is unused; the diagnostic does not depend on constant evaluation executing it. -### Immediate cover - -Immediate cover executes its pass statement when the condition is true. -Coverage counters and reports are not exposed. Deferred cover (`#0` / `final`) -is rejected because its scheduling is not modeled. - ### Severity tasks and reports `$info`, `$warning`, `$error` and `$fatal`, including the default `$error` of @@ -625,22 +619,29 @@ run; `$fatal` also ends the simulation with an error. ### Deferred assertions -In an `initial` or `always` process with a timing control, and in an -edge-triggered `always` or `always_ff` process, the action of `assert #0`, -`assume #0`, `assert final` and `assume final` waits in the process's -deferred assertion report queue (IEEE 1800-2023 16.4). Its arguments are -evaluated when the assertion executes. The process flushes the queue each -time it resumes from an event control or a wait, and an edge-triggered -process each time it runs; a resume after a delay is no flush point -(16.4.2). When the time slot is over, the actions still waiting are -executed: those of `#0` ones first, then those of `final` ones. A deferred -`$fatal` ends the simulation then. An action is one display or severity -task call; a user subroutine, or more than one statement, is rejected. - -The same assertions in `always_comb`, `always_latch` or a process lowered as -combinational logic (an `always` whose only timing control is its leading -event control) still report at once, like simple immediate assertions. -Deferred assertions as module items and deferred cover are rejected. +The action of `assert #0`, `assume #0`, `cover #0` and their `final` forms +waits in the deferred assertion report queue of its process (IEEE 1800-2023 +16.4). Its arguments are evaluated when the assertion executes. The process +flushes the queue at its flush points (16.4.2): +- a process with timing controls, each time it resumes from an event control + or a wait; a resume after a delay is no flush point; +- an edge-triggered `always` or `always_ff` process, each time it runs; +- `always_comb`, `always_latch` and an `always` lowered as combinational logic + (one whose only timing control is its leading event control), each time it + runs again. + +When the time slot is over, the actions still waiting are executed: those of +`#0` ones first, then those of `final` ones. A deferred `$fatal` ends the +simulation then. A deferred assertion as a module item is the same assertion +in an `always_comb` (16.4.3). An action is one display or severity task +call; a user subroutine, or more than one statement, is rejected. A +`Simulator` call is a time slot: there, actions mature when the call settles +combinational logic or runs a domain. + +### Immediate cover + +Immediate cover executes its pass statement when the condition is true. +Coverage counters and reports are not exposed. ### Constant functions diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 49f40d7e00d..952eb064d73 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -84,7 +84,7 @@ The main supported areas are: | RTL processes | `assign`, `always_comb`, `always @*`, blocking `always_latch`, edge-triggered `always` and `always_ff` | | Timed processes | `initial` and `always` with `#delay` (also time literals such as `#5ns`), `@(...)` on variables, edges, selects, expressions and `@*`, `wait (...)`, nonblocking assignments and task calls with timing controls | | Computation | Arithmetic, selects, assignment patterns, branches, loops and functions | -| Simulation helpers | Immediate assertions, display tasks, `$readmemh` / `$readmemb`, time queries and random numbers | +| Simulation helpers | Immediate and deferred immediate assertions, display tasks, `$readmemh` / `$readmemb`, time queries and random numbers | Each area has restrictions. Use the [detailed support list](./systemverilog-reference#what-is-supported) to check diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index efe68525764..5de49f53e7f 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -41,7 +41,7 @@ outline: [2, 3] | 組み合わせプロセス | `always_comb`、`always @*`、ブロッキング代入の `always_latch`、ブロックローカル変数、逐次・依存するブロッキング代入、プロセスが書き込む前の変数の読み出し(直前の値) | | 順序プロセス | `always_ff @(posedge clk)`、`always @(posedge clk or negedge rst_n)` など。ブロッキング・ノンブロッキング代入、連結を代入先とする代入、4 値のクロック・リセット信号、複数のクロックドメインで共有する非同期リセット、同一クロック・同一リセットの両エッジを使うプロセス、あるプロセスのクロックを別のプロセスの非同期リセットとして使う信号(時間付きの `Simulation` はすべてのエッジを実行します。`Simulator::tick` はイベントの立ち上がりエッジだけです) | | initial ブロック | `initial` ブロックと変数宣言の初期化子(`logic [7:0] v = 8'h5a;`、interface のメンバーを含む)。初期化子は `initial` ブロックより先に適用。書き込む値が定数のもの(定数の `if` / `for`、`$readmemh` / `$readmemb` を含む)は初期状態を定める。デザインの状態を読むものやシステムタスクを呼ぶものなどそれ以外は、時間を持つ `Simulation` で時刻 0 からプロセスとして実行(`Simulator` はプロセスを実行しないため、このようなデザインでは `SimulatorErrorKind::ProcessRequiresSimulation` でビルドに失敗) | -| 文 | `if` / `else`、`case`、`casez`、`casex`、`case ... inside`、`unique` / `priority`、`for`、`while`、`do ... while`、`repeat`、`forever`、`foreach`(反復回数が定数なら展開し、そうでなければ実行時に実行)、`break` / `continue` / `return`、即時アサーション | +| 文 | `if` / `else`、`case`、`casez`、`casex`、`case ... inside`、`unique` / `priority`、`for`、`while`、`do ... while`、`repeat`、`forever`、`foreach`(反復回数が定数なら展開し、そうでなければ実行時に実行)、`break` / `continue` / `return`、即時アサーションと遅延付き即時アサーション | | 関数 | `input` / `output` / `inout` 引数を持てる `function` と、`task`。`return`、または関数名への代入で値を返す。ローカル変数と `localparam`、部分選択や複合的な代入先への代入。呼び出しはインライン展開。定数式(パラメータ、範囲)の中の定数引数による呼び出しはエラボレーション時に評価 | ### タイミング制御 {#timing-controls} @@ -401,19 +401,20 @@ VPI ホストと `celox` コマンドが表示する形に整形します。`cel ### 遅延付きアサーション -タイミング制御を含む `initial` / `always` プロセスと、エッジで起動する `always` / -`always_ff` プロセスでは、`assert #0`、`assume #0`、`assert final`、`assume final` の -アクションはプロセスの遅延アサーション報告キューで待ちます(IEEE 1800-2023 16.4)。 -引数はアサーションを実行した時点で評価します。プロセスはイベント制御や wait から再開する -たびに、エッジで起動するプロセスは実行するたびにキューをフラッシュします。遅延からの再開は -フラッシュ点ではありません(16.4.2)。タイムスロットが終わると、まだ待っているアクションを -`#0` のもの、`final` のものの順に実行します。遅延付きの `$fatal` はそこでシミュレーションを -終了します。アクションは表示タスクか重大度タスクの呼び出し 1 つで、ユーザーのサブルーチンや -複数の文は拒否します。 - -`always_comb`、`always_latch`、組み合わせ回路として扱うプロセス(タイミング制御が先頭の -イベント制御だけの `always`)の同じアサーションは、まだ単純な即時アサーションと同じく -その場で報告します。モジュール直下の遅延付きアサーションと遅延付きの cover は拒否します。 +`assert #0`、`assume #0`、`cover #0` とそれぞれの `final` 形のアクションは、プロセスの遅延 +アサーション報告キューで待ちます(IEEE 1800-2023 16.4)。引数はアサーションを実行した時点で +評価します。プロセスはフラッシュ点でキューを空にします(16.4.2)。 +- タイミング制御を含むプロセスは、イベント制御や wait から再開するたびに。遅延からの再開は + フラッシュ点ではありません。 +- エッジで起動する `always` / `always_ff` プロセスは、実行するたびに。 +- `always_comb`、`always_latch`、組み合わせ回路として扱う `always`(タイミング制御が先頭の + イベント制御だけのもの)は、再実行するたびに。 + +タイムスロットが終わると、まだ待っているアクションを `#0` のもの、`final` のものの順に実行します。 +遅延付きの `$fatal` はそこでシミュレーションを終了します。モジュール直下の遅延付きアサーションは、 +`always_comb` に入れた同じアサーションです(16.4.3)。アクションは表示タスクか重大度タスクの +呼び出し 1 つで、ユーザーのサブルーチンや複数の文は拒否します。`Simulator` では呼び出し 1 回が +タイムスロットで、組み合わせ回路が落ち着いたときやドメインを実行したときにアクションが成熟します。 ### 定数関数 diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 947852c6397..4c8a4face3e 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -80,7 +80,7 @@ X/Z を扱う場合は builder に `.four_state(true)` を指定します。 | RTL のプロセス | `assign`、`always_comb`、`always @*`、ブロッキング代入の `always_latch`、エッジで起動する `always` と `always_ff` | | 時間を持つプロセス | `#delay`(`#5ns` などの時間リテラルを含む)、変数・エッジ・選択・式・`@*` に対する `@(...)`、`wait (...)`、ノンブロッキング代入、タイミング制御を持つ task 呼び出しを使う `initial` と `always` | | 演算と制御 | 算術、部分選択、assignment pattern、分岐、ループ、関数 | -| シミュレーション補助 | 即時アサーション、表示タスク、`$readmemh` / `$readmemb`、時刻の取得、乱数 | +| シミュレーション補助 | 即時アサーションと遅延付き即時アサーション、表示タスク、`$readmemh` / `$readmemb`、時刻の取得、乱数 | 各領域には制約があります。デザインを移植する際は、 [詳しい対応一覧](./systemverilog-reference#what-is-supported)でポート、型、文、システム関数を確認してください。 diff --git a/flake.lock b/flake.lock index 1e1a987ee6e..0b5d0171d87 100644 --- a/flake.lock +++ b/flake.lock @@ -7,11 +7,11 @@ ] }, "locked": { - "lastModified": 1792542234, - "narHash": "sha256-485fkwc2ZSHqtC+FpF2CrtuynntL4fm378pF0nBRZHQ=", + "lastModified": 1792838410, + "narHash": "sha256-PCLsTfCsvQil43pMJRF6rZIgts9ddGEGg31R+S49aV8=", "owner": "tignear", "repo": "nix-packages", - "rev": "d0eff0edac65dd338f780e84882a4dc7e473ec28", + "rev": "fd5c964507d21e820c948e280a0aecda842bd5b2", "type": "github" }, "original": {