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
2 changes: 1 addition & 1 deletion crates/celox-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1428,7 +1428,7 @@ pub(crate) fn generated_time_declarations(
sources: &[(&str, &std::path::Path)],
roots: Option<&[&str]>,
) -> Result<String, AnalyzerError> {
timescales::generated_source_declarations(sources, roots, false)
timescales::generated_source_declarations(sources, roots, crate::AnalysisOptions::default())
}

const MAX_GENERATE_LOOP_EXPANSION: usize = 10_000;
Expand Down
7 changes: 3 additions & 4 deletions crates/celox-sv-analyzer/src/ast/interfaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,17 +89,16 @@ pub fn interface_prototypes_with_options(
.zip(sources)
.map(|(file, (_, path))| (&file.syntax_tree, *path))
.collect::<Vec<_>>(),
options.allow_mixed_timescales,
options,
)?)
};
let trees = files
.iter()
.zip(sources)
.map(|(file, (_, path))| (&file.syntax_tree, *path))
.collect::<Vec<_>>();
let packages =
packages::Packages::analyze_with_options(&trees, None, options.allow_mixed_timescales)
.map_err(|error| error.with_warnings(source_warnings))?;
let packages = packages::Packages::analyze_with_options(&trees, None, options)
.map_err(|error| error.with_warnings(source_warnings))?;
let package_warnings = packages.warnings().to_vec();
let mut used_names = design
.modules
Expand Down
11 changes: 5 additions & 6 deletions crates/celox-sv-analyzer/src/ast/packages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,19 +197,19 @@ impl Packages {
trees: &[(&SyntaxTree, &Path)],
roots: Option<&[&str]>,
) -> Result<Self, AnalyzerError> {
Self::analyze_with_options(trees, roots, false)
Self::analyze_with_options(trees, roots, crate::AnalysisOptions::default())
}

pub(crate) fn analyze_with_options(
trees: &[(&SyntaxTree, &Path)],
roots: Option<&[&str]>,
allow_mixed_timescales: bool,
options: crate::AnalysisOptions,
) -> Result<Self, AnalyzerError> {
let mut warnings = Vec::new();
for (tree, _) in trees {
super::warnings::append(&mut warnings, super::warnings::packages(tree));
}
match Self::analyze_with_roots_impl(trees, roots, allow_mixed_timescales) {
match Self::analyze_with_roots_impl(trees, roots, options) {
Ok(packages) => Ok(packages.with_warnings(warnings)),
Err(error) => Err(error.with_warnings(warnings)),
}
Expand All @@ -218,10 +218,9 @@ impl Packages {
fn analyze_with_roots_impl(
trees: &[(&SyntaxTree, &Path)],
roots: Option<&[&str]>,
allow_mixed_timescales: bool,
options: crate::AnalysisOptions,
) -> Result<Self, AnalyzerError> {
let mut timescales =
timescales::Timescales::collect_with_options(trees, allow_mixed_timescales)?;
let mut timescales = timescales::Timescales::collect_with_options(trees, options)?;
if let Some(roots) = roots {
timescales.select_roots(roots);
}
Expand Down
8 changes: 6 additions & 2 deletions crates/celox-sv-analyzer/src/ast/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,11 @@ pub(super) fn apply_parameter_overrides(
}
for parameter in parameters {
if let Some(value) = overrides.get(parameter.name()) {
parameter.value = Some(value.clone());
parameter.value = normalize_unbased_unsized_parameter_value(
Some(value.clone()),
parameter.declared_width(),
parameter.declared_signed(),
);
}
}
Ok(())
Expand Down Expand Up @@ -433,14 +437,14 @@ pub(super) fn parameters_from_native_with_environment(
} else {
None
};
value = normalize_unbased_unsized_parameter_value(value, parameter_width, parameter_signed);
// Apply overrides as each declaration is collected so later
// parameter initializers (including casts) are evaluated from the
// specialized values rather than defaults that will be replaced
// only after collection has finished.
if !is_local && let Some(override_value) = parameter_overrides.get(&name) {
value = Some(override_value.clone());
}
value = normalize_unbased_unsized_parameter_value(value, parameter_width, parameter_signed);
if value
.as_ref()
.is_some_and(|expression| is_unbounded(expression, const_env))
Expand Down
31 changes: 31 additions & 0 deletions crates/celox-sv-analyzer/src/ast/parameters/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1385,3 +1385,34 @@ fn logical_type_inference_requires_operand_types_outside_bounded_proofs() {
}),
);
}

#[test]
fn unbased_parameter_overrides_fill_declared_width_before_dependent_parameters() {
let tree = crate::source_tree::parse_scope_fixture(
"module Top #(parameter logic [57:0] FILL=0, \
parameter logic signed [57:0] SIGNED_FILL=0, \
parameter logic [57:0] COPY=FILL, parameter NEGATIVE=SIGNED_FILL < 0); endmodule",
Path::new("unbased_parameter_overrides.sv"),
)
.unwrap();
let tree = AnalysisContext::unspecialized(&tree);
for (literal, unsigned, signed) in [("'1", (1i128 << 58) - 1, -1), ("'0", 0, 0)] {
let overrides = ["FILL", "SIGNED_FILL"]
.into_iter()
.map(|name| (name.into(), ConstExpr::Literal(literal.into())))
.collect();
let mut parameters =
parameters_from_scope(&tree, &HashMap::default(), &HashMap::default(), &overrides)
.unwrap();
for reapplied in [false, true] {
if reapplied {
apply_parameter_overrides(&mut parameters, &overrides).unwrap();
}
let values = const_env_from_parameters(&tree.state, &parameters);
assert_eq!(values["FILL"], unsigned, "{literal}, reapplied={reapplied}");
assert_eq!(values["SIGNED_FILL"], signed);
assert_eq!(values["COPY"], unsigned);
assert_eq!(values["NEGATIVE"], i128::from(signed < 0));
}
}
}
35 changes: 23 additions & 12 deletions crates/celox-sv-analyzer/src/ast/timescales.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ pub(super) struct Timescales {
instantiated: HashSet<String>,
roots: Option<HashSet<String>>,
specified: [u8; 2],
allow_mixed_timescales: bool,
options: crate::AnalysisOptions,
}

/// Time-query state owned by one analysis, shared explicitly by nested scopes.
Expand Down Expand Up @@ -361,7 +361,7 @@ fn time_declarations(unit: Option<i32>, precision: Option<i32>) -> String {
pub(crate) fn generated_source_declarations(
sources: &[(&str, &Path)],
roots: Option<&[&str]>,
allow_mixed_timescales: bool,
options: crate::AnalysisOptions,
) -> Converted<String> {
let trees = sources
.iter()
Expand All @@ -372,7 +372,7 @@ pub(crate) fn generated_source_declarations(
.iter()
.map(|(tree, path)| (tree, *path))
.collect::<Vec<_>>(),
allow_mixed_timescales,
options,
)?;
if let Some(roots) = roots {
scales.select_roots(roots);
Expand Down Expand Up @@ -516,13 +516,12 @@ impl Timescales {
self.precision.unwrap_or(DEFAULT.precision)
}
fn including_tree(&self, tree: &SyntaxTree) -> Converted<Self> {
let local =
Self::collect_with_options(&[(tree, Path::new(""))], self.allow_mixed_timescales)?;
let local = Self::collect_with_options(&[(tree, Path::new(""))], self.options)?;
let specified = [
self.specified[0] | local.specified[0],
self.specified[1] | local.specified[1],
];
if specified.contains(&3) && !self.allow_mixed_timescales {
if specified.contains(&3) && !self.options.allow_mixed_timescales {
return Err(unsupported(
"mixed explicit and default time units or precisions across design elements",
));
Expand Down Expand Up @@ -577,17 +576,29 @@ impl Timescales {

#[cfg(test)]
pub(super) fn collect(trees: &[(&SyntaxTree, &Path)]) -> Converted<Self> {
Self::collect_with_options(trees, false)
Self::collect_with_options(trees, crate::AnalysisOptions::default())
}

pub(super) fn collect_with_options(
trees: &[(&SyntaxTree, &Path)],
allow_mixed_timescales: bool,
options: crate::AnalysisOptions,
) -> Converted<Self> {
#[cfg(test)]
COLLECTIONS.with(|count| count.set(count.get() + 1));
let default = match options.default_timescale {
Some((unit, precision))
if (-15..=2).contains(&unit)
&& (-15..=2).contains(&precision)
&& precision <= unit =>
{
Scale { unit, precision }
}
Some(_) => return Err(unsupported("invalid default time unit or precision")),
None => DEFAULT,
};
let mut design = Self {
allow_mixed_timescales,
precision: options.default_timescale.map(|(_, precision)| precision),
options,
..Self::default()
};
// Each bit records whether a design element uses a default (1) or an
Expand Down Expand Up @@ -686,8 +697,8 @@ impl Timescales {
}
directives.sort_by_key(|(at, _)| *at);
let unit = Scale {
unit: unit_decl.0.unwrap_or(DEFAULT.unit),
precision: unit_decl.1.unwrap_or(DEFAULT.precision),
unit: unit_decl.0.unwrap_or(default.unit),
precision: unit_decl.1.unwrap_or(default.precision),
};
if unit.precision > unit.unit {
return Err(unsupported("timeprecision coarser than timeunit"));
Expand Down Expand Up @@ -740,7 +751,7 @@ impl Timescales {
}),
);
}
if specified.contains(&3) && !allow_mixed_timescales {
if specified.contains(&3) && !options.allow_mixed_timescales {
return Err(unsupported(
"mixed explicit and default time units or precisions across design elements",
));
Expand Down
9 changes: 4 additions & 5 deletions crates/celox-sv-analyzer/src/ast/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -466,12 +466,11 @@ fn validate_scope(
return Err(unsupported("mintypmax expression"));
}
ExprKind::Select { dimension, .. } => {
if let DimensionKind::Indexed { base, width, .. } = dimension.kind {
if let DimensionKind::Indexed { width, .. } = dimension.kind {
if parameter_ranges.iter().any(|range| contains(*range, dimension.tokens)) { continue; }
let mut dimensions = indexed_dimensions.clone();
dimensions.constant_indexed_base = true;
let value = expression_binding::value(base, native, syntax_tree, &dimensions)?;
selects::indexed_expression_value(&syntax_tree.state, value, &dimensions).ok_or_else(|| unsupported("index expression"))?;
// IEEE 1800-2023 11.5.1 permits a variable base. Its
// expression is bound after variable types are available;
// only the width requires constant validation here.
check_indexed_width(width, syntax_tree, indexed_dimensions)?;
}
}
Expand Down
6 changes: 4 additions & 2 deletions crates/celox-sv-analyzer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,12 @@ pub use parsed::ParsedSource;
/// simulator's two-state/four-state mode is known.
pub const DIV_ZERO_UNKNOWN_LITERAL: &str = "$celox_div_zero_unknown";

/// Options for recoverable language compatibility checks.
/// Language compatibility checks and implementation-defined timing defaults.
#[derive(Debug, Clone, Copy, Default)]
pub struct AnalysisOptions {
pub allow_mixed_timescales: bool,
/// Default unit/precision exponents; precision also bounds global resolution.
pub default_timescale: Option<(i32, i32)>,
}

/// Errors reported by the SystemVerilog analyzer.
Expand Down Expand Up @@ -246,7 +248,7 @@ pub fn generated_time_declarations_with_options(
roots: Option<&[&str]>,
options: AnalysisOptions,
) -> Result<String, AnalyzerError> {
ast::timescales::generated_source_declarations(sources, roots, options.allow_mixed_timescales)
ast::timescales::generated_source_declarations(sources, roots, options)
}

/// Parse and analyze a SystemVerilog source string.
Expand Down
3 changes: 1 addition & 2 deletions crates/celox-sv-analyzer/src/parsed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,7 @@ impl ParsedSource {
}
}
}
let mut packages =
Packages::analyze_with_options(&trees, roots, options.allow_mixed_timescales)?;
let mut packages = Packages::analyze_with_options(&trees, roots, options)?;
packages.interface_names = design_units
.into_iter()
.filter_map(|(name, kind)| {
Expand Down
27 changes: 27 additions & 0 deletions crates/celox-test-suite/src/sv/cases/indexed_select.vtest
Original file line number Diff line number Diff line change
Expand Up @@ -1736,3 +1736,30 @@
(top Top)
(assert_eq enumeration 10)
(assert_eq width 10))

(case runtime_indexed_bases_preserve_numeric_and_type_casts
(source "runtime_indexed_cast.sv" #"
module Top(input logic [63:0] data, input logic [1:0] offset,
input logic [3:0] index,
output logic [31:0] y, output logic [3:0] narrowed,
output logic [3:0] typed, output logic [63:0] written);
typedef logic [2:0] index_t;
assign y = data[3'(4-offset)*8 +: 32];
assign narrowed = data[2'(index) +: 4];
assign typed = data[index_t'(index) +: 4];
always_comb begin
written = data;
written[3'(4-offset)*8 +: 8] = 8'hff;
end
endmodule
"#)
(top Top)
(modify (set data 0x0123456789abcdef))
(for offset_value (range 0 4)
(modify (set offset offset_value))
(assert_eq y (& (>> 0x0123456789abcdef (* (- 4 offset_value) 8)) 0xffffffff))
(assert_eq written (| 0x0123456789abcdef (<< 0xff (* (- 4 offset_value) 8)))))
(for index_value (range 0 16)
(modify (set index index_value))
(assert_eq narrowed (& (>> 0x0123456789abcdef (& index_value 3)) 15))
(assert_eq typed (& (>> 0x0123456789abcdef (& index_value 7)) 15))))
2 changes: 2 additions & 0 deletions crates/celox-vpi/src/bin/celox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> {
.threads(arguments.execution.threads as usize)
.opt_level(arguments.opt_level)
.diagnostic_policy(arguments.design.diagnostics.clone())
.sv_timescale(arguments.design.timescale)
.signal_access(arguments.design.signal_access.clone());
let builder = arguments.design.apply_parameters(builder);
let max_steps = if arguments.execution.unlimited {
Expand Down Expand Up @@ -405,6 +406,7 @@ fn compile_native_design(design: &Design) -> Result<NativeProgramImage, String>
let builder = celox::Simulator::from_sv_sources(refs, &design.top)
.four_state(design.four_state.unwrap_or(false))
.diagnostic_policy(design.diagnostics.clone())
.sv_timescale(design.timescale)
.signal_access(design.signal_access.clone())
.opt_level(design.opt_level.unwrap_or(celox::OptLevel::O1));
let simulator = design
Expand Down
Loading
Loading