Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
203 changes: 203 additions & 0 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1817,6 +1817,7 @@ fn prepare_external_hierarchy_collecting(
&lowered_modules,
four_state,
allow_inferred_latches,
true,
warnings,
)?;
modules.insert(
Expand Down Expand Up @@ -2331,6 +2332,7 @@ fn schedule_sources_collecting(
&lowered_modules,
four_state,
allow_inferred_latches,
false,
warnings,
)?;
module_names.insert(module_id, key.name.clone());
Expand Down Expand Up @@ -3556,6 +3558,7 @@ pub(crate) fn attach_instance_glue(
lowered_modules: &HashMap<ModuleId, LoweredSvModule>,
four_state: bool,
allow_inferred_latches: bool,
foreign: bool,
warnings: &mut Vec<crate::warning::PendingWarning>,
) -> Result<(), ParserError> {
let mut signal_names = lowered.signal_names.clone();
Expand Down Expand Up @@ -3685,6 +3688,67 @@ pub(crate) fn attach_instance_glue(
let waits = lowered_modules
.values()
.any(|module| !module.sim_module.wait_sites.is_empty());
// An `always_comb` alternative is kept only if a wait or a flip-flop
// domain counts one of its targets. Within the module, they name its
// wait terms, its triggers and whole-variable copies of them; beyond
// it, ports, instance connections and package variables. Every counter
// a design declares also keeps nonblocking writes queued, so a design
// with a nonblocking switch lowers every alternative, and so does a
// module of a design with foreign modules, which this module does not see.
let watch_seeds = (waits
&& !foreign
&& !lowered_modules
.values()
.any(|module| !module.sim_module.nba_switches.is_empty()))
.then(|| {
let mut seeds: HashSet<SourceVarId> = module
.wait_sites
.iter()
.flat_map(|site| site.terms.iter().map(|&(signal, _)| signal))
.collect();
let triggers = module
.eval_only_ff_blocks
.keys()
.chain(module.apply_ff_blocks.keys())
.chain(module.eval_apply_ff_blocks.keys())
.chain(module.split_commit_ff_blocks.keys())
.chain(module.parallel_ff_parts.keys());
for trigger in triggers {
seeds.insert(trigger.clock);
seeds.extend(trigger.resets.iter().copied());
}
for &(copy, signal) in &lowered.event_copies {
seeds.extend([copy, signal]);
}
seeds.extend(lowered.package_variables.iter().map(|(id, _, _)| *id));
let instantiated = lowered_modules.values().any(|other| {
other
.instances
.iter()
.any(|instance| &LoweredSvModuleKey::instance_key(instance) == current_key)
});
if instantiated {
seeds.extend(
parent_variables
.iter()
.filter(|(_, variable)| variable.kind.is_port())
.map(|(id, _)| *id),
);
}
let mut names = HashSet::default();
for (_, _, _, connections) in &resolved_instances {
for actual in connections.iter().filter_map(|c| c.actual_expr.as_ref()) {
procedural::expr_idents(actual, &mut names);
}
}
seeds.extend(
names
.iter()
.filter_map(|name| signal_names.get(name).copied()),
);
seeds.extend(port_assignments.iter().map(|(target, _)| *target));
seeds
});
let (comb_blocks, arena, created, comb_observers, comb_sites, comb_alternatives) =
lower_comb_processes(
&lowered.source,
Expand All @@ -3699,6 +3763,7 @@ pub(crate) fn attach_instance_glue(
&mut module.extern_functions,
warnings,
waits,
watch_seeds.as_ref(),
)
.map_err(|error| match error {
sv::AnalyzerError::MemoryFile(detail) => ParserError::MemoryFile {
Expand Down Expand Up @@ -4266,6 +4331,7 @@ fn lower_comb_processes(
extern_functions: &mut Vec<ExternFunction>,
warnings: &mut Vec<crate::warning::PendingWarning>,
waits: bool,
watch_seeds: Option<&HashSet<SourceVarId>>,
) -> Result<
(
Vec<LogicPath<SourceVarId>>,
Expand Down Expand Up @@ -4294,6 +4360,8 @@ fn lower_comb_processes(
pm.runtime_errors = std::mem::take(runtime_errors);
pm.extern_functions = std::mem::take(extern_functions);
let random_seeds = process_random_seeds(module);
let watchable =
watch_seeds.map(|seeds| watchable_variables(&pm, module, port_assignments, seeds));
for (index, process) in module.comb_processes().iter().enumerate() {
if let Some(condition) = process.condition() {
let condition =
Expand Down Expand Up @@ -4354,6 +4422,15 @@ fn lower_comb_processes(
targets.sort_unstable();
targets.dedup();
comb_blocks.extend(paths);
if let Some(watchable) = &watchable
&& targets
.iter()
.map(|target| target.id)
.chain(pm.written_variables(process.body()))
.all(|id| !watchable.contains(&id))
{
continue;
}
if let Some((paths, alternative)) = lower_comb_alternative(
&mut pm,
process,
Expand Down Expand Up @@ -4492,6 +4569,65 @@ fn lower_comb_processes(
Ok((comb_blocks, arena, created, observers, sites, alternatives))
}

/// `seeds` and the variables a whole-variable copy of a combinational
/// process or a port assignment may connect to them, in either direction.
/// Any variable a process writes may copy any variable of the same width
/// the process writes or reads.
fn watchable_variables(
pm: &procedural::ProcModule<'_>,
module: &sv::ir::Module,
port_assignments: &[(SourceVarId, Vec<sv::ir::Stmt>)],
seeds: &HashSet<SourceVarId>,
) -> HashSet<SourceVarId> {
let mut groups: HashMap<(usize, usize), Vec<SourceVarId>> = HashMap::default();
let mut group = |index: usize, writes: HashSet<SourceVarId>, reads: Vec<SourceVarId>| {
let widths: HashSet<usize> = writes.iter().map(|&id| pm.var(id).width).collect();
for id in writes.into_iter().chain(reads) {
let width = pm.var(id).width;
if widths.contains(&width) {
groups.entry((index, width)).or_default().push(id);
}
}
};
let processes = module.comb_processes();
for (index, process) in processes.iter().enumerate() {
let mut reads = pm.implicit_reads(process.body(), true);
reads.extend(pm.implicit_reads(process.sensitivity_body(), true));
group(
index,
pm.written_variables(process.body()),
reads.iter().map(|read| read.id).collect(),
);
}
for (index, (target, body)) in port_assignments.iter().enumerate() {
let mut writes = pm.written_variables(body);
writes.insert(*target);
group(
processes.len() + index,
writes,
pm.implicit_reads(body, true)
.iter()
.map(|read| read.id)
.collect(),
);
}
let mut watchable = seeds.clone();
let mut groups: Vec<_> = groups.into_values().collect();
loop {
let before = groups.len();
groups.retain(|group| {
if !group.iter().any(|id| watchable.contains(id)) {
return true;
}
watchable.extend(group.iter().copied());
false
});
if groups.len() == before {
return watchable;
}
}
}

/// The imperative unit of an `always_comb` process lowered symbolically to
/// `targets`, and its [`CombAlternative`], if the unit may store a variable
/// of the design twice in one execution. Otherwise nothing of the attempt
Expand Down Expand Up @@ -9184,6 +9320,73 @@ mod tests {
.count()
}

/// The `always_comb` alternatives the modules of `source` lowered.
fn comb_alternatives(source: &str) -> usize {
let mut trace = FrontendTrace::default();
schedule_sources(
&[(source, Path::new("top.sv"))],
"Top",
&[],
&[],
&[],
false,
&celox_frontend_core::ParallelScheduleOptions::default(),
&FrontendTraceOptions {
sim_modules: true,
..Default::default()
},
Some(&mut trace),
&mut Vec::new(),
)
.unwrap_or_else(|error| panic!("{error}"));
trace
.sim_modules
.expect("traced modules")
.values()
.map(|module| module.comb_alternatives.len())
.sum()
}

/// An `always_comb` that stores a variable twice gets its imperative
/// alternative only where a wait or a flip-flop domain may watch it.
#[test]
fn comb_alternatives_only_for_watchable_targets() {
let multi_store = "always_comb begin w = 0; if (s[0]) w = 1; end";
for (case, body, alternatives) in [
("unwatched", "initial forever @(s) ;", 0),
("waited", "initial forever @(w) ;", 1),
(
"aliased clock",
"bit c; assign c = w; bit q; always_ff @(posedge c) q <= ~q;
initial forever @(s) ;",
1,
),
(
"nonblocking switch",
"bit [7:0] t; initial forever @(s) t <= s;",
1,
),
] {
let source = format!(
"module Top(input bit [7:0] s);
bit w;
{multi_store}
{body}
endmodule"
);
assert_eq!(comb_alternatives(&source), alternatives, "{case}");
}
let child_port = "module Child(input bit [7:0] s, output bit w);
always_comb begin w = 0; if (s[0]) w = 1; end
endmodule
module Top(input bit [7:0] s);
bit w;
Child child(.s(s), .w(w));
initial forever @(w) ;
endmodule";
assert_eq!(comb_alternatives(child_port), 1, "child output port");
}

/// Only the `always @(list)` processes of a combinational loop stay
/// processes; one `initial` block drives each design.
#[test]
Expand Down
28 changes: 28 additions & 0 deletions crates/celox-frontend-sv/src/lowering/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,34 @@ impl<'a> ProcModule<'a> {
false
}

/// The variables `body` may write, directly or in the bodies of its
/// callees. Names a callee declares itself may resolve to a variable of
/// the module too, so the set may be larger than the writes.
pub fn written_variables(&self, body: &[sv::ir::Stmt]) -> HashSet<SourceVarId> {
let mut names = HashSet::default();
let mut calls = Vec::new();
written_names(body, &mut names);
for stmt in body {
stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls));
}
let mut visited = HashSet::default();
while let Some((callee, args)) = calls.pop() {
let sv::ir::Callee::Subroutine(name) = callee else {
continue;
};
if let Some(subroutine) = self.subroutine(&name) {
default_calls(subroutine, &args, &mut calls);
if visited.insert(name) {
written_names(&subroutine.body, &mut names);
for stmt in &subroutine.body {
stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls));
}
}
}
}
names.iter().filter_map(|name| self.id(name)).collect()
}

/// Whether `always @(items) body` is `always @* body`: no item has an edge
/// or a select, the items name exactly the variables the implicit event
/// expression of `body` has (IEEE 1800-2023 9.4.2.2), and the body neither
Expand Down
15 changes: 13 additions & 2 deletions crates/celox-sv-analyzer/src/ast/constant_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,9 +267,20 @@ fn bind_in_context(
})
{
let value = indexed_expression(id, native, tree, query_dimensions)?;
values.push(
let value = if query_dimensions
.array_parameter_values
.contains_key(&name_key)
{
selects::indexed_expression_value(
&tree.state,
value,
query_dimensions,
)
} else {
expr_to_index_const(&tree.state, value, query_dimensions)
.ok_or_else(|| unsupported("parameter selection shape"))?,
};
values.push(
value.ok_or_else(|| unsupported("parameter selection shape"))?,
);
continue;
}
Expand Down
Loading
Loading