diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 0ca7bcdd834..366e7817e60 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -969,7 +969,10 @@ impl DriverScan<'_> { procedural::stmt_calls(stmt, &mut calls); }); } - while let Some((name, args)) = calls.pop() { + while let Some((callee, args)) = calls.pop() { + let sv::ir::Callee::Subroutine(name) = callee else { + continue; + }; let Some(subroutine) = self .subroutines .iter() @@ -2652,12 +2655,12 @@ fn expr_for_state_mode(expr: &sv::ir::Expr, four_state: bool) -> sv::ir::Expr { .collect(), }, sv::ir::Expr::Call { - name, + callee, args, arg_order, } => sv::ir::Expr::Call { arg_order: arg_order.clone(), - name: name.clone(), + callee: callee.clone(), args: args .iter() .map(|arg| arg.as_ref().map(|arg| expr_for_state_mode(arg, four_state))) @@ -4115,10 +4118,10 @@ fn lower_glue_parent_expr( context_signed, ), sv::ir::Expr::Call { - name, + callee: sv::ir::Callee::System(function), args, - arg_order, - } if sv::typecheck::bit_vector_function_return_type(name, args.len()).is_some() => { + .. + } if function.result_type().is_some() => { let mut operands = Vec::with_capacity(args.len()); let mut sources = HashSet::default(); let mut source_ids = Vec::new(); @@ -4143,7 +4146,7 @@ fn lower_glue_parent_expr( Some(( lower_bit_vector_function_slt( arena, - name, + *function, &operands, context_width, context_signed, @@ -4494,7 +4497,7 @@ fn permute_reversed_lvalue_rhs_slt( // IEEE 1800-2023 20.9: bit vector functions return known counts/predicates. fn lower_bit_vector_function_slt( arena: &mut SLTNodeArena, - name: &str, + function: sv::ir::SystemFunction, operands: &[NodeId], context_width: Option, context_signed: Option, @@ -4503,114 +4506,133 @@ fn lower_bit_vector_function_slt( let known = arena .alloc(SLTNode::Unary(UnaryOp::ToTwoState, inner)) .ok()?; - let (width, signed) = sv::typecheck::bit_vector_function_return_type(name, operands.len())?; - let result = if name == "$countbits" { - let controls = operands[1..] - .iter() - .map(|&expr| { - arena + use sv::ir::SystemFunction; + let (width, signed) = function.result_type()?; + let result = match function { + SystemFunction::Countbits => { + let controls = operands[1..] + .iter() + .map(|&expr| { + arena + .alloc(SLTNode::Slice { + expr, + access: BitAccess::new(0, 0), + }) + .ok() + }) + .collect::>>()?; + let operand_width = celox_slt::get_width(inner, arena); + let mut matches = Vec::with_capacity(operand_width); + for bit in (0..operand_width).rev() { + let selected = arena .alloc(SLTNode::Slice { - expr, - access: BitAccess::new(0, 0), + expr: inner, + access: BitAccess::new(bit, bit), }) - .ok() - }) - .collect::>>()?; - let operand_width = celox_slt::get_width(inner, arena); - let mut matches = Vec::with_capacity(operand_width); - for bit in (0..operand_width).rev() { - let selected = arena - .alloc(SLTNode::Slice { - expr: inner, - access: BitAccess::new(bit, bit), - }) - .ok()?; - let mut matched = None; - for &control in &controls { - // Case equality distinguishes all four states and returns a - // known bit. OR makes repeated controls count only once. - let equal = arena - .alloc(SLTNode::Binary(selected, BinaryOp::EqCase, control)) .ok()?; - matched = Some(match matched { - None => equal, - Some(previous) => arena - .alloc(SLTNode::Binary(previous, BinaryOp::Or, equal)) - .ok()?, - }); + let mut matched = None; + for &control in &controls { + // Case equality distinguishes all four states and returns a + // known bit. OR makes repeated controls count only once. + let equal = arena + .alloc(SLTNode::Binary(selected, BinaryOp::EqCase, control)) + .ok()?; + matched = Some(match matched { + None => equal, + Some(previous) => arena + .alloc(SLTNode::Binary(previous, BinaryOp::Or, equal)) + .ok()?, + }); + } + matches.push((matched?, 1)); } - matches.push((matched?, 1)); + let matching_bits = arena.alloc(SLTNode::Concat(matches)).ok()?; + let count = arena + .alloc(SLTNode::Unary(UnaryOp::PopCount, matching_bits)) + .ok()?; + coerce_node_width(arena, count, Some(32), false).ok()? } - let matching_bits = arena.alloc(SLTNode::Concat(matches)).ok()?; - let count = arena - .alloc(SLTNode::Unary(UnaryOp::PopCount, matching_bits)) - .ok()?; - coerce_node_width(arena, count, Some(32), false).ok()? - } else if name == "$clog2" { - // ceil(log2(x)): the bit length of x - 1, and 0 for x <= 1 - // (IEEE 1800-2023 20.8.1). - let operand_width = celox_slt::get_width(known, arena); - let constant = |arena: &mut SLTNodeArena, value: usize, width: usize| { - arena - .alloc(SLTNode::Constant( - BigUint::from(value), - BigUint::default(), - width, - false, - )) - .ok() - }; - let one = constant(arena, 1, operand_width)?; - let decremented = arena - .alloc(SLTNode::Binary(known, BinaryOp::Sub, one)) - .ok()?; - let zeros = arena - .alloc(SLTNode::Unary(UnaryOp::CountLeadingZeros, decremented)) - .ok()?; - let zeros = coerce_node_width(arena, zeros, Some(32), false).ok()?; - let total = constant(arena, operand_width, 32)?; - let bits = arena - .alloc(SLTNode::Binary(total, BinaryOp::Sub, zeros)) - .ok()?; - let small = arena - .alloc(SLTNode::Binary(known, BinaryOp::LeU, one)) - .ok()?; - let zero = constant(arena, 0, 32)?; - arena - .alloc(SLTNode::Mux { - cond: small, - then_expr: zero, - else_expr: bits, - }) - .ok()? - } else if name == "$isunknown" { - // Case inequality detects either X or Z, including unknown bits whose - // value plane is zero and would disappear during two-state conversion. - arena - .alloc(SLTNode::Binary(inner, BinaryOp::NeCase, known)) - .ok()? - } else { - let count = arena.alloc(SLTNode::Unary(UnaryOp::PopCount, known)).ok()?; - // PopCount has a minimal unsigned width; $countones returns signed int. - let count = coerce_node_width(arena, count, Some(32), false).ok()?; - if name == "$countones" { - count - } else { - let one = arena - .alloc(SLTNode::Constant( - BigUint::from(1u8), - BigUint::default(), - 32, - false, - )) + SystemFunction::Clog2 => { + // ceil(log2(x)): the bit length of x - 1, and 0 for x <= 1 + // (IEEE 1800-2023 20.8.1). + let operand_width = celox_slt::get_width(known, arena); + let constant = |arena: &mut SLTNodeArena, value: usize, width: usize| { + arena + .alloc(SLTNode::Constant( + BigUint::from(value), + BigUint::default(), + width, + false, + )) + .ok() + }; + let one = constant(arena, 1, operand_width)?; + let decremented = arena + .alloc(SLTNode::Binary(known, BinaryOp::Sub, one)) + .ok()?; + let zeros = arena + .alloc(SLTNode::Unary(UnaryOp::CountLeadingZeros, decremented)) + .ok()?; + let zeros = coerce_node_width(arena, zeros, Some(32), false).ok()?; + let total = constant(arena, operand_width, 32)?; + let bits = arena + .alloc(SLTNode::Binary(total, BinaryOp::Sub, zeros)) .ok()?; - let op = if name == "$onehot" { - BinaryOp::Eq + let small = arena + .alloc(SLTNode::Binary(known, BinaryOp::LeU, one)) + .ok()?; + let zero = constant(arena, 0, 32)?; + arena + .alloc(SLTNode::Mux { + cond: small, + then_expr: zero, + else_expr: bits, + }) + .ok()? + } + SystemFunction::Isunknown => { + // Case inequality detects either X or Z, including unknown bits whose + // value plane is zero and would disappear during two-state conversion. + arena + .alloc(SLTNode::Binary(inner, BinaryOp::NeCase, known)) + .ok()? + } + SystemFunction::Countones | SystemFunction::Onehot | SystemFunction::Onehot0 => { + let count = arena.alloc(SLTNode::Unary(UnaryOp::PopCount, known)).ok()?; + // PopCount has a minimal unsigned width; $countones returns signed int. + let count = coerce_node_width(arena, count, Some(32), false).ok()?; + if function == SystemFunction::Countones { + count } else { - BinaryOp::LeU - }; - arena.alloc(SLTNode::Binary(count, op, one)).ok()? + let one = arena + .alloc(SLTNode::Constant( + BigUint::from(1u8), + BigUint::default(), + 32, + false, + )) + .ok()?; + let op = if function == SystemFunction::Onehot { + BinaryOp::Eq + } else { + BinaryOp::LeU + }; + arena.alloc(SLTNode::Binary(count, op, one)).ok()? + } } + // `$urandom` needs process state, and the analyzer folds the other + // functions to constants. + SystemFunction::Urandom + | SystemFunction::Timeunit + | SystemFunction::Timeprecision + | SystemFunction::Isunbounded + | SystemFunction::Signed + | SystemFunction::Unsigned + | SystemFunction::Bits + | SystemFunction::Size + | SystemFunction::Dimensions + | SystemFunction::UnpackedDimensions + | SystemFunction::ArrayQuery(_) => return None, }; coerce_node_width( arena, @@ -5290,10 +5312,10 @@ fn lower_expr_with_context( context_signed, ), sv::ir::Expr::Call { - name, + callee: sv::ir::Callee::System(function), args, - arg_order, - } if sv::typecheck::bit_vector_function_return_type(name, args.len()).is_some() => { + .. + } if function.result_type().is_some() => { let mut operands = Vec::with_capacity(args.len()); let mut sources = HashSet::default(); @@ -5317,7 +5339,7 @@ fn lower_expr_with_context( Some(( lower_bit_vector_function_slt( arena, - name, + *function, &operands, context_width, context_signed, @@ -6469,10 +6491,7 @@ fn sv_glue_expr_is_signed( sv::ir::Expr::Resize { signed, .. } => *signed, sv::ir::Expr::Select { signed, .. } => *signed, sv::ir::Expr::Inside { .. } => false, - sv::ir::Expr::Call { name, args, .. } => { - sv::typecheck::bit_vector_function_return_type(name, args.len()) - .is_some_and(|(_, signed)| signed) - } + sv::ir::Expr::Call { callee, .. } => callee.result_type().is_some_and(|(_, signed)| signed), sv::ir::Expr::Concat(_) | sv::ir::Expr::RepeatConcat { .. } => false, sv::ir::Expr::Unary { op, expr } => { matches!( @@ -6531,10 +6550,7 @@ fn sv_expr_is_signed_with_parameters( sv::ir::Expr::Resize { signed, .. } => *signed, sv::ir::Expr::Select { signed, .. } => *signed, sv::ir::Expr::Inside { .. } => false, - sv::ir::Expr::Call { name, args, .. } => { - sv::typecheck::bit_vector_function_return_type(name, args.len()) - .is_some_and(|(_, signed)| signed) - } + sv::ir::Expr::Call { callee, .. } => callee.result_type().is_some_and(|(_, signed)| signed), sv::ir::Expr::Concat(_) | sv::ir::Expr::RepeatConcat { .. } => false, sv::ir::Expr::Unary { op, expr } => { matches!( @@ -6779,9 +6795,7 @@ fn sv_expr_natural_width( )?), ), sv::ir::Expr::Inside { .. } => Some(1), - sv::ir::Expr::Call { name, args, .. } => { - sv::typecheck::bit_vector_function_return_type(name, args.len()).map(|(width, _)| width) - } + sv::ir::Expr::Call { callee, .. } => callee.result_type().map(|(width, _)| width), } } diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 325df6e9087..bb8fdea1ce8 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -846,39 +846,39 @@ impl<'p, 'a> Comb<'p, 'a> { expr_from_const_expr(expr).ok_or_else(|| unsupported("operand in a select")) }; Ok(match expr { - ConstExpr::Function { name, .. } if name == "$urandom" => { - return Err(unsupported("$urandom called in combinational logic")); + ConstExpr::Function { + callee: callee @ sv::ir::Callee::System(_), + .. + } if self.m.is_callee(callee) => { + return Err(unsupported(format!( + "{callee} called in combinational logic" + ))); } - ConstExpr::Function { name, args, .. } - if self.m.subroutines.contains_key(name) - || self.m.dpi_imports.contains_key(name) => - { + ConstExpr::Function { callee, args, .. } if self.m.is_callee(callee) => { if let Some((_, result)) = calls.iter().find(|(call, _)| call == expr) { return Ok(result.clone()); } let mut lowered = Vec::with_capacity(args.len()); for arg in args { let arg = self.hoist_const(store, frames, arg, calls)?; - lowered.push( - expr_from_const_expr(&arg).ok_or_else(|| { - unsupported(format!("argument of `{name}` in a select")) - })?, - ); + lowered.push(expr_from_const_expr(&arg).ok_or_else(|| { + unsupported(format!("argument of `{callee}` in a select")) + })?); } let call = sv::ir::Expr::Call { arg_order: Vec::new(), - name: name.clone(), + callee: callee.clone(), args: lowered.into_iter().map(Some).collect(), }; let sv::ir::Expr::Ident(result) = self.hoist(store, frames, &call)? else { - return Err(unsupported(format!("call of `{name}` in a select"))); + return Err(unsupported(format!("call of `{callee}` in a select"))); }; let result = ConstExpr::Ident(result); calls.push((expr.clone(), result.clone())); result } - ConstExpr::Function { name, args, site } => ConstExpr::Function { - name: name.clone(), + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee: callee.clone(), args: args .iter() .map(|arg| self.hoist_const(store, frames, arg, calls)) @@ -1095,8 +1095,8 @@ impl<'p, 'a> Comb<'p, 'a> { expr: Box::new(self.freeze_const(store, frames, expr, copies)?), bit: Box::new(self.freeze_const(store, frames, bit, copies)?), }, - ConstExpr::Function { name, args, site } => ConstExpr::Function { - name: name.clone(), + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee: callee.clone(), args: args .iter() .map(|arg| self.freeze_const(store, frames, arg, copies)) @@ -1150,16 +1150,24 @@ impl<'p, 'a> Comb<'p, 'a> { return Ok(expr.clone()); } Ok(match expr { - Expr::Call { name, .. } if name == "$urandom" => { - return Err(unsupported("$urandom called in combinational logic")); + Expr::Call { + callee: callee @ sv::ir::Callee::System(_), + .. + } if self.m.is_callee(callee) => { + return Err(unsupported(format!( + "{callee} called in combinational logic" + ))); } - Expr::Call { name, .. } if self.m.dpi_imports.contains_key(name) => { + Expr::Call { + callee: sv::ir::Callee::Subroutine(name), + .. + } if self.m.dpi_imports.contains_key(name) => { return Err(unsupported(format!( "DPI-C function `{name}` called in combinational logic" ))); } Expr::Call { - name, + callee: sv::ir::Callee::Subroutine(name), args, arg_order, } if self.m.subroutines.contains_key(name) => { @@ -1186,12 +1194,12 @@ impl<'p, 'a> Comb<'p, 'a> { Expr::Ident(temp_name) } Expr::Call { - name, + callee, args, arg_order, } => Expr::Call { arg_order: arg_order.clone(), - name: name.clone(), + callee: callee.clone(), args: args .iter() .map(|arg| { @@ -1901,17 +1909,18 @@ impl<'p, 'a> Comb<'p, 'a> { self.eval(&mut store, frames, expr, None)?; Ok(store) } - sv::ir::Stmt::SystemTask { name, args } - if name == "$readmemh" || name == "$readmemb" => - { - self.readmem(&mut store, frames, name, args)?; + sv::ir::Stmt::SystemTask { + task: sv::ir::SystemTask::Readmem(format), + args, + } => { + self.readmem(&mut store, frames, *format, args)?; Ok(store) } - sv::ir::Stmt::SystemTask { name, .. } if self.initial => Err(unsupported(format!( - "system task `{name}` inside an initial block" + sv::ir::Stmt::SystemTask { task, .. } if self.initial => Err(unsupported(format!( + "system task `{task}` inside an initial block" ))), - sv::ir::Stmt::SystemTask { name, args } => { - self.system_task(&mut store, frames, name, args)?; + sv::ir::Stmt::SystemTask { task, args } => { + self.system_task(&mut store, frames, *task, args)?; Ok(store) } } @@ -3010,9 +3019,10 @@ impl<'p, 'a> Comb<'p, 'a> { &mut self, store: &mut Store, frames: &[Frame], - name: &str, + format: sv::ir::MemoryFormat, args: &[sv::ir::SystemTaskArg], ) -> Result<(), sv::AnalyzerError> { + let name = sv::ir::SystemTask::Readmem(format); let mut addresses = [None, None]; for (slot, arg) in addresses.iter_mut().zip(args.iter().skip(2)) { let sv::ir::SystemTaskArg::Expr(expr) = arg else { @@ -3037,7 +3047,7 @@ impl<'p, 'a> Comb<'p, 'a> { if self.path_condition()?.is_some() { return Err(unsupported(format!("`{name}` under a run-time condition"))); } - let (id, words) = self.m.readmem(name, args, addresses[0], addresses[1])?; + let (id, words) = self.m.readmem(format, args, addresses[0], addresses[1])?; for word in words { let width = word.access.msb - word.access.lsb + 1; let node = self.alloc(SLTNode::Constant(word.value, word.mask, width, false))?; @@ -3090,16 +3100,16 @@ impl<'p, 'a> Comb<'p, 'a> { &mut self, store: &mut Store, frames: &[Frame], - name: &str, + task: sv::ir::SystemTask, args: &[sv::ir::SystemTaskArg], ) -> Result<(), sv::AnalyzerError> { let kind = - system_task_kind(name).ok_or_else(|| unsupported(format!("system task `{name}`")))?; + system_task_kind(task).ok_or_else(|| unsupported(format!("system task `{task}`")))?; let observer_store = store.fork(); let mut observed = Sources::default(); let assertion = if matches!(kind, SystemTaskKind::Assertion(_)) { let Some(sv::ir::SystemTaskArg::Expr(condition)) = args.first() else { - return Err(unsupported(format!("condition of `{name}`"))); + return Err(unsupported(format!("condition of `{task}`"))); }; let (node, sources) = self.eval(store, frames, condition, None)?; observed.extend(sources); @@ -3134,7 +3144,7 @@ impl<'p, 'a> Comb<'p, 'a> { slt_constant(self.arena, value, width, false)? } sv::ir::SystemTaskArg::Empty => { - return Err(unsupported(format!("empty argument of `{name}`"))); + return Err(unsupported(format!("empty argument of `{task}`"))); } }; arg_widths.push(self.width(node)); @@ -3679,8 +3689,8 @@ fn substitute_literals( expr: Box::new(constant(expr, literals)), bit: Box::new(constant(bit, literals)), }, - ConstExpr::Function { name, args, site } => ConstExpr::Function { - name: name.clone(), + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee: callee.clone(), site: *site, args: args.iter().map(|arg| constant(arg, literals)).collect(), }, @@ -3798,12 +3808,12 @@ fn substitute_literals( else_expr: Box::new(go(else_expr)), }, Expr::Call { - name, + callee, args, arg_order, } => Expr::Call { arg_order: arg_order.clone(), - name: name.clone(), + callee: callee.clone(), args: args.iter().map(|arg| arg.as_ref().map(go)).collect(), }, Expr::Inside { expr, items } => Expr::Inside { diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 8a88829027e..66d33279f6b 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -194,8 +194,8 @@ impl<'p, 'a> Ff<'p, 'a> { writes.extend(parts.iter().map(|part| (part.clone(), !nonblocking))); } // `$readmemh` writes its destination immediately. - sv::ir::Stmt::SystemTask { name, args } => { - if let Some(destination) = readmem_destination(name, args) { + sv::ir::Stmt::SystemTask { task, args } => { + if let Some(destination) = readmem_destination(*task, args) { writes.push((sv::ir::LValue::Ident(destination.to_string()), true)); } } @@ -211,13 +211,19 @@ impl<'p, 'a> Ff<'p, 'a> { for stmt in stmts { stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); } - while let Some((name, args)) = calls.pop() { - if name == "$urandom" && self.random.is_none() { - let (id, name) = self.m.temp("urandom_state", 33, false, false); - self.working.insert(id); - self.targets.push((id, BitAccess::new(0, 32))); - self.random = Some((id, name)); - } + while let Some((callee, args)) = calls.pop() { + let name = match callee { + sv::ir::Callee::System(function) => { + if function == sv::ir::SystemFunction::Urandom && self.random.is_none() { + let (id, name) = self.m.temp("urandom_state", 33, false, false); + self.working.insert(id); + self.targets.push((id, BitAccess::new(0, 32))); + self.random = Some((id, name)); + } + continue; + } + sv::ir::Callee::Subroutine(name) => name, + }; let Some(subroutine) = self.m.subroutine(&name).cloned() else { continue; }; @@ -502,33 +508,31 @@ impl<'p, 'a> Ff<'p, 'a> { expr_from_const_expr(expr).ok_or_else(|| unsupported("operand in a select")) }; Ok(match expr { - ConstExpr::Function { name, args, .. } if self.m.is_callee(name) => { + ConstExpr::Function { callee, args, .. } if self.m.is_callee(callee) => { if let Some((_, result)) = calls.iter().find(|(call, _)| call == expr) { return Ok(result.clone()); } let mut lowered = Vec::with_capacity(args.len()); for arg in args { let arg = self.hoist_const(arg, calls)?; - lowered.push( - expr_from_const_expr(&arg).ok_or_else(|| { - unsupported(format!("argument of `{name}` in a select")) - })?, - ); + lowered.push(expr_from_const_expr(&arg).ok_or_else(|| { + unsupported(format!("argument of `{callee}` in a select")) + })?); } let call = sv::ir::Expr::Call { arg_order: Vec::new(), - name: name.clone(), + callee: callee.clone(), args: lowered.into_iter().map(Some).collect(), }; let sv::ir::Expr::Ident(result) = self.hoist(&call)? else { - return Err(unsupported(format!("call of `{name}` in a select"))); + return Err(unsupported(format!("call of `{callee}` in a select"))); }; let result = ConstExpr::Ident(result); calls.push((expr.clone(), result.clone())); result } - ConstExpr::Function { name, args, site } => ConstExpr::Function { - name: name.clone(), + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee: callee.clone(), args: args .iter() .map(|arg| self.hoist_const(arg, calls)) @@ -734,8 +738,8 @@ impl<'p, 'a> Ff<'p, 'a> { expr: Box::new(self.freeze_const(expr, copies)?), bit: Box::new(self.freeze_const(bit, copies)?), }, - ConstExpr::Function { name, args, site } => ConstExpr::Function { - name: name.clone(), + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee: callee.clone(), args: args .iter() .map(|arg| self.freeze_const(arg, copies)) @@ -782,9 +786,13 @@ impl<'p, 'a> Ff<'p, 'a> { return Ok(expr.clone()); } Ok(match expr { - Expr::Call { name, args, .. } if name == "$urandom" => self.urandom(args)?, Expr::Call { - name, + callee: sv::ir::Callee::System(sv::ir::SystemFunction::Urandom), + args, + .. + } => self.urandom(args)?, + Expr::Call { + callee: sv::ir::Callee::Subroutine(name), args, arg_order, } if self.m.dpi_imports.contains_key(name) => { @@ -808,7 +816,7 @@ impl<'p, 'a> Ff<'p, 'a> { Expr::Ident(temp_name) } Expr::Call { - name, + callee: sv::ir::Callee::Subroutine(name), args, arg_order, } if self.m.subroutines.contains_key(name) => { @@ -865,12 +873,12 @@ impl<'p, 'a> Ff<'p, 'a> { } } Expr::Call { - name, + callee, args, arg_order, } => Expr::Call { arg_order: arg_order.clone(), - name: name.clone(), + callee: callee.clone(), args: args .iter() .map(|arg| arg.as_ref().map(|arg| self.hoist(arg)).transpose()) @@ -1707,7 +1715,7 @@ impl<'p, 'a> Ff<'p, 'a> { self.eval(expr, None)?; Ok(true) } - sv::ir::Stmt::SystemTask { name, args } => self.system_task(name, args), + sv::ir::Stmt::SystemTask { task, args } => self.system_task(*task, args), } } @@ -1715,10 +1723,10 @@ impl<'p, 'a> Ff<'p, 'a> { /// simulation with an error. fn system_task( &mut self, - name: &str, + task: sv::ir::SystemTask, args: &[sv::ir::SystemTaskArg], ) -> Result { - if readmem_destination(name, args).is_some() { + if let sv::ir::SystemTask::Readmem(format) = task { let mut addresses = [None, None]; for (slot, arg) in addresses.iter_mut().zip(args.iter().skip(2)) { let sv::ir::SystemTaskArg::Expr(expr) = arg else { @@ -1727,7 +1735,7 @@ impl<'p, 'a> Ff<'p, 'a> { let signed = self.expr_signed(expr); let (value, width) = self .eval_const(expr)? - .ok_or_else(|| unsupported(format!("`{name}` address that is not constant")))?; + .ok_or_else(|| unsupported(format!("`{task}` address that is not constant")))?; let value = num_bigint::BigInt::from(value); let value = if signed && width > 0 && value.bit(width as u64 - 1) { value - (num_bigint::BigInt::from(1u8) << width) @@ -1737,10 +1745,10 @@ impl<'p, 'a> Ff<'p, 'a> { *slot = Some( value .to_i128() - .ok_or_else(|| unsupported(format!("`{name}` address")))?, + .ok_or_else(|| unsupported(format!("`{task}` address")))?, ); } - let (id, words) = self.m.readmem(name, args, addresses[0], addresses[1])?; + let (id, words) = self.m.readmem(format, args, addresses[0], addresses[1])?; for word in words { let width = word.access.msb - word.access.lsb + 1; let reg = if word.mask.is_zero() { @@ -1758,7 +1766,7 @@ impl<'p, 'a> Ff<'p, 'a> { return Ok(true); } let kind = - system_task_kind(name).ok_or_else(|| unsupported(format!("system task `{name}`")))?; + system_task_kind(task).ok_or_else(|| unsupported(format!("system task `{task}`")))?; // A process ends the simulation itself; the rest of its body does not // run. if matches!(kind, SystemTaskKind::Finish) && self.kernel.is_some() { @@ -1767,7 +1775,7 @@ impl<'p, 'a> Ff<'p, 'a> { } let assertion = if matches!(kind, SystemTaskKind::Assertion(_)) { let Some(sv::ir::SystemTaskArg::Expr(condition)) = args.first() else { - return Err(unsupported(format!("condition of `{name}`"))); + return Err(unsupported(format!("condition of `{task}`"))); }; Some(self.eval_truth(condition)?) } else { @@ -1802,7 +1810,7 @@ impl<'p, 'a> Ff<'p, 'a> { regs.push(reg); } sv::ir::SystemTaskArg::Empty => { - return Err(unsupported(format!("empty argument of `{name}`"))); + return Err(unsupported(format!("empty argument of `{task}`"))); } } } @@ -1846,7 +1854,7 @@ impl<'p, 'a> Ff<'p, 'a> { if kind.is_fatal() { let code = self .m - .runtime_error(template.unwrap_or_else(|| "$fatal".to_string())); + .runtime_error(template.unwrap_or_else(|| sv::ir::SystemTask::Fatal.to_string())); self.b.seal_block(SIRTerminator::Error(code)); if resume.is_none() { return Ok(false); @@ -2742,8 +2750,8 @@ fn substitute_overlay_const( expr: Box::new(go(expr)), bit: Box::new(go(bit)), }, - ConstExpr::Function { name, args, site } => ConstExpr::Function { - name: name.clone(), + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee: callee.clone(), site: *site, args: args.iter().map(go).collect(), }, @@ -2833,12 +2841,12 @@ fn substitute_overlay( else_expr: Box::new(go(else_expr)), }, Expr::Call { - name, + callee, args, arg_order, } => Expr::Call { arg_order: arg_order.clone(), - name: name.clone(), + callee: callee.clone(), args: args.iter().map(|arg| arg.as_ref().map(go)).collect(), }, Expr::Inside { expr, items } => Expr::Inside { diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 43f1660a05b..f8178cc7e65 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -151,10 +151,16 @@ impl<'a> ProcModule<'a> { stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); } let mut visited = HashSet::default(); - while let Some((name, args)) = calls.pop() { - if name == "$urandom" { - return true; - } + while let Some((callee, args)) = calls.pop() { + let name = match callee { + sv::ir::Callee::System(function) => { + if function == sv::ir::SystemFunction::Urandom { + return true; + } + continue; + } + sv::ir::Callee::Subroutine(name) => name, + }; if let Some(subroutine) = self.subroutine(&name) { default_calls(subroutine, &args, &mut calls); if visited.insert(name) { @@ -184,9 +190,11 @@ impl<'a> ProcModule<'a> { let mut exprs = Vec::new(); use sv::ir::Expr; match expr { - Expr::Call { name, args, .. } => { + Expr::Call { callee, args, .. } => { exprs.extend(args.iter().flatten().cloned()); - if let Some(subroutine) = m.subroutine(name) { + if let sv::ir::Callee::Subroutine(name) = callee + && let Some(subroutine) = m.subroutine(name) + { for (i, param) in subroutine.params.iter().enumerate() { if args.get(i).and_then(Option::as_ref).is_none() { exprs.extend(param.default.clone()); @@ -298,7 +306,7 @@ impl<'a> ProcModule<'a> { } = stmt { exprs.push(sv::ir::Expr::Call { - name: name.clone(), + callee: sv::ir::Callee::Subroutine(name.clone()), args: args.clone(), arg_order: arg_order.clone(), }); @@ -325,12 +333,13 @@ impl<'a> ProcModule<'a> { /// read when the design is compiled. pub fn readmem( &self, - name: &str, + format: sv::ir::MemoryFormat, args: &[sv::ir::SystemTaskArg], start: Option, finish: Option, ) -> Result<(SourceVarId, Vec), sv::AnalyzerError> { - let radix = if name == "$readmemb" { 2 } else { 16 }; + let name = sv::ir::SystemTask::Readmem(format).name(); + let radix = format.base(); let Some(sv::ir::SystemTaskArg::Str(filename)) = args.first() else { return Err(unsupported(format!( "`{name}` with a file name that is not a string literal" @@ -518,19 +527,24 @@ impl<'a> ProcModule<'a> { self.subroutines.get(name) } - pub fn is_callee(&self, name: &str) -> bool { - name == "$urandom" - || self.subroutines.contains_key(name) - || self.dpi_imports.contains_key(name) + /// Whether a call of `callee` has effects: a user subroutine or a DPI + /// import, or an effectful system function such as `$urandom`. + pub fn is_callee(&self, callee: &sv::ir::Callee) -> bool { + match callee { + sv::ir::Callee::System(function) => function.is_effectful(), + sv::ir::Callee::Subroutine(name) => { + self.subroutines.contains_key(name) || self.dpi_imports.contains_key(name) + } + } } /// Whether an expression contains a call whose evaluation has effects. pub fn lvalue_calls(&self, lvalue: &sv::ir::LValue) -> bool { - lvalue_calls(lvalue, &|name| self.is_callee(name)) + lvalue_calls(lvalue, &|callee| self.is_callee(callee)) } pub fn const_calls(&self, expr: &sv::ir::ConstExpr) -> bool { - const_calls(expr, &|name| self.is_callee(name)) + const_calls(expr, &|callee| self.is_callee(callee)) } /// The largest subexpressions of `expr` that call a subroutine and also @@ -541,12 +555,12 @@ impl<'a> ProcModule<'a> { other: &sv::ir::ConstExpr, ) -> Vec<&'e sv::ir::ConstExpr> { let mut shared = Vec::new(); - shared_calls(expr, other, &|name| self.is_callee(name), &mut shared); + shared_calls(expr, other, &|callee| self.is_callee(callee), &mut shared); shared } pub fn calls(&self, expr: &sv::ir::Expr) -> bool { - expr_calls(expr, &|name| self.is_callee(name)) + expr_calls(expr, &|callee| self.is_callee(callee)) } /// The local index of the extern function `import` links to. Imports @@ -624,13 +638,19 @@ impl<'a> ProcModule<'a> { use sv::ir::Expr; let go = |expr: &Expr| self.typed_calls(expr); match expr { - Expr::Call { name, .. } if self.dpi_imports.contains_key(name) => { + Expr::Call { + callee: sv::ir::Callee::Subroutine(name), + .. + } if self.dpi_imports.contains_key(name) => { let (width, signed) = self.dpi_imports[name] .return_type() .map_or((1, false), |r#type| (r#type.width(), r#type.is_signed())); Expr::Literal(typed_literal(&BigUint::zero(), width, signed)) } - Expr::Call { name, .. } if self.subroutines.contains_key(name) => { + Expr::Call { + callee: sv::ir::Callee::Subroutine(name), + .. + } if self.subroutines.contains_key(name) => { let (width, signed) = self .subroutines .get(name) @@ -684,12 +704,12 @@ impl<'a> ProcModule<'a> { else_expr: Box::new(go(else_expr)), }, Expr::Call { - name, + callee, args, arg_order, } => Expr::Call { arg_order: arg_order.clone(), - name: name.clone(), + callee: callee.clone(), args: args.iter().map(|arg| arg.as_ref().map(go)).collect(), }, Expr::Inside { expr, items } => Expr::Inside { @@ -712,13 +732,12 @@ impl<'a> ProcModule<'a> { } } -/// How a system task statement reports. /// The variable `$readmemh`/`$readmemb` writes, if it is a task of these. -pub(super) fn readmem_destination<'e>( - name: &str, - args: &'e [sv::ir::SystemTaskArg], -) -> Option<&'e str> { - if name != "$readmemh" && name != "$readmemb" { +pub(super) fn readmem_destination( + task: sv::ir::SystemTask, + args: &[sv::ir::SystemTaskArg], +) -> Option<&str> { + if !matches!(task, sv::ir::SystemTask::Readmem(_)) { return None; } match args.get(1)? { @@ -731,6 +750,7 @@ pub(super) fn readmem_destination<'e>( } } +/// How a system task statement reports. pub(super) enum SystemTaskKind { /// `$display` and `$write`, with the radix of their `b`, `o` and `h` /// variants (`d` otherwise). @@ -755,30 +775,25 @@ impl SystemTaskKind { } } -pub(super) fn system_task_kind(name: &str) -> Option { - Some(match name { - "$display" | "$displayb" | "$displayh" | "$displayo" => { - SystemTaskKind::Print(RuntimeEventKind::Display, print_radix(name)) - } - "$write" | "$writeb" | "$writeh" | "$writeo" => { - SystemTaskKind::Print(RuntimeEventKind::Write, print_radix(name)) - } - "$finish" => SystemTaskKind::Finish, - "$error" | "$warning" | "$info" => SystemTaskKind::Message, - "$fatal" => SystemTaskKind::Fatal, - "$assert" => SystemTaskKind::Assertion(RuntimeEventKind::AssertFatal), - "$assert_continue" => SystemTaskKind::Assertion(RuntimeEventKind::AssertContinue), - _ => return None, +/// How a task reports, for the tasks that report: `$readmemh`/`$readmemb` +/// load memory instead, and the analyzer rewrites `$printtimescale` into a +/// `$display`. +pub(super) fn system_task_kind(task: sv::ir::SystemTask) -> Option { + use sv::ir::SystemTask; + Some(match task { + SystemTask::Display(radix) => { + SystemTaskKind::Print(RuntimeEventKind::Display, radix.letter()) + } + SystemTask::Write(radix) => SystemTaskKind::Print(RuntimeEventKind::Write, radix.letter()), + SystemTask::Finish => SystemTaskKind::Finish, + SystemTask::Severity(_) => SystemTaskKind::Message, + SystemTask::Fatal => SystemTaskKind::Fatal, + SystemTask::Assert => SystemTaskKind::Assertion(RuntimeEventKind::AssertFatal), + SystemTask::AssertContinue => SystemTaskKind::Assertion(RuntimeEventKind::AssertContinue), + SystemTask::Readmem(_) | SystemTask::Printtimescale => return None, }) } -fn print_radix(name: &str) -> char { - match name.as_bytes().last() { - Some(radix @ (b'b' | b'o' | b'h')) => char::from(*radix), - _ => 'd', - } -} - /// How many arguments the conversions of `template` consume, as the runtime /// renders them. fn template_arguments(template: &str) -> usize { @@ -1792,7 +1807,10 @@ pub(super) fn expr_idents(expr: &sv::ir::Expr, names: &mut HashSet) { /// Whether a constant-expression operand, such as a run-time select index, /// calls a subroutine. -pub(super) fn const_calls(expr: &sv::ir::ConstExpr, is_callee: &dyn Fn(&str) -> bool) -> bool { +pub(super) fn const_calls( + expr: &sv::ir::ConstExpr, + is_callee: &dyn Fn(&sv::ir::Callee) -> bool, +) -> bool { use sv::ir::ConstExpr; match expr { ConstExpr::Literal(_) | ConstExpr::Ident(_) => false, @@ -1804,8 +1822,8 @@ pub(super) fn const_calls(expr: &sv::ir::ConstExpr, is_callee: &dyn Fn(&str) -> ConstExpr::Select { expr, bit } => { const_calls(expr, is_callee) || const_calls(bit, is_callee) } - ConstExpr::Function { name, args, .. } => { - is_callee(name) || args.iter().any(|arg| const_calls(arg, is_callee)) + ConstExpr::Function { callee, args, .. } => { + is_callee(callee) || args.iter().any(|arg| const_calls(arg, is_callee)) } ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => { const_calls(expr, is_callee) @@ -1861,7 +1879,7 @@ fn const_contains(expr: &sv::ir::ConstExpr, part: &sv::ir::ConstExpr) -> bool { fn shared_calls<'e>( expr: &'e sv::ir::ConstExpr, other: &sv::ir::ConstExpr, - is_callee: &dyn Fn(&str) -> bool, + is_callee: &dyn Fn(&sv::ir::Callee) -> bool, shared: &mut Vec<&'e sv::ir::ConstExpr>, ) { use sv::ir::ConstExpr; @@ -1906,7 +1924,10 @@ fn shared_calls<'e>( } /// Whether the select positions of an assignment target call a subroutine. -pub(super) fn lvalue_calls(lvalue: &sv::ir::LValue, is_callee: &dyn Fn(&str) -> bool) -> bool { +pub(super) fn lvalue_calls( + lvalue: &sv::ir::LValue, + is_callee: &dyn Fn(&sv::ir::Callee) -> bool, +) -> bool { match lvalue { sv::ir::LValue::Ident(_) => false, sv::ir::LValue::Select { msb, lsb, .. } => { @@ -1916,7 +1937,7 @@ pub(super) fn lvalue_calls(lvalue: &sv::ir::LValue, is_callee: &dyn Fn(&str) -> } /// Whether an expression calls a user subroutine. -pub(super) fn expr_calls(expr: &sv::ir::Expr, is_callee: &dyn Fn(&str) -> bool) -> bool { +pub(super) fn expr_calls(expr: &sv::ir::Expr, is_callee: &dyn Fn(&sv::ir::Callee) -> bool) -> bool { match expr { sv::ir::Expr::Ident(_) | sv::ir::Expr::Literal(_) => false, sv::ir::Expr::Select { expr, msb, lsb, .. } => { @@ -1942,8 +1963,8 @@ pub(super) fn expr_calls(expr: &sv::ir::Expr, is_callee: &dyn Fn(&str) -> bool) || expr_calls(then_expr, is_callee) || expr_calls(else_expr, is_callee) } - sv::ir::Expr::Call { name, args, .. } => { - is_callee(name) || args.iter().flatten().any(|arg| expr_calls(arg, is_callee)) + sv::ir::Expr::Call { callee, args, .. } => { + is_callee(callee) || args.iter().flatten().any(|arg| expr_calls(arg, is_callee)) } sv::ir::Expr::Inside { expr, items } => { expr_calls(expr, is_callee) @@ -2032,15 +2053,14 @@ pub(super) fn stmt_may_jump(stmt: &sv::ir::Stmt, in_loop: bool) -> bool { } } -/// The user subroutine calls an expression makes, outermost first, with their -/// arguments. +/// The calls an expression makes, outermost first, with their arguments. pub(super) fn collect_calls( expr: &sv::ir::Expr, - calls: &mut Vec<(String, Vec>)>, + calls: &mut Vec<(sv::ir::Callee, Vec>)>, ) { match expr { - sv::ir::Expr::Call { name, args, .. } => { - calls.push((name.clone(), args.clone())); + sv::ir::Expr::Call { callee, args, .. } => { + calls.push((callee.clone(), args.clone())); for arg in args.iter().flatten() { collect_calls(arg, calls); } @@ -2087,13 +2107,13 @@ pub(super) fn collect_calls( /// position. fn collect_const_calls( expr: &sv::ir::ConstExpr, - calls: &mut Vec<(String, Vec>)>, + calls: &mut Vec<(sv::ir::Callee, Vec>)>, ) { use sv::ir::ConstExpr; match expr { - ConstExpr::Function { name, args, .. } => { + ConstExpr::Function { callee, args, .. } => { calls.push(( - name.clone(), + callee.clone(), args.iter().map(expr_from_const_expr).collect(), )); args.iter().for_each(|arg| collect_const_calls(arg, calls)); @@ -2132,7 +2152,7 @@ fn collect_const_calls( /// The calls in the select positions of an assignment target. fn lvalue_position_calls( lvalue: &sv::ir::LValue, - calls: &mut Vec<(String, Vec>)>, + calls: &mut Vec<(sv::ir::Callee, Vec>)>, ) { if let sv::ir::LValue::Select { msb, lsb, .. } = lvalue { collect_const_calls(msb, calls); @@ -2142,12 +2162,12 @@ fn lvalue_position_calls( pub(super) fn stmt_calls( stmt: &sv::ir::Stmt, - calls: &mut Vec<(String, Vec>)>, + calls: &mut Vec<(sv::ir::Callee, Vec>)>, ) { let mut exprs: Vec<&sv::ir::Expr> = Vec::new(); match stmt { sv::ir::Stmt::Call { name, args, .. } => { - calls.push((name.clone(), args.clone())); + calls.push((sv::ir::Callee::Subroutine(name.clone()), args.clone())); exprs.extend(args.iter().flatten()); } sv::ir::Stmt::Assign { lhs, rhs, .. } => { @@ -2208,7 +2228,7 @@ pub(super) fn stmt_calls( pub(super) fn default_calls( subroutine: &sv::ir::Subroutine, args: &[Option], - calls: &mut Vec<(String, Vec>)>, + calls: &mut Vec<(sv::ir::Callee, Vec>)>, ) { for (position, param) in subroutine.params.iter().enumerate() { if matches!(args.get(position), None | Some(None)) diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 539e4975a46..b0ae6dcc941 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -19,6 +19,7 @@ use std::{ use sv_parser::{Locate, RefNode, SyntaxTree, unwrap_node}; +pub use crate::system_functions::{ArrayQuery, Callee, SystemFunction, SystemTask}; use crate::{AnalyzerError, system_functions, typecheck}; mod array_compatibility; @@ -106,7 +107,8 @@ use dimensions::{ variable_size_marker, variable_unpacked_dimensions_marker, }; use expressions::{ - expr_from_expression, expr_from_expression_for_lvalue, expr_from_expression_with_types, + called_system_function, called_system_task, expr_from_expression, + expr_from_expression_for_lvalue, expr_from_expression_with_types, expr_from_function_subroutine_call, expr_from_primary, expr_from_subroutine_call, expr_from_tf_call, expression_is_grouped, guard_zero_divisions, system_tf_call_parts, }; @@ -1788,7 +1790,7 @@ pub enum ConstExpr { signed: bool, }, Function { - name: String, + callee: Callee, args: Vec, /// Tells a user subroutine call apart from a call written alike: a /// select repeats its index in its bounds and range checks, and the @@ -1826,10 +1828,11 @@ pub(crate) fn with_call_sites(f: impl FnOnce() -> T) -> T { impl ConstExpr { /// Effectful calls get distinct sites; analyzer-created copies retain them. - fn call(name: String, args: Vec) -> Self { - let site = (name == "$urandom" || !system_functions::is_system_name(&name)) + fn call(callee: Callee, args: Vec) -> Self { + let site = callee + .is_effectful() .then(|| NEXT_CALL_SITE.with(|next| next.replace(next.get() + 1))); - ConstExpr::Function { name, args, site } + ConstExpr::Function { callee, args, site } } } @@ -2234,7 +2237,7 @@ pub enum Expr { else_expr: Box, }, Call { - name: String, + callee: Callee, /// Missing actuals retain their formal slots for declaration-scope defaults. args: Vec>, /// Formal positions in source evaluation/copy-out order; empty means positional. diff --git a/crates/celox-sv-analyzer/src/ast/case.rs b/crates/celox-sv-analyzer/src/ast/case.rs index 1b319eeb356..ec204b7ffe5 100644 --- a/crates/celox-sv-analyzer/src/ast/case.rs +++ b/crates/celox-sv-analyzer/src/ast/case.rs @@ -52,13 +52,17 @@ pub(super) fn expr_is_two_state(expr: &Expr, packed_dimensions: &PackedDimension || (expr_is_two_state(condition, packed_dimensions) && expr_is_two_state(else_expr, packed_dimensions))) } - Expr::Call { name, args, .. } => { - typecheck::bit_vector_function_return_type(name, args.len()).is_some() - || packed_dimensions - .function_return_types - .get(name) - .is_some_and(|metadata| metadata.is_2state) - } + Expr::Call { + callee: Callee::System(function), + .. + } => function.result_type().is_some(), + Expr::Call { + callee: Callee::Subroutine(name), + .. + } => packed_dimensions + .function_return_types + .get(name) + .is_some_and(|metadata| metadata.is_2state), } } diff --git a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs index 139829a65b9..c9e3ad4bca9 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs @@ -86,16 +86,17 @@ pub(super) fn expr_static_width( expr_static_width(then_expr, packed_dimensions)? .max(expr_static_width(else_expr, packed_dimensions)?), ), - Expr::Call { name, args, .. } => { - typecheck::bit_vector_function_return_type(name, args.len()) - .map(|(width, _)| width) - .or_else(|| { - packed_dimensions - .function_return_types - .get(name) - .and_then(|metadata| metadata.width) - }) - } + Expr::Call { + callee: Callee::System(function), + .. + } => function.result_type().map(|(width, _)| width), + Expr::Call { + callee: Callee::Subroutine(name), + .. + } => packed_dimensions + .function_return_types + .get(name) + .and_then(|metadata| metadata.width), } } diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index b50df6ef985..71898334e11 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -465,9 +465,9 @@ fn collect_module_constant_functions( } /// Fill defaults in the declaration's bound scope; runtime IR keeps its holes. -pub(super) fn resolved_arguments(name: &str, args: &[Option]) -> Option> { +pub(super) fn resolved_arguments(callee: &Callee, args: &[Option]) -> Option> { let functions = FUNCTIONS.with(|functions| functions.borrow().clone()); - let Some(function) = functions.get(name) else { + let Some(function) = callee.subroutine().and_then(|name| functions.get(name)) else { return args.iter().cloned().collect(); }; if args.len() > function.params.len() { @@ -512,7 +512,11 @@ pub(super) fn eval_expression_literal( expr: &Expr, constants: &HashMap, ) -> Option { - let Expr::Call { name, .. } = expr else { + let Expr::Call { + callee: Callee::Subroutine(name), + .. + } = expr + else { return None; }; let functions = FUNCTIONS.with(|functions| functions.borrow().clone()); @@ -752,9 +756,9 @@ impl Frame<'_> { self.lower(else_expr)? } } - Expr::Call { name, args, .. } => ConstExpr::Function { - name: name.clone(), - args: resolved_arguments(name, args)? + Expr::Call { callee, args, .. } => ConstExpr::Function { + callee: callee.clone(), + args: resolved_arguments(callee, args)? .iter() .map(|arg| self.lower(arg)) .collect::>()?, diff --git a/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs b/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs index a25a4ff5fd6..0fbe7a2fa2b 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs @@ -73,7 +73,7 @@ fn functions() -> ConstantFunctions { vec![Stmt::Return(Some(binary( Expr::Call { arg_order: Vec::new(), - name: "read".into(), + callee: Callee::Subroutine("read".into()), args: vec![], }, BinaryOp::Add, @@ -89,7 +89,7 @@ fn functions() -> ConstantFunctions { else_body: vec![Stmt::Return(Some(binary( Expr::Call { arg_order: Vec::new(), - name: "recursive".into(), + callee: Callee::Subroutine("recursive".into()), args: vec![Some(binary(ident("n"), BinaryOp::Sub, literal("1")))], }, BinaryOp::Add, @@ -331,7 +331,7 @@ fn literal_probes_do_not_execute_user_functions_and_recursion_is_not_repeated() let _installed = install(functions()); let env = environment(0); let expr = crate::ir::ConstExpr::Function { - name: "recursive".into(), + callee: Callee::Subroutine("recursive".into()), args: vec![crate::ir::ConstExpr::Literal("12".into())], site: None, }; diff --git a/crates/celox-sv-analyzer/src/ast/constant_folding.rs b/crates/celox-sv-analyzer/src/ast/constant_folding.rs index 5f81267ae03..5f09361486d 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_folding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_folding.rs @@ -211,12 +211,12 @@ pub(super) fn simplify_constant_mux_conditions( .collect(), }, Expr::Call { - name, + callee, args, arg_order, } => Expr::Call { arg_order: arg_order.clone(), - name, + callee, args: args .into_iter() .map(|arg| arg.map(|arg| simplify_constant_mux_conditions(arg, const_env))) @@ -382,8 +382,8 @@ fn constant_with_folded_selections_with_lookup( then_expr: Box::new(convert(then_expr)?), else_expr: Box::new(convert(else_expr)?), }), - Expr::Call { name, args, .. } => Some(ConstExpr::call( - name.clone(), + Expr::Call { callee, args, .. } => Some(ConstExpr::call( + callee.clone(), args.iter() .map(|arg| convert(arg.as_ref()?)) .collect::>>()?, diff --git a/crates/celox-sv-analyzer/src/ast/constant_folding/tests.rs b/crates/celox-sv-analyzer/src/ast/constant_folding/tests.rs index ae7881497f8..38e0efed0f8 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_folding/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_folding/tests.rs @@ -129,7 +129,7 @@ fn lazy_types_preserve_width_signedness_and_masks_across_expression_shapes() { ( Expr::Call { arg_order: Vec::new(), - name: "$countones".into(), + callee: Callee::System(SystemFunction::Countones), args: vec![Some(ident("A"))], }, 1, @@ -137,7 +137,7 @@ fn lazy_types_preserve_width_signedness_and_masks_across_expression_shapes() { ( Expr::Call { arg_order: Vec::new(), - name: "unresolved_function".into(), + callee: Callee::Subroutine("unresolved_function".into()), args: vec![Some(ident("B"))], }, 1, diff --git a/crates/celox-sv-analyzer/src/ast/constants.rs b/crates/celox-sv-analyzer/src/ast/constants.rs index cd1eb31c444..d6a5dceb978 100644 --- a/crates/celox-sv-analyzer/src/ast/constants.rs +++ b/crates/celox-sv-analyzer/src/ast/constants.rs @@ -394,7 +394,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( .collect(), }, Expr::Call { - name, + callee, args, arg_order, } => { @@ -410,7 +410,8 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( }) }) .collect(); - if matches!(name.as_str(), "$signed" | "$unsigned") + let function = callee.system(); + if let Some(function @ (SystemFunction::Signed | SystemFunction::Unsigned)) = function && let [Some(arg)] = args.as_slice() && let Some(constant) = expr_to_const(arg.clone()) && let Some(ty) = @@ -419,13 +420,13 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( Expr::Resize { expr: Box::new(arg.clone()), width: ty.width, - signed: name == "$signed", + signed: function == SystemFunction::Signed, } - } else if name == "$countbits" { + } else if function == Some(SystemFunction::Countbits) { // Resolve constant calls before SLT lowering while retaining X/Z masks. fold_const_integral_expr_preserving_mask( Expr::Call { - name, + callee, args, arg_order, }, @@ -433,7 +434,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( ) } else { Expr::Call { - name, + callee, args, arg_order, } @@ -534,8 +535,8 @@ fn substitute_const_expr_constants_impl( preserve_enum_types, )), }, - ConstExpr::Function { name, args, site } => ConstExpr::Function { - name, + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee, site, args: args .into_iter() @@ -821,7 +822,7 @@ pub(super) fn expr_to_const(expr: Expr) -> Option { else_expr: Box::new(expr_to_const(*else_expr)?), }), Expr::Call { - name, + callee, args, arg_order, } => { @@ -829,7 +830,7 @@ pub(super) fn expr_to_const(expr: Expr) -> Option { return None; } Some(ConstExpr::call( - name, + callee, args.into_iter() .map(|arg| expr_to_const(arg?)) .collect::>()?, @@ -893,7 +894,7 @@ pub(super) fn expr_to_index_const(expr: Expr, dimensions: &PackedDimensions) -> else_expr: Box::new(expr_to_index_const(*else_expr, dimensions)?), }), Expr::Call { - name, + callee, args, arg_order, } => { @@ -903,7 +904,7 @@ pub(super) fn expr_to_index_const(expr: Expr, dimensions: &PackedDimensions) -> return None; } Some(ConstExpr::call( - name, + callee, args.into_iter() .map(|arg| expr_to_index_const(arg?, dimensions)) .collect::>()?, @@ -1301,13 +1302,9 @@ pub(super) fn const_expr_from_ref_node_with_env( sv_parser::ConstantPrimary::ConstantFunctionCall(call) => { if let sv_parser::SubroutineCall::SystemTfCall(system_call) = &call.nodes.0.nodes.0 { - let (name, args) = some!(system_tf_call_parts(system_call, syntax_tree)); - system_functions::check_call( - name, - args.as_deref(), - system_functions::CallSite::Expression, - )?; - if matches!(name, "$timeunit" | "$timeprecision") { + let function = + some!(expressions::system_function_call(system_call, syntax_tree)?); + if let SystemFunction::Timeunit | SystemFunction::Timeprecision = function { return Ok(Some(ConstExpr::Literal(format_typed_parameter_literal( i128::from(timescales::query(system_call, syntax_tree)?), 32, @@ -1320,47 +1317,50 @@ pub(super) fn const_expr_from_ref_node_with_env( const_env, false, )?; - if name == "$isunbounded" { + match function { // Imported aliases may not be bound in preliminary // collection. Retain the query for later resolution, // including its one-bit type for dependent queries. - return const_expr_from_function_subroutine_call( - &call.nodes.0, - syntax_tree, - const_env, - ); - } - if name == "$dimensions" - && let Some(count) = dimensions::dimensions_system_function_call_value( - system_call, - syntax_tree, - const_env, - type_aliases, - None, - ) - { - return Ok(Some(ConstExpr::Literal(count.to_string()))); - } - if name == "$unpacked_dimensions" - && let Some(count) = dimensions::unpacked_dimensions_call_value( - system_call, - syntax_tree, - const_env, - type_aliases, - None, - ) - { - return Ok(Some(ConstExpr::Literal(count.to_string()))); - } - if matches!(name, "$left" | "$right" | "$low" | "$high" | "$increment") { - return Ok(dimensions::array_query_call( - system_call, - syntax_tree, - const_env, - type_aliases, - None, - ) - .and_then(expr_to_const)); + SystemFunction::Isunbounded => { + return const_expr_from_function_subroutine_call( + &call.nodes.0, + syntax_tree, + const_env, + ); + } + SystemFunction::Dimensions => { + if let Some(count) = dimensions::dimensions_system_function_call_value( + system_call, + syntax_tree, + const_env, + type_aliases, + None, + ) { + return Ok(Some(ConstExpr::Literal(count.to_string()))); + } + } + SystemFunction::UnpackedDimensions => { + if let Some(count) = dimensions::unpacked_dimensions_call_value( + system_call, + syntax_tree, + const_env, + type_aliases, + None, + ) { + return Ok(Some(ConstExpr::Literal(count.to_string()))); + } + } + SystemFunction::ArrayQuery(_) => { + return Ok(dimensions::array_query_call( + system_call, + syntax_tree, + const_env, + type_aliases, + None, + ) + .and_then(expr_to_const)); + } + _ => {} } } if let sv_parser::SubroutineCall::TfCall(tf_call) = &call.nodes.0.nodes.0 @@ -1389,8 +1389,11 @@ pub(super) fn const_expr_from_ref_node_with_env( syntax_tree, const_env, )?; - if let Some(ConstExpr::Function { name, args, .. }) = &lowered - && name == "$bits" + if let Some(ConstExpr::Function { + callee: Callee::System(SystemFunction::Bits), + args, + .. + }) = &lowered && let [arg] = args.as_slice() && let Some(r#type) = infer_const_expr_type(arg, ¶meter_types_from_const_env(const_env)) @@ -1600,14 +1603,14 @@ fn const_user_call( // Effectful runtime named calls keep their source order. Constant calls // are folded only when their bodies and actuals evaluate successfully. let literal = const_functions::eval_expression_literal(&expression, constants)?; - let Expr::Call { name, args, .. } = &expression else { + let Expr::Call { callee, args, .. } = &expression else { unreachable!() }; let types = parameter_types_from_const_env(constants) .into_iter() .map(|(name, ty)| (name, (ty.width, ty.signed))) .collect(); - let args = const_functions::resolved_arguments(name, args)? + let args = const_functions::resolved_arguments(callee, args)? .into_iter() .map(|arg| { expr_to_const(arg.clone()).or_else(|| { @@ -1618,7 +1621,7 @@ fn const_user_call( // Keep references to parameters for consumers that re-specialize the // declaration contract; retain the native function's result type too. return Some(ConstExpr::Resize { - expr: Box::new(ConstExpr::call(name.clone(), args)), + expr: Box::new(ConstExpr::call(callee.clone(), args)), width: literal.width, signed: literal.signed, }); @@ -1665,29 +1668,26 @@ fn const_expr_from_function_subroutine_call( } _ => return Ok(None), }; - let (name, args) = some!(system_tf_call_parts(system_call, syntax_tree)); - system_functions::check_call( - name, - args.as_deref(), - system_functions::CallSite::Expression, - )?; - if name == "$isunbounded" { + let function = some!(expressions::system_function_call(system_call, syntax_tree)?); + if function == SystemFunction::Isunbounded { if let Some(value) = parameters::isunbounded_call(system_call, syntax_tree, const_env)? { return Ok(Some(value)); } let argument = expressions::single_expression_argument(system_call).unwrap(); return Ok(Some(ConstExpr::call( - name.into(), + Callee::System(function), vec![const_expr_from_expr(argument, syntax_tree)?.unwrap()], ))); } let sv_parser::SystemTfCall::ArgExpression(expression_call) = &**system_call else { return Ok(None); }; - if matches!( - name, - "$countbits" | "$countones" | "$onehot" | "$onehot0" | "$isunknown" - ) { + if let SystemFunction::Countbits + | SystemFunction::Countones + | SystemFunction::Onehot + | SystemFunction::Onehot0 + | SystemFunction::Isunknown = function + { // Use expression lowering so selections are never silently discarded // by the limited constant-primary identifier path below. Unsupported // constant argument forms must remain unresolved rather than counting @@ -1699,7 +1699,7 @@ fn const_expr_from_function_subroutine_call( ) .ok(); return Ok(expression.and_then(|expression| { - if name == "$countbits" { + if function == SystemFunction::Countbits { countbits_constant_call(expression, const_env) } else { expr_to_const(expression) @@ -1712,7 +1712,7 @@ fn const_expr_from_function_subroutine_call( let argument = some!(argument.as_ref()); lowered.push(parsed!(const_expr_from_expr(argument, syntax_tree))); } - Ok(Some(ConstExpr::call(name.to_string(), lowered))) + Ok(Some(ConstExpr::call(Callee::System(function), lowered))) } // ConstExpr represents bit selects but not concatenations or part selects. @@ -1722,7 +1722,7 @@ fn countbits_constant_call( expression: Expr, const_env: &HashMap, ) -> Option { - let Expr::Call { name, args, .. } = expression else { + let Expr::Call { args, .. } = expression else { return None; }; let mut args = args.into_iter().collect::>>()?; @@ -1737,12 +1737,11 @@ fn countbits_constant_call( control => expr_to_const(control), }) .collect::>>()?; - countbits_constant_operand(operand, &name, &controls, const_env) + countbits_constant_operand(operand, &controls, const_env) } fn countbits_constant_operand( operand: Expr, - name: &str, controls: &[ConstExpr], const_env: &HashMap, ) -> Option { @@ -1750,7 +1749,7 @@ fn countbits_constant_operand( let mut args = Vec::with_capacity(controls.len() + 1); args.push(operand); args.extend_from_slice(controls); - ConstExpr::call(name.to_string(), args) + ConstExpr::call(Callee::System(SystemFunction::Countbits), args) }; let sum = |mut terms: Vec| { // Keep large selected vectors from creating a deeply nested sum. @@ -1791,15 +1790,14 @@ fn countbits_constant_operand( } Expr::Concat(parts) => sum(parts .into_iter() - .map(|part| countbits_constant_operand(part, name, controls, const_env)) + .map(|part| countbits_constant_operand(part, controls, const_env)) .collect::>>()?), Expr::RepeatConcat { count, parts } => { let count = eval_ast_const_expr(&count, const_env)?; if count < 0 { return None; } - let counted = - countbits_constant_operand(Expr::Concat(parts), name, controls, const_env)?; + let counted = countbits_constant_operand(Expr::Concat(parts), controls, const_env)?; Some(ConstExpr::Binary { left: Box::new(counted), op: BinaryOp::Mul, diff --git a/crates/celox-sv-analyzer/src/ast/constants/tests.rs b/crates/celox-sv-analyzer/src/ast/constants/tests.rs index 7bf200182fa..354d7d7e26b 100644 --- a/crates/celox-sv-analyzer/src/ast/constants/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/constants/tests.rs @@ -227,10 +227,10 @@ fn compare_lazy_and_copied_scalar_call_contexts() { ) .unwrap() }; - let Some(ConstExpr::Function { name, args, .. }) = black_box(result) else { + let Some(ConstExpr::Function { callee, args, .. }) = black_box(result) else { panic!("call was not retained") }; - assert_eq!(name, "f"); + assert_eq!(callee, Callee::Subroutine("f".into())); assert_eq!(args.len(), 1); } start.elapsed().as_secs_f64() * 1000.0 diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index 4c6d1a276d8..f8e402c0a48 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -13,7 +13,8 @@ pub(super) fn dimensions_system_function_call_value( ) -> Option { match call { sv_parser::SystemTfCall::ArgDataType(call) => { - if syntax_tree.get_str(&call.nodes.0.nodes.0)? != "$dimensions" + if SystemFunction::from_name(syntax_tree.get_str(&call.nodes.0.nodes.0)?) + != Some(SystemFunction::Dimensions) || call.nodes.1.nodes.1.1.is_some() { return None; @@ -34,7 +35,9 @@ pub(super) fn dimensions_system_function_call_value( Some(ty.unpacked_ranges().len() + ty.packed_ranges().len()) } sv_parser::SystemTfCall::ArgExpression(call) => { - if syntax_tree.get_str(&call.nodes.0.nodes.0)? != "$dimensions" { + if SystemFunction::from_name(syntax_tree.get_str(&call.nodes.0.nodes.0)?) + != Some(SystemFunction::Dimensions) + { return None; } let arguments = call.nodes.1.nodes.1.0.contents(); @@ -278,7 +281,10 @@ fn expression_dimensions( } } let expression = expr_from_expression_with_types(argument, syntax_tree, dimensions).ok()?; - if let Expr::Call { name, .. } = &expression + if let Expr::Call { + callee: Callee::Subroutine(name), + .. + } = &expression && let Some(metadata) = dimensions.function_return_types.get(name) { return metadata.dimensions; @@ -309,7 +315,8 @@ pub(super) fn unpacked_dimensions_call_value( ) -> Option { match call { sv_parser::SystemTfCall::ArgDataType(call) => { - if syntax_tree.get_str(&call.nodes.0.nodes.0)? != "$unpacked_dimensions" + if SystemFunction::from_name(syntax_tree.get_str(&call.nodes.0.nodes.0)?) + != Some(SystemFunction::UnpackedDimensions) || call.nodes.1.nodes.1.1.is_some() { return None; @@ -328,7 +335,9 @@ pub(super) fn unpacked_dimensions_call_value( .map(|ty| ty.unpacked_ranges().len()) } sv_parser::SystemTfCall::ArgExpression(call) => { - if syntax_tree.get_str(&call.nodes.0.nodes.0)? != "$unpacked_dimensions" { + if SystemFunction::from_name(syntax_tree.get_str(&call.nodes.0.nodes.0)?) + != Some(SystemFunction::UnpackedDimensions) + { return None; } let arguments = call.nodes.1.nodes.1.0.contents(); @@ -595,9 +604,14 @@ pub(super) fn size_system_function_call_type( .flatten() .and_then(|dimension| eval_ast_const_expr(&dimension, const_env)) }; - let (name, r#type, dimension) = match call { + let function = called_system_function(call, syntax_tree)?; + let size = match function { + SystemFunction::Bits => false, + SystemFunction::Size => true, + _ => return None, + }; + let (r#type, dimension) = match call { sv_parser::SystemTfCall::ArgDataType(call) => { - let name = syntax_tree.get_str(&call.nodes.0.nodes.0)?; let (data_type, dimension) = &call.nodes.1.nodes.1; let dimension = match dimension { Some((_, dimension)) => Some(dimension_argument(dimension)?), @@ -615,19 +629,16 @@ pub(super) fn size_system_function_call_type( type_aliases, ), }?; - (name, r#type, dimension) + (r#type, dimension) } // sv-parser classifies an unqualified typedef argument as an // expression because its grammar cannot know whether the identifier // names a type. Resolve that ambiguity from the module alias table. sv_parser::SystemTfCall::ArgExpression(call) => { - let name = syntax_tree.get_str(&call.nodes.0.nodes.0)?; let arguments = call.nodes.1.nodes.1.0.contents(); // `$size(x, n)`: the number of elements of dimension `n`, counted // from the outermost unpacked dimension (IEEE 1800-2023 20.7). - if name == "$size" - && let [Some(argument), Some(dimension)] = arguments.as_slice() - { + if size && let [Some(argument), Some(dimension)] = arguments.as_slice() { let identifier = match const_expr_from_expr(argument, syntax_tree).ok().flatten()? { ConstExpr::Ident(identifier) => identifier, _ => return None, @@ -655,9 +666,6 @@ pub(super) fn size_system_function_call_type( return None; } let argument = arguments[0].as_ref()?; - if name != "$bits" && name != "$size" { - return None; - } // An unqualified typedef is parsed as an expression. Once the // lexical scope is complete, distinguish it from a visible value // before falling back to enclosing-declaration discovery. @@ -672,7 +680,7 @@ pub(super) fn size_system_function_call_type( && !dimensions.parameter_values.contains_key(&identifier) && let Some(r#type) = type_aliases.get(&identifier) { - return size_query_for_type(r#type, const_env, name == "$size"); + return size_query_for_type(r#type, const_env, size); } if let Some(dimensions) = dimensions && let Some(ty) = size_function_expression_type( @@ -680,7 +688,7 @@ pub(super) fn size_system_function_call_type( syntax_tree, const_env, type_aliases, - name == "$size", + size, Some(dimensions), ) { @@ -698,7 +706,7 @@ pub(super) fn size_system_function_call_type( { let dimensions = PackedDimensions::new(dimensions, const_env, type_aliases); let expression = Expr::Ident(identifier.clone()); - let width = if name == "$size" { + let width = if size { selected_expression_first_dimension_width(argument, syntax_tree, &dimensions) } else { expr_static_width(&expression, &dimensions) @@ -712,8 +720,7 @@ pub(super) fn size_system_function_call_type( // found by the enclosing-module scan used for complex expressions. if let Ok(Some(ConstExpr::Ident(identifier))) = const_expr_from_expr(argument, syntax_tree) - && let Some(width) = - variable_size_function_width(const_env, &identifier, name == "$size") + && let Some(width) = variable_size_function_width(const_env, &identifier, size) { return Some(ExprType { width, @@ -729,7 +736,7 @@ pub(super) fn size_system_function_call_type( syntax_tree, const_env, type_aliases, - name == "$size", + size, None, ) { return Some(r#type); @@ -738,11 +745,10 @@ pub(super) fn size_system_function_call_type( if let ConstExpr::Ident(alias) = &argument && let Some(r#type) = type_aliases.get(alias) { - (name, r#type.clone(), None) + (r#type.clone(), None) } else { if let ConstExpr::Ident(identifier) = &argument - && let Some(width) = - variable_size_function_width(const_env, identifier, name == "$size") + && let Some(width) = variable_size_function_width(const_env, identifier, size) { return Some(ExprType { width, @@ -761,10 +767,10 @@ pub(super) fn size_system_function_call_type( }; // $bits covers every unpacked and packed dimension; $size covers one // dimension, by default the outermost one. - if name == "$size" { + if size { return type_dimension_size(&r#type, dimension, const_env); } - if name != "$bits" || dimension.is_some() { + if dimension.is_some() { return None; } size_query_for_type(&r#type, const_env, false) @@ -945,16 +951,17 @@ fn size_function_expression_type_from_dimensions( // (IEEE 1800-2023 6.20.2), even without explicit dimensions. Expr::Ident(name) => variable_size_function_width(const_env, name, true) .or_else(|| parameter_type_from_const_env(const_env, name).map(|ty| ty.width)), - Expr::Call { name, args, .. } => { - typecheck::bit_vector_function_return_type(name, args.len()) - .map(|(width, _)| width) - .or_else(|| { - packed_dimensions - .function_return_types - .get(name) - .and_then(|metadata| metadata.first_packed_dimension_width) - }) - } + Expr::Call { + callee: Callee::System(function), + .. + } => function.result_type().map(|(width, _)| width), + Expr::Call { + callee: Callee::Subroutine(name), + .. + } => packed_dimensions + .function_return_types + .get(name) + .and_then(|metadata| metadata.first_packed_dimension_width), _ => expr_static_width(&expression, packed_dimensions), }, ) diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/queries.rs b/crates/celox-sv-analyzer/src/ast/dimensions/queries.rs index e76e0ea174f..d2ccabc1d98 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/queries.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/queries.rs @@ -10,7 +10,7 @@ pub(in crate::ast) fn array_query_call( aliases: &HashMap, dimensions: Option<&PackedDimensions>, ) -> Option { - let (name, _) = system_tf_call_parts(call, tree)?; + let function = called_system_function(call, tree)?; let (bounds, unpacked, dimension) = match call { sv_parser::SystemTfCall::ArgDataType(call) => { let (data_type, dimension) = &call.nodes.1.nodes.1; @@ -62,25 +62,25 @@ pub(in crate::ast) fn array_query_call( _ => return None, }; let integer = |value| Expr::Literal(format_typed_parameter_literal(value, 32, true)); - match name { - "$dimensions" => return Some(integer(bounds.len() as i128)), - "$unpacked_dimensions" => return Some(integer(unpacked as i128)), - _ => {} - } + let query = match function { + SystemFunction::Dimensions => return Some(integer(bounds.len() as i128)), + SystemFunction::UnpackedDimensions => return Some(integer(unpacked as i128)), + SystemFunction::ArrayQuery(query) => query, + _ => return None, + }; let value = |&(left, right): &(i128, i128)| { - integer(match name { - "$left" => left, - "$right" => right, - "$low" => left.min(right), - "$high" => left.max(right), - "$increment" => { + integer(match query { + ArrayQuery::Left => left, + ArrayQuery::Right => right, + ArrayQuery::Low => left.min(right), + ArrayQuery::High => left.max(right), + ArrayQuery::Increment => { if left >= right { 1 } else { -1 } } - _ => unreachable!(), }) }; let dimension = dimension.unwrap_or_else(|| integer(1)); diff --git a/crates/celox-sv-analyzer/src/ast/expressions.rs b/crates/celox-sv-analyzer/src/ast/expressions.rs index c0d7ab362e3..1982bc90b25 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -368,12 +368,12 @@ pub(super) fn guard_zero_divisions(expr: Expr) -> Expr { .collect(), }, Expr::Call { - name, + callee, args, arg_order, } => Expr::Call { arg_order: arg_order.clone(), - name, + callee, args: args .into_iter() .map(|arg| arg.map(guard_zero_divisions)) @@ -588,11 +588,7 @@ fn expr_from_system_function_call( ) -> Converted { let (name, args) = system_tf_call_parts(call, syntax_tree) .ok_or_else(|| unsupported("system function name"))?; - system_functions::check_call( - name, - args.as_deref(), - system_functions::CallSite::Expression, - )?; + let function = system_functions::check_function_call(name, args.as_deref())?; parameters::reject_unbounded_data_query( call, syntax_tree, @@ -600,8 +596,8 @@ fn expr_from_system_function_call( packed_dimensions.scope_types_complete, )?; let operand_error = || unsupported(format!("operand of `{name}`")); - match name { - "$urandom" => { + match function { + SystemFunction::Urandom => { let args = match call { sv_parser::SystemTfCall::ArgOptionl(call) if call.nodes.1.is_none() => Vec::new(), _ => match single_expression_argument(call) { @@ -637,15 +633,17 @@ fn expr_from_system_function_call( }, }; Ok(Expr::Call { - name: name.into(), + callee: Callee::System(function), args, arg_order: Vec::new(), }) } - "$timeunit" | "$timeprecision" => timescales::query(call, syntax_tree).map(|value| { - Expr::Literal(format_typed_parameter_literal(i128::from(value), 32, true)) - }), - "$isunbounded" => { + SystemFunction::Timeunit | SystemFunction::Timeprecision => { + timescales::query(call, syntax_tree).map(|value| { + Expr::Literal(format_typed_parameter_literal(i128::from(value), 32, true)) + }) + } + SystemFunction::Isunbounded => { parameters::isunbounded_call(call, syntax_tree, &packed_dimensions.const_env)? .map(const_expr_to_expr) .ok_or_else(|| AnalyzerError::InvalidSystemTfCall { @@ -653,7 +651,7 @@ fn expr_from_system_function_call( detail: "argument must name a value parameter".into(), }) } - "$dimensions" => dimensions::dimensions_system_function_call_value( + SystemFunction::Dimensions => dimensions::dimensions_system_function_call_value( call, syntax_tree, &packed_dimensions.const_env, @@ -662,7 +660,7 @@ fn expr_from_system_function_call( ) .map(|count| Expr::Literal(count.to_string())) .ok_or_else(operand_error), - "$unpacked_dimensions" => dimensions::unpacked_dimensions_call_value( + SystemFunction::UnpackedDimensions => dimensions::unpacked_dimensions_call_value( call, syntax_tree, &packed_dimensions.const_env, @@ -671,7 +669,7 @@ fn expr_from_system_function_call( ) .map(|count| Expr::Literal(count.to_string())) .ok_or_else(operand_error), - "$left" | "$right" | "$low" | "$high" | "$increment" => dimensions::array_query_call( + SystemFunction::ArrayQuery(_) => dimensions::array_query_call( call, syntax_tree, &packed_dimensions.const_env, @@ -680,7 +678,7 @@ fn expr_from_system_function_call( ) .ok_or_else(operand_error), // `$bits(x)` and `$size(x)` depend only on the declared type of `x`. - "$bits" | "$size" => dimensions::size_system_function_call_type( + SystemFunction::Bits | SystemFunction::Size => dimensions::size_system_function_call_type( call, syntax_tree, &packed_dimensions.const_env, @@ -689,7 +687,7 @@ fn expr_from_system_function_call( ) .map(|ty| Expr::Literal(ty.width.to_string())) .ok_or_else(operand_error), - "$signed" | "$unsigned" => { + SystemFunction::Signed | SystemFunction::Unsigned => { // Reinterpret the operand's signedness without changing its width. let arg = expr_from_expression_with_types( single_expression_argument(call).ok_or_else(operand_error)?, @@ -700,10 +698,10 @@ fn expr_from_system_function_call( Ok(Expr::Resize { expr: Box::new(arg), width, - signed: name == "$signed", + signed: function == SystemFunction::Signed, }) } - "$countbits" => { + SystemFunction::Countbits => { let sv_parser::SystemTfCall::ArgExpression(call) = call else { return Err(operand_error()); }; @@ -717,22 +715,26 @@ fn expr_from_system_function_call( } Ok(Expr::Call { arg_order: Vec::new(), - name: name.to_string(), + callee: Callee::System(function), args: args.into_iter().map(Some).collect(), }) } - "$clog2" | "$countones" | "$onehot" | "$onehot0" | "$isunknown" => { + SystemFunction::Clog2 + | SystemFunction::Countones + | SystemFunction::Onehot + | SystemFunction::Onehot0 + | SystemFunction::Isunknown => { let arg = expr_from_expression_with_types( single_expression_argument(call).ok_or_else(operand_error)?, syntax_tree, packed_dimensions, )?; // `$clog2` of a constant is a constant. - if name == "$clog2" + if function == SystemFunction::Clog2 && let Some(argument) = expr_to_const(arg.clone()) && let Some(value) = eval_ast_const_expr( &ConstExpr::Function { - name: name.to_string(), + callee: Callee::System(function), args: vec![argument], site: None, }, @@ -743,13 +745,10 @@ fn expr_from_system_function_call( } Ok(Expr::Call { arg_order: Vec::new(), - name: name.to_string(), + callee: Callee::System(function), args: vec![Some(arg)], }) } - _ => Err(AnalyzerError::Unsupported(format!( - "system function `{name}` in an expression" - ))), } } @@ -874,7 +873,7 @@ pub(super) fn expr_from_tf_call( args.push(Some(arg)); } Ok(Expr::Call { - name, + callee: Callee::Subroutine(name), args, arg_order, }) @@ -925,6 +924,34 @@ fn selected_concatenation( }) } +/// Check a system function call in expression position and identify the +/// function; `None` if its name cannot be read. +pub(crate) fn system_function_call( + call: &sv_parser::SystemTfCall, + syntax_tree: &SyntaxTree, +) -> Converted> { + let Some((name, args)) = system_tf_call_parts(call, syntax_tree) else { + return Ok(None); + }; + system_functions::check_function_call(name, args.as_deref()).map(Some) +} + +/// The supported system function a call names, without checking the call. +pub(super) fn called_system_function( + call: &sv_parser::SystemTfCall, + syntax_tree: &SyntaxTree, +) -> Option { + SystemFunction::from_name(system_tf_call_parts(call, syntax_tree)?.0) +} + +/// The supported system task a call names, without checking the call. +pub(super) fn called_system_task( + call: &sv_parser::SystemTfCall, + syntax_tree: &SyntaxTree, +) -> Option { + SystemTask::from_name(system_tf_call_parts(call, syntax_tree)?.0) +} + /// The name of a system task or function call, with its leading `$`, and its /// arguments as written (`None` when they are bound by name). pub(super) fn system_tf_call_parts<'a>( diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index 5654cb9e59a..aa8abe5b5b6 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -1774,7 +1774,7 @@ fn function_expr_from_conditional_statement( Some(Expr::Call { arg_order: Vec::new(), - name: "$unsupported_mixed_function_conditional".to_string(), + callee: Callee::Subroutine("$unsupported_mixed_function_conditional".to_string()), args: Vec::new(), }) } @@ -1928,7 +1928,7 @@ fn function_expr_from_case_statement( Some(Expr::Call { arg_order: Vec::new(), - name: "$unsupported_mixed_function_case".to_string(), + callee: Callee::Subroutine("$unsupported_mixed_function_case".to_string()), args: Vec::new(), }) } diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index b5adcbceadb..1f451d23239 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -260,8 +260,10 @@ impl Item<'_> { } } } - Expr::Call { name, args, .. } => { - *name = self.name(name); + Expr::Call { callee, args, .. } => { + if let Callee::Subroutine(name) = callee { + *name = self.name(name); + } args.iter_mut().flatten().for_each(|e| self.expr(e)); } } @@ -280,8 +282,10 @@ impl Item<'_> { self.constant(expr); self.constant(bit); } - ConstExpr::Function { name, args, .. } => { - *name = self.name(name); + ConstExpr::Function { callee, args, .. } => { + if let Callee::Subroutine(name) = callee { + *name = self.name(name); + } args.iter_mut().for_each(|e| self.constant(e)); } ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => self.constant(expr), @@ -557,11 +561,13 @@ impl<'a> Elaborator<'a, '_> { fn expand_constant_calls(&self, expr: &mut ConstExpr, scope: &Scope) -> Option<()> { match expr { - ConstExpr::Function { name, args, .. } => { + ConstExpr::Function { callee, args, .. } => { for arg in args { self.expand_constant_calls(arg, scope)?; } - if self.functions.contains_key(name) { + if let Callee::Subroutine(name) = callee + && self.functions.contains_key(name) + { if scope.shadowed.contains(name) { return None; } diff --git a/crates/celox-sv-analyzer/src/ast/inlining.rs b/crates/celox-sv-analyzer/src/ast/inlining.rs index 8cee8e30f90..6933629c7c8 100644 --- a/crates/celox-sv-analyzer/src/ast/inlining.rs +++ b/crates/celox-sv-analyzer/src/ast/inlining.rs @@ -97,16 +97,21 @@ pub(super) fn expr_signedness_with_return_types( )?, ), Expr::Inside { .. } => Some(false), - Expr::Call { name, args, .. } => { - typecheck::bit_vector_function_return_type(name, args.len()) - .map(|(_, signed)| signed) - .or_else(|| functions.get(name).map(|function| function.return_signed)) - .or_else(|| { - function_return_types - .get(name) - .map(|metadata| metadata.signed) - }) - } + Expr::Call { + callee: Callee::System(function), + .. + } => function.result_type().map(|(_, signed)| signed), + Expr::Call { + callee: Callee::Subroutine(name), + .. + } => functions + .get(name) + .map(|function| function.return_signed) + .or_else(|| { + function_return_types + .get(name) + .map(|metadata| metadata.signed) + }), } } @@ -114,8 +119,8 @@ pub(super) fn expr_signedness_with_return_types( pub(super) fn calls_subroutine(expr: &Expr) -> bool { fn constant(expr: &ConstExpr) -> bool { match expr { - ConstExpr::Function { name, args, .. } => { - !system_functions::is_system_name(name) || args.iter().any(constant) + ConstExpr::Function { callee, args, .. } => { + callee.subroutine().is_some() || args.iter().any(constant) } ConstExpr::SelectRange { expr, msb, lsb, .. } => { constant(expr) || constant(msb) || constant(lsb) @@ -132,8 +137,8 @@ pub(super) fn calls_subroutine(expr: &Expr) -> bool { } } match expr { - Expr::Call { name, args, .. } => { - !system_functions::is_system_name(name) || args.iter().flatten().any(calls_subroutine) + Expr::Call { callee, args, .. } => { + callee.subroutine().is_some() || args.iter().flatten().any(calls_subroutine) } Expr::Ident(_) | Expr::Literal(_) => false, Expr::Select { expr, msb, lsb, .. } => { @@ -315,7 +320,7 @@ pub(super) fn expand_expr_calls( .collect(), }, Expr::Call { - name, + callee, args, arg_order, } => { @@ -333,16 +338,16 @@ pub(super) fn expand_expr_calls( }) }) .collect::>(); - let Some(function) = functions.get(&name) else { + let Some(function) = callee.subroutine().and_then(|name| functions.get(name)) else { return Expr::Call { - name, + callee, args, arg_order, }; }; let Some(function_body) = &function.body else { return Expr::Call { - name, + callee, args, arg_order, }; @@ -355,7 +360,7 @@ pub(super) fn expand_expr_calls( || args.iter().flatten().any(calls_subroutine) { return Expr::Call { - name, + callee, args, arg_order, }; @@ -401,7 +406,7 @@ pub(super) fn expand_expr_calls( if calls_subroutine(&expanded) { return Expr::Call { arg_order, - name, + callee, args: call_args, }; } @@ -499,12 +504,12 @@ pub(super) fn substitute_expr_idents(expr: Expr, env: &HashMap) -> .collect(), }, Expr::Call { - name, + callee, args, arg_order, } => Expr::Call { arg_order: arg_order.clone(), - name, + callee, args: args .into_iter() .map(|arg| arg.map(|arg| substitute_expr_idents(arg, env))) diff --git a/crates/celox-sv-analyzer/src/ast/instances.rs b/crates/celox-sv-analyzer/src/ast/instances.rs index 9e5ab3fd0b0..6665e760901 100644 --- a/crates/celox-sv-analyzer/src/ast/instances.rs +++ b/crates/celox-sv-analyzer/src/ast/instances.rs @@ -546,12 +546,14 @@ fn constant_pattern_literal( freeze(then_expr, constants); freeze(else_expr, constants); } - ConstExpr::Function { name, args, .. } => { + ConstExpr::Function { callee, args, .. } => { for arg in args.iter_mut() { freeze(arg, constants); } let lowered = args.iter().cloned().map(Into::into).collect::>(); - if let Some(literal) = const_functions::eval_call_literal(name, &lowered, constants) + if let Callee::Subroutine(name) = callee + && let Some(literal) = + const_functions::eval_call_literal(name, &lowered, constants) { *expr = ConstExpr::Literal(typecheck::format_integral_literal_binary(&literal)); } diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index ce7978aa4d6..45cde2ff162 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -410,8 +410,10 @@ fn resolve_interface_timescale_queries( scales: &super::timescales::Timescales, ) -> Result>, AnalyzerError> { let is_query = |call, tree| { - system_tf_call_parts(call, tree) - .is_some_and(|(name, _)| matches!(name, "$timeunit" | "$timeprecision")) + matches!( + called_system_function(call, tree), + Some(SystemFunction::Timeunit | SystemFunction::Timeprecision) + ) }; let mut changed = false; let codes = files @@ -600,9 +602,7 @@ impl<'a> File<'a> { let RefNode::SystemTfCall(call) = node else { continue; }; - if !system_tf_call_parts(call, &file.syntax_tree) - .is_some_and(|(name, _)| name == "$printtimescale") - { + if called_system_task(call, &file.syntax_tree) != Some(SystemTask::Printtimescale) { continue; } let span = file.span(RefNode::SystemTfCall(call))?; @@ -2258,13 +2258,12 @@ impl<'a> Design<'a> { let RefNode::SystemTfCall(call) = node else { return false; }; - system_tf_call_parts(call, &file.syntax_tree).is_some_and(|(name, _)| { - matches!(name, "$timeunit" | "$timeprecision" | "$printtimescale") - }) && super::timescales::argument(call).is_some_and(|argument| { - file.syntax_tree - .get_str_trim(argument) - .is_some_and(|text| text.contains('.')) - }) + super::timescales::is_timescale_call(call, &file.syntax_tree) + && super::timescales::argument(call).is_some_and(|argument| { + file.syntax_tree + .get_str_trim(argument) + .is_some_and(|text| text.contains('.')) + }) }); if handles.is_empty() && child_instantiations.is_empty() @@ -2305,7 +2304,7 @@ impl<'a> Design<'a> { let Some((function, args)) = system_tf_call_parts(call, &file.syntax_tree) else { return Ok(None); }; - if !matches!(function, "$timeunit" | "$timeprecision" | "$printtimescale") { + if !super::timescales::is_timescale_call(call, &file.syntax_tree) { return Ok(None); } let Some(argument) = super::timescales::argument(call) else { @@ -2353,8 +2352,8 @@ impl<'a> Design<'a> { for node in RefNode::ModuleDeclarationAnsi(declaration) { let edit = match node { RefNode::SystemTfCall(call) - if system_tf_call_parts(call, &file.syntax_tree) - .is_none_or(|(name, _)| name != "$printtimescale") => + if called_system_task(call, &file.syntax_tree) + != Some(SystemTask::Printtimescale) => { query_edit(call, system_functions::CallSite::Expression)? } @@ -2380,8 +2379,8 @@ impl<'a> Design<'a> { check_query_origin(file, file.syntax_tree.get_str_trim(statement), span)?; Some(Edit { span, - text: if system_tf_call_parts(call, &file.syntax_tree) - .is_some_and(|(name, _)| name == "$printtimescale") + text: if called_system_task(call, &file.syntax_tree) + == Some(SystemTask::Printtimescale) { format!("{};", edit.text) } else { @@ -3547,7 +3546,7 @@ fn readmem_destination<'b>( sv_parser::SystemTfCall::ArgDataType(_) => return Ok(None), }; let name = file.text(file.span(RefNode::SystemTfIdentifier(identifier))?); - if name != "$readmemh" && name != "$readmemb" { + if !matches!(SystemTask::from_name(name), Some(SystemTask::Readmem(_))) { return Ok(None); } Ok(arguments.get(1).and_then(|argument| argument.as_ref())) diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index 4c857203a54..84b66629b3a 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -664,12 +664,14 @@ fn stmt_exprs(stmt: &Stmt) -> Vec<&Expr> { } } -/// Call `f` with the name and arguments of every call in `expr`. +/// Call `f` with the name and arguments of every subroutine call in `expr`. fn visit_calls<'e>(expr: &'e Expr, f: &mut impl FnMut(&'e str, &'e [Option])) { match expr { Expr::Ident(_) | Expr::Literal(_) => {} - Expr::Call { name, args, .. } => { - f(name, args); + Expr::Call { callee, args, .. } => { + if let Callee::Subroutine(name) = callee { + f(name, args); + } for arg in args.iter().flatten() { visit_calls(arg, f); } diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index 9d1c8567db3..fa41e68f480 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -63,7 +63,10 @@ pub(super) fn contains_unbounded_operand(value: &ConstExpr, env: &HashMap { contains_unbounded_operand(expr, env) || contains_unbounded_operand(bit, env) } - ConstExpr::Function { name, .. } if name == "$isunbounded" => false, + ConstExpr::Function { + callee: Callee::System(SystemFunction::Isunbounded), + .. + } => false, ConstExpr::Function { args, .. } => { args.iter().any(|arg| contains_unbounded_operand(arg, env)) } @@ -94,21 +97,10 @@ pub(super) fn reject_unbounded_data_query( env: &HashMap, complete: bool, ) -> Result<(), AnalyzerError> { - let Some((name, _)) = system_tf_call_parts(call, tree) else { + let Some(function) = called_system_function(call, tree) else { return Ok(()); }; - if !matches!( - name, - "$bits" - | "$size" - | "$dimensions" - | "$unpacked_dimensions" - | "$left" - | "$right" - | "$low" - | "$high" - | "$increment" - ) { + if !function.is_data_query() { return Ok(()); } let sv_parser::SystemTfCall::ArgExpression(call) = call else { @@ -122,13 +114,12 @@ pub(super) fn reject_unbounded_data_query( sv_parser::NodeEvent::Leave(child) => (false, child), }; if let RefNode::SystemTfCall(nested) = &child - && system_tf_call_parts(nested, tree) - .is_some_and(|(name, _)| name == "$isunbounded") + && called_system_function(nested, tree) == Some(SystemFunction::Isunbounded) { if entering { if complete && isunbounded_call(nested, tree, env)?.is_none() { return Err(AnalyzerError::InvalidSystemTfCall { - name: "$isunbounded".into(), + name: SystemFunction::Isunbounded.name().into(), detail: "argument must name a value parameter".into(), }); } @@ -156,7 +147,7 @@ pub(super) fn reject_unbounded_data_query( }; if unbounded { return Err(AnalyzerError::InvalidSystemTfCall { - name: name.into(), + name: function.name().into(), detail: "unbounded parameter is not valid in this data query".into(), }); } @@ -178,7 +169,7 @@ pub(super) fn isunbounded_call( .and_then(|arg| const_expr_from_expr(arg, tree).ok().flatten()); let Some(ConstExpr::Ident(name)) = argument else { return Err(AnalyzerError::InvalidSystemTfCall { - name: "$isunbounded".into(), + name: SystemFunction::Isunbounded.name().into(), detail: "argument must name a value parameter".into(), }); }; @@ -632,20 +623,7 @@ pub(super) fn validate_parameter_initializer_literal_widths( continue; } if let RefNode::SystemTfCall(call) = node - && system_tf_call_parts(call, tree).is_some_and(|(name, _)| { - matches!( - name, - "$bits" - | "$size" - | "$left" - | "$right" - | "$low" - | "$high" - | "$increment" - | "$dimensions" - | "$unpacked_dimensions" - ) - }) + && called_system_function(call, tree).is_some_and(SystemFunction::is_data_query) && let sv_parser::SystemTfCall::ArgExpression(call) = call && let Some(Some(argument)) = call.nodes.1.nodes.1.0.contents().first() { @@ -1680,8 +1658,8 @@ fn replace_oob_const_selects_with_unknown( } } } - ConstExpr::Function { name, args, site } => ConstExpr::Function { - name, + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee, site, args: args .into_iter() @@ -1788,9 +1766,9 @@ pub(super) fn const_expr_to_expr(expr: ConstExpr) -> Expr { width, signed, }, - ConstExpr::Function { name, args, .. } => Expr::Call { + ConstExpr::Function { callee, args, .. } => Expr::Call { arg_order: Vec::new(), - name, + callee, args: args .into_iter() .map(|arg| Some(const_expr_to_expr(arg))) @@ -1895,17 +1873,21 @@ pub(super) fn substitute_typed_parameter_literals_with_lookup( parameter_types, )), }, - ConstExpr::Function { name, args, site } if name == "$isunbounded" => { + ConstExpr::Function { + callee: callee @ Callee::System(SystemFunction::Isunbounded), + args, + site, + } => { if let [ConstExpr::Ident(parameter)] = args.as_slice() && let Some(value) = constants.get(&unbounded_parameter_marker(parameter)) { ConstExpr::Literal(format!("1'b{}", usize::from(*value == 1))) } else { - ConstExpr::Function { name, args, site } + ConstExpr::Function { callee, args, site } } } - ConstExpr::Function { name, args, site } => ConstExpr::Function { - name, + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee, site, args: args .into_iter() @@ -2013,23 +1995,22 @@ fn infer_const_expr_type_inner( width: 1, signed: false, }), - ConstExpr::Function { name, args, .. } => match name.as_str() { - "$signed" | "$unsigned" => { + ConstExpr::Function { + callee: Callee::System(function), + args, + .. + } => match function { + SystemFunction::Signed | SystemFunction::Unsigned => { let [arg] = args.as_slice() else { return None }; let mut ty = infer_const_expr_type_inner(arg, parameter_types, bounded_proof)?; - ty.signed = name == "$signed"; + ty.signed = *function == SystemFunction::Signed; Some(ty) } - "$clog2" | "$countones" | "$countbits" => Some(ExprType { - width: 32, - signed: true, - }), - "$onehot" | "$onehot0" | "$isunknown" | "$isunbounded" => Some(ExprType { - width: 1, - signed: false, - }), - _ => None, + function => function + .result_type() + .map(|(width, signed)| ExprType { width, signed }), }, + ConstExpr::Function { .. } => None, ConstExpr::Unary { op, expr } => { let operand = infer_const_expr_type_inner(expr, parameter_types, bounded_proof)?; if matches!( diff --git a/crates/celox-sv-analyzer/src/ast/parameters/tests.rs b/crates/celox-sv-analyzer/src/ast/parameters/tests.rs index 545007fa3bb..e0fda8a6b0b 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/tests.rs @@ -125,7 +125,7 @@ fn typed_constant_lookup_matches_full_tables_and_visits_only_referenced_names() ), ( ConstExpr::Function { - name: "f".into(), + callee: Callee::Subroutine("f".into()), args: vec![*a(), *b()], site: Some(17), }, @@ -785,7 +785,7 @@ fn retained_parameter_literals_match_separate_resolution_across_types_and_depend right: Box::new(ConstExpr::Literal("8'h0f".into())), }, ConstExpr::Function { - name: "$countones".into(), + callee: Callee::System(SystemFunction::Countones), args: vec![ConstExpr::Literal("8'h81".into())], site: None, }, @@ -1057,7 +1057,7 @@ fn referenced_value_projection_matches_full_environment() { p( "B", ConstExpr::Function { - name: "missing".into(), + callee: Callee::Subroutine("missing".into()), args: vec![id("P")], site: None, }, @@ -1176,7 +1176,7 @@ fn compare_full_and_referenced_parameter_values() { Parameter::new( format!("P{i}"), Some(ConstExpr::Function { - name: "uninstalled".into(), + callee: Callee::Subroutine("uninstalled".into()), args: vec![if i == 0 { ConstExpr::Literal("0".into()) } else { diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 4f5149ea249..eed8a71f83a 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -754,42 +754,41 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { sv_parser::SubroutineCall::SystemTfCall(system_call) => { let (name, args) = system_tf_call_parts(system_call, self.tree) .ok_or_else(|| unsupported("system task or function name"))?; - let tf = system_functions::check_call( + let task = match system_functions::check_call( name, args.as_deref(), system_functions::CallSite::Statement(self.body), - )?; - if name == "$printtimescale" { - return Ok(vec![Stmt::SystemTask { - name: "$display".into(), - args: vec![SystemTaskArg::Str(timescales::print_message( - system_call, - self.tree, - system_functions::CallSite::Statement(self.body), - )?)], - }]); - } - if tf.expression { - // A system function called as a statement is converted - // and checked like the same call in an expression, then - // its value is discarded. `$bits` and `$size` become - // constants and do not evaluate their operands - // (IEEE 1800-2023 20.6.2). - let mut value = expr_from_subroutine_call(call, self.tree, &self.dims)?; - self.rename_expr(&mut value); - return Ok(vec![Stmt::Eval(value)]); - } - let call = system_call; - let (name, args) = match &**call { - sv_parser::SystemTfCall::ArgOptionl(call) => ( - self.tree.get_str(&call.nodes.0.nodes.0), - call.nodes - .1 - .as_ref() - .map(|paren| self.system_task_arguments(&paren.nodes.1)) - .transpose()? - .unwrap_or_default(), - ), + )? { + system_functions::SystemCall::Function(_) => { + // A system function called as a statement is + // converted and checked like the same call in an + // expression, then its value is discarded. `$bits` + // and `$size` become constants and do not evaluate + // their operands (IEEE 1800-2023 20.6.2). + let mut value = expr_from_subroutine_call(call, self.tree, &self.dims)?; + self.rename_expr(&mut value); + return Ok(vec![Stmt::Eval(value)]); + } + system_functions::SystemCall::Task(SystemTask::Printtimescale) => { + return Ok(vec![Stmt::SystemTask { + task: SystemTask::Display(system_functions::Radix::Decimal), + args: vec![SystemTaskArg::Str(timescales::print_message( + system_call, + self.tree, + system_functions::CallSite::Statement(self.body), + )?)], + }]); + } + system_functions::SystemCall::Task(task) => task, + }; + let args = match &**system_call { + sv_parser::SystemTfCall::ArgOptionl(call) => call + .nodes + .1 + .as_ref() + .map(|paren| self.system_task_arguments(&paren.nodes.1)) + .transpose()? + .unwrap_or_default(), sv_parser::SystemTfCall::ArgExpression(call) => { let mut args = Vec::new(); for arg in call.nodes.1.nodes.1.0.contents() { @@ -798,16 +797,15 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { if args.len() == 1 && args[0] == SystemTaskArg::Empty { args.clear(); } - (self.tree.get_str(&call.nodes.0.nodes.0), args) + args } sv_parser::SystemTfCall::ArgDataType(_) => { return Err(unsupported("system task with a data type argument")); } }; - let name = name.ok_or_else(|| unsupported("system task"))?.to_string(); // Keep Veryl's assertion calls as calls: their message arguments // execute even on success, unlike an SV assertion's fail action. - Ok(vec![Stmt::SystemTask { name, args }]) + Ok(vec![Stmt::SystemTask { task, args }]) } _ => Err(unsupported("method or randomize call")), } @@ -1320,7 +1318,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { }; let fail = fail.unwrap_or_else(|| { vec![Stmt::SystemTask { - name: "$error".to_string(), + task: SystemTask::Severity(system_functions::Severity::Error), args: vec![SystemTaskArg::Str(format!("{keyword} failed"))], }] }); diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index a9921807cfe..c6120ed531c 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -564,8 +564,8 @@ impl Renamer<'_> { expr: Box::new(self.const_expr(*expr)), bit: Box::new(self.const_expr(*bit)), }, - ConstExpr::Function { name, args, site } => ConstExpr::Function { - name: self.name(&name), + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee: callee.map_subroutine(|name| self.name(&name)), args: args.into_iter().map(|arg| self.const_expr(arg)).collect(), site, }, @@ -650,12 +650,12 @@ impl Renamer<'_> { else_expr: boxed(else_expr), }, Expr::Call { - name, + callee, args, arg_order, } => Expr::Call { arg_order: arg_order.clone(), - name: self.name(&name), + callee: callee.map_subroutine(|name| self.name(&name)), args: args .into_iter() .map(|arg| arg.map(|arg| self.expr(arg))) diff --git a/crates/celox-sv-analyzer/src/ast/timescales.rs b/crates/celox-sv-analyzer/src/ast/timescales.rs index 94f451ad1e2..18c178acfd1 100644 --- a/crates/celox-sv-analyzer/src/ast/timescales.rs +++ b/crates/celox-sv-analyzer/src/ast/timescales.rs @@ -14,14 +14,16 @@ enum DisplayScope { } struct ResolvedScope { + /// The query or `$printtimescale` call that resolved the scope. + call: system_functions::SystemCall, scale: Scale, display: DisplayScope, is_interface: bool, } impl ResolvedScope { - fn value(&self, name: &str) -> i32 { - if name == "$timeunit" { + fn value(&self) -> i32 { + if self.call == system_functions::SystemCall::Function(SystemFunction::Timeunit) { self.scale.unit } else { self.scale.precision @@ -63,15 +65,24 @@ impl ResolvedScope { .replace('"', "\\\"") } - fn replacement(&self, function: &str, prefix: Option<&str>) -> String { - if function == "$printtimescale" { + fn replacement(&self, prefix: Option<&str>) -> String { + if self.call == system_functions::SystemCall::Task(SystemTask::Printtimescale) { format!("$display(\"{}\")", self.message(prefix)) } else { - format!("32'sh{:08x}", self.value(function) as u32) + format!("32'sh{:08x}", self.value() as u32) } } } +/// Whether `call` is a timescale query or `$printtimescale`, whose argument +/// names a design element instead of a value. +pub(super) fn is_timescale_call(call: &sv_parser::SystemTfCall, tree: &SyntaxTree) -> bool { + matches!( + called_system_function(call, tree), + Some(SystemFunction::Timeunit | SystemFunction::Timeprecision) + ) || called_system_task(call, tree) == Some(SystemTask::Printtimescale) +} + #[derive(Debug, Clone, Copy)] struct Scale { unit: i32, @@ -772,11 +783,8 @@ impl Timescales { tree: &SyntaxTree, unit: &Unit, ) -> Converted { - let name = system_tf_call_parts(call, tree) - .ok_or_else(|| unsupported("timescale query name"))? - .0; self.resolve(call, tree, unit, system_functions::CallSite::Expression) - .map(|scope| scope.value(name)) + .map(|scope| scope.value()) } pub(super) fn interface_path_queries<'a>( @@ -791,11 +799,8 @@ impl Timescales { .ok_or_else(|| unsupported("missing interface query time scope"))?; // Resolve the content key once for this rewrite, not for each query. Ok(move |call: &sv_parser::SystemTfCall, site| { - let name = system_tf_call_parts(call, tree) - .ok_or_else(|| unsupported("timescale query name"))? - .0; self.resolve(call, tree, unit, site) - .map(|scope| scope.is_interface.then(|| scope.replacement(name, None))) + .map(|scope| scope.is_interface.then(|| scope.replacement(None))) }) } @@ -808,7 +813,7 @@ impl Timescales { ) -> Converted { let (name, args) = system_tf_call_parts(call, tree).ok_or_else(|| unsupported("timescale query name"))?; - system_functions::check_call(name, args.as_deref(), site)?; + let checked = system_functions::check_call(name, args.as_deref(), site)?; let at = offset(RefNode::SystemTfCall(call)).unwrap_or_default(); let current = scope_at(&unit.scopes, &unit.parents, at).map(|i| &unit.scopes[i]); let mut interface_target = false; @@ -922,6 +927,7 @@ impl Timescales { } }; Ok(ResolvedScope { + call: checked, scale, display, is_interface: interface_target, @@ -986,17 +992,18 @@ impl Timescales { ) -> Converted { let (name, args) = system_tf_call_parts(call, tree).ok_or_else(|| unsupported("timescale query name"))?; - system_functions::check_call(name, args.as_deref(), site)?; + let checked = system_functions::check_call(name, args.as_deref(), site)?; let scope = self .definitions .get(ty) .ok_or_else(|| unsupported(format!("unknown timescale query design element `{ty}`")))?; Ok(ResolvedScope { + call: checked, scale: scope.scale, display: DisplayScope::Relative(handle.to_string()), is_interface: true, } - .replacement(name, None)) + .replacement(None)) } } diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index a5803570bc3..ff1a9a8f9fc 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -158,20 +158,7 @@ fn validate_folded_parameter_names( } }; if let RefNode::SystemTfCall(call) = node - && system_tf_call_parts(call, tree).is_some_and(|(name, _)| { - matches!( - name, - "$bits" - | "$size" - | "$left" - | "$right" - | "$low" - | "$high" - | "$increment" - | "$dimensions" - | "$unpacked_dimensions" - ) - }) + && called_system_function(call, tree).is_some_and(SystemFunction::is_data_query) && let sv_parser::SystemTfCall::ArgExpression(call) = call { let arguments = call.nodes.1.nodes.1.0.contents(); @@ -406,19 +393,13 @@ fn reject_silently_ignored_constructs_with_dimensions( parameters::reject_unbounded_data_query(call, syntax_tree, const_env, true)?; } if let RefNode::SystemTfCall(call) = child.clone() - && system_tf_call_parts(call, syntax_tree) - .is_some_and(|(name, _)| name == "$isunbounded") + && called_system_function(call, syntax_tree) == Some(SystemFunction::Isunbounded) { - let (name, args) = system_tf_call_parts(call, syntax_tree).unwrap(); - system_functions::check_call( - name, - args.as_deref(), - system_functions::CallSite::Expression, - )?; + let function = expressions::system_function_call(call, syntax_tree)?.unwrap(); let value = parameters::isunbounded_call(call, syntax_tree, const_env)?; if value.is_none() && !procedural_queries.contains(&call) { return Err(AnalyzerError::InvalidSystemTfCall { - name: name.into(), + name: function.name().into(), detail: "argument must name a value parameter".into(), }); } @@ -476,18 +457,17 @@ fn reject_silently_ignored_constructs_with_dimensions( } } match child { - RefNode::SystemTfCall(call) if system_tf_call_parts(call, syntax_tree).is_some_and(|(name, _)| name == "$printtimescale") => { + RefNode::SystemTfCall(call) if called_system_task(call, syntax_tree) == Some(SystemTask::Printtimescale) => { let site = if print_statements.contains(&call) { system_functions::CallSite::Statement(system_functions::Body::Subroutine) } else { system_functions::CallSite::Expression }; timescales::print_message(call, syntax_tree, site)?; } RefNode::SystemTfCall(call) - if system_tf_call_parts(call, syntax_tree).is_some_and(|(name, _)| matches!(name, "$timeunit" | "$timeprecision")) => + if matches!(called_system_function(call, syntax_tree), Some(SystemFunction::Timeunit | SystemFunction::Timeprecision)) => { timescales::query(call, syntax_tree)?; } RefNode::SystemTfCall(call) - if system_tf_call_parts(call, syntax_tree) - .is_some_and(|(name, _)| name == "$bits") + if called_system_function(call, syntax_tree) == Some(SystemFunction::Bits) && !procedural_queries.contains(&call) => { // First preserve diagnostics from the operand's own calls; @@ -495,8 +475,7 @@ fn reject_silently_ignored_constructs_with_dimensions( deferred_bits_queries.push(call); } RefNode::SystemTfCall(call) - if system_tf_call_parts(call, syntax_tree) - .is_some_and(|(name, _)| name == "$dimensions") + if called_system_function(call, syntax_tree) == Some(SystemFunction::Dimensions) && !procedural_queries.contains(&call) => { // Preliminary parameter lowering may defer a type query. @@ -506,8 +485,8 @@ fn reject_silently_ignored_constructs_with_dimensions( ).ok_or_else(|| unsupported(format!("operand of `$dimensions`: {}", syntax_tree.get_str(call).unwrap_or_default())))?; } RefNode::SystemTfCall(call) - if system_tf_call_parts(call, syntax_tree) - .is_some_and(|(name, _)| name == "$unpacked_dimensions") + if called_system_function(call, syntax_tree) + == Some(SystemFunction::UnpackedDimensions) && !procedural_queries.contains(&call) => { // Preliminary parameter lowering may defer a type query. @@ -830,20 +809,7 @@ fn reject_constant_random_calls(node: RefNode<'_>, tree: &SyntaxTree) -> Convert let RefNode::SystemTfCall(call) = child else { continue; }; - if !system_tf_call_parts(call, tree).is_some_and(|(name, _)| { - matches!( - name, - "$bits" - | "$size" - | "$left" - | "$right" - | "$low" - | "$high" - | "$increment" - | "$dimensions" - | "$unpacked_dimensions" - ) - }) { + if !called_system_function(call, tree).is_some_and(SystemFunction::is_data_query) { continue; } let sv_parser::SystemTfCall::ArgExpression(call) = call else { @@ -872,11 +838,11 @@ fn reject_constant_random_calls(node: RefNode<'_>, tree: &SyntaxTree) -> Convert constant.push(in_constant); if in_constant && let RefNode::SystemTfCall(call) = child - && system_tf_call_parts(call, tree).is_some_and(|(name, _)| name == "$urandom") + && called_system_function(call, tree) == Some(SystemFunction::Urandom) && !unevaluated.contains(&(call as *const _)) { return Err(AnalyzerError::InvalidSystemTfCall { - name: "$urandom".into(), + name: SystemFunction::Urandom.name().into(), detail: "not permitted in a constant-value expression".into(), }); } diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 0a464ce998a..b67f9902f10 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -5,6 +5,9 @@ use crate::{ast, symbol::ModuleId, typecheck}; pub use crate::procedural::{ CaseKind, CaseLabel, LoopKind, ParamDirection, StmtBase, SystemTaskArg, }; +pub use crate::system_functions::{ + ArrayQuery, Callee, MemoryFormat, Radix, Severity, SystemFunction, SystemTask, +}; /// A procedural statement of the analyzed IR. pub type Stmt = StmtBase; @@ -666,7 +669,7 @@ pub enum ConstExpr { signed: bool, }, Function { - name: String, + callee: Callee, args: Vec, /// Tells a user subroutine call apart from a call written alike: a /// select repeats its index in its bounds and range checks, and the @@ -974,7 +977,7 @@ pub enum Expr { else_expr: Box, }, Call { - name: String, + callee: Callee, /// Missing actuals retain their formal slots for declaration-scope defaults. args: Vec>, /// Formal positions in source evaluation/copy-out order; empty means positional. @@ -1049,8 +1052,8 @@ impl From for ConstExpr { lsb: Box::new((*lsb).into()), signed, }, - ast::ConstExpr::Function { name, args, site } => ConstExpr::Function { - name, + ast::ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee, site, args: args.into_iter().map(Into::into).collect(), }, @@ -1105,8 +1108,8 @@ impl From for ast::ConstExpr { lsb: Box::new((*lsb).into()), signed, }, - ConstExpr::Function { name, args, site } => ast::ConstExpr::Function { - name, + ConstExpr::Function { callee, args, site } => ast::ConstExpr::Function { + callee, site, args: args.into_iter().map(Into::into).collect(), }, @@ -1309,12 +1312,12 @@ impl From for Expr { else_expr: Box::new((*else_expr).into()), }, ast::Expr::Call { - name, + callee, args, arg_order, } => Expr::Call { arg_order: arg_order.clone(), - name, + callee, args: args.into_iter().map(|arg| arg.map(Into::into)).collect(), }, ast::Expr::Inside { expr, items } => Expr::Inside { diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index 29e73510cb2..f832b8def25 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -7,6 +7,8 @@ //! generic over the expression and lvalue representation so the AST and the IR //! share one definition. +use crate::system_functions::SystemTask; + /// One procedural statement. #[derive(Debug, Clone, PartialEq, Eq)] pub enum StmtBase { @@ -59,7 +61,7 @@ pub enum StmtBase { Eval(E), /// A system task call statement such as `$display`. SystemTask { - name: String, + task: SystemTask, args: Vec>, }, /// The declaration point of a local variable: it is (re)initialized here, @@ -238,8 +240,8 @@ impl StmtBase { args: args.into_iter().map(|arg| arg.map(&mut *fe)).collect(), }, StmtBase::Eval(expr) => StmtBase::Eval(fe(expr)), - StmtBase::SystemTask { name, args } => StmtBase::SystemTask { - name, + StmtBase::SystemTask { task, args } => StmtBase::SystemTask { + task, args: args .into_iter() .map(|arg| match arg { diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 902fecffa83..4f675690537 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -6,9 +6,316 @@ //! frontend cannot lower is reported by name instead of being dropped or //! reported as a generic expression error. Names that are not in the catalog //! are rejected as unknown. +//! +//! A supported call is identified by [`SystemFunction`] or [`SystemTask`] +//! from then on: the IR and the frontend dispatch on these, never on names. + +use std::fmt; use crate::AnalyzerError; +/// A system function the frontend supports. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SystemFunction { + /// `$timeunit` (20.4.2). + Timeunit, + /// `$timeprecision` (20.4.2). + Timeprecision, + /// `$signed` (11.7). + Signed, + /// `$unsigned` (11.7). + Unsigned, + /// `$bits` (20.6.2). + Bits, + /// `$isunbounded` (20.6.3). + Isunbounded, + /// `$dimensions` (20.7). + Dimensions, + /// `$unpacked_dimensions` (20.7). + UnpackedDimensions, + /// `$size` (20.7). + Size, + /// `$left`, `$right`, `$low`, `$high`, `$increment` (20.7). + ArrayQuery(ArrayQuery), + /// `$clog2` (20.8.1). + Clog2, + /// `$countbits` (20.9). + Countbits, + /// `$countones` (20.9). + Countones, + /// `$onehot` (20.9). + Onehot, + /// `$onehot0` (20.9). + Onehot0, + /// `$isunknown` (20.9). + Isunknown, + /// `$urandom` (18.13.1, 20.15.2). + Urandom, +} + +/// An array query function that selects one bound of a dimension (20.7). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ArrayQuery { + Left, + Right, + Low, + High, + Increment, +} + +impl SystemFunction { + /// The name, with its leading `$`. + pub const fn name(self) -> &'static str { + match self { + Self::Timeunit => "$timeunit", + Self::Timeprecision => "$timeprecision", + Self::Signed => "$signed", + Self::Unsigned => "$unsigned", + Self::Bits => "$bits", + Self::Isunbounded => "$isunbounded", + Self::Dimensions => "$dimensions", + Self::UnpackedDimensions => "$unpacked_dimensions", + Self::Size => "$size", + Self::ArrayQuery(ArrayQuery::Left) => "$left", + Self::ArrayQuery(ArrayQuery::Right) => "$right", + Self::ArrayQuery(ArrayQuery::Low) => "$low", + Self::ArrayQuery(ArrayQuery::High) => "$high", + Self::ArrayQuery(ArrayQuery::Increment) => "$increment", + Self::Clog2 => "$clog2", + Self::Countbits => "$countbits", + Self::Countones => "$countones", + Self::Onehot => "$onehot", + Self::Onehot0 => "$onehot0", + Self::Isunknown => "$isunknown", + Self::Urandom => "$urandom", + } + } + + /// The supported function named `name`. + pub fn from_name(name: &str) -> Option { + match lookup(name)?.support { + Support::Function(function) => Some(function), + Support::Task(..) | Support::Unsupported => None, + } + } + + /// The queries of a data object's or type's shape (20.6.2, 20.7), whose + /// operand is not evaluated. + pub fn is_data_query(self) -> bool { + matches!( + self, + Self::Bits + | Self::Size + | Self::Dimensions + | Self::UnpackedDimensions + | Self::ArrayQuery(_) + ) + } + + /// Whether each call has an effect, so that copies of one call made by + /// the analyzer must not run it twice. + pub fn is_effectful(self) -> bool { + self == Self::Urandom + } + + /// The width and signedness of a call that is lowered as an integral + /// operation. `None` for `$signed` and `$unsigned`, whose type follows + /// their operand, and for the data queries, which the analyzer folds to + /// literals where it converts them. + pub fn result_type(self) -> Option<(usize, bool)> { + match self { + Self::Timeunit + | Self::Timeprecision + | Self::Clog2 + | Self::Countbits + | Self::Countones => Some((32, true)), + Self::Onehot | Self::Onehot0 | Self::Isunknown | Self::Isunbounded => Some((1, false)), + Self::Urandom => Some((32, false)), + Self::Signed + | Self::Unsigned + | Self::Bits + | Self::Dimensions + | Self::UnpackedDimensions + | Self::Size + | Self::ArrayQuery(_) => None, + } + } +} + +impl fmt::Display for SystemFunction { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +/// A system task the frontend supports. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SystemTask { + /// `$finish` (20.2). + Finish, + /// `$printtimescale` (20.4.1); the analyzer rewrites it into a + /// [`SystemTask::Display`] of the message. + Printtimescale, + /// `$fatal` (20.10). + Fatal, + /// `$error`, `$warning`, `$info` (20.10). + Severity(Severity), + /// `$display` and its `b`, `o` and `h` variants (21.2.1). + Display(Radix), + /// `$write` and its `b`, `o` and `h` variants (21.2.1). + Write(Radix), + /// `$readmemb` and `$readmemh` (21.4). + Readmem(MemoryFormat), + /// Veryl's immediate assertions, emitted into SystemVerilog as calls of + /// `$assert(condition, message...)`, which ends the simulation when the + /// condition fails, and `$assert_continue`, which reports and continues. + Assert, + AssertContinue, +} + +/// The severity of `$error`, `$warning` and `$info`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Severity { + Error, + Warning, + Info, +} + +/// The number format of a memory file read by `$readmemb` or `$readmemh`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum MemoryFormat { + Binary, + Hexadecimal, +} + +impl MemoryFormat { + /// The base of the numbers in the file. + pub const fn base(self) -> u32 { + match self { + Self::Binary => 2, + Self::Hexadecimal => 16, + } + } +} + +/// The default radix of a display task. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Radix { + Binary, + Octal, + Decimal, + Hexadecimal, +} + +impl Radix { + /// The format letter of the radix, as in `%h`. + pub const fn letter(self) -> char { + match self { + Self::Binary => 'b', + Self::Octal => 'o', + Self::Decimal => 'd', + Self::Hexadecimal => 'h', + } + } +} + +impl SystemTask { + /// The name, with its leading `$`. + pub const fn name(self) -> &'static str { + use Radix::{Binary, Decimal, Hexadecimal, Octal}; + match self { + Self::Finish => "$finish", + Self::Printtimescale => "$printtimescale", + Self::Fatal => "$fatal", + Self::Severity(Severity::Error) => "$error", + Self::Severity(Severity::Warning) => "$warning", + Self::Severity(Severity::Info) => "$info", + Self::Display(Decimal) => "$display", + Self::Display(Binary) => "$displayb", + Self::Display(Octal) => "$displayo", + Self::Display(Hexadecimal) => "$displayh", + Self::Write(Decimal) => "$write", + Self::Write(Binary) => "$writeb", + Self::Write(Octal) => "$writeo", + Self::Write(Hexadecimal) => "$writeh", + Self::Readmem(MemoryFormat::Binary) => "$readmemb", + Self::Readmem(MemoryFormat::Hexadecimal) => "$readmemh", + Self::Assert => "$assert", + Self::AssertContinue => "$assert_continue", + } + } + + /// The supported task named `name`. + pub fn from_name(name: &str) -> Option { + match lookup(name)?.support { + Support::Task(task, _) => Some(task), + Support::Function(_) | Support::Unsupported => None, + } + } +} + +impl fmt::Display for SystemTask { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +/// The subroutine a call expression calls. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum Callee { + /// A user function or a DPI import, by its resolved name. + Subroutine(String), + System(SystemFunction), +} + +impl Callee { + /// The name of the user subroutine, if this is not a system function. + pub fn subroutine(&self) -> Option<&str> { + match self { + Self::Subroutine(name) => Some(name), + Self::System(_) => None, + } + } + + /// The system function, if this is one. + pub fn system(&self) -> Option { + match self { + Self::Subroutine(_) => None, + Self::System(function) => Some(*function), + } + } + + /// The width and signedness of a call of a system function that is + /// lowered as an integral operation; see [`SystemFunction::result_type`]. + pub fn result_type(&self) -> Option<(usize, bool)> { + self.system()?.result_type() + } + + /// Rename a user subroutine with `rename`. + pub fn map_subroutine(self, rename: impl FnOnce(String) -> String) -> Self { + match self { + Self::Subroutine(name) => Self::Subroutine(rename(name)), + Self::System(function) => Self::System(function), + } + } + + /// Whether each call has an effect, so that copies of one call made by + /// the analyzer must not run it twice: user subroutines may have side + /// effects, as does `$urandom`. + pub fn is_effectful(&self) -> bool { + self.system().is_none_or(SystemFunction::is_effectful) + } +} + +impl fmt::Display for Callee { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Subroutine(name) => f.write_str(name), + Self::System(function) => f.write_str(function.name()), + } + } +} + /// Whether IEEE 1800-2023 defines the name as a task, a function, or both. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SystemTfKind { @@ -18,28 +325,34 @@ pub enum SystemTfKind { TaskOrFunction, } -/// Where a call may appear as a statement. +/// Where a supported task may appear as a statement. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum StatementUse { - Unsupported, /// In `always` processes and subroutines, but not in `initial` blocks. Procedural, /// Also in `initial` blocks. ProceduralAndInitial, } +/// How the frontend supports a catalog entry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Support { + Unsupported, + /// A function, in expressions and as a statement whose value is + /// discarded, in any procedural body. + Function(SystemFunction), + /// A task, as a statement where [`StatementUse`] allows. + Task(SystemTask, StatementUse), +} + /// One system task or function. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SystemTf { pub name: &'static str, pub kind: SystemTfKind, - /// Support as a statement. A function called as a statement is evaluated - /// and its value discarded. - pub statement: StatementUse, - /// Support as an expression operand, including constant expressions. - pub expression: bool, - /// The number of arguments Celox accepts, when the call is supported - /// somewhere: at least `min_args`, and at most `max_args` if bounded. + pub support: Support, + /// The number of arguments Celox accepts, when the call is supported: + /// at least `min_args`, and at most `max_args` if bounded. pub min_args: usize, pub max_args: Option, } @@ -47,7 +360,7 @@ pub struct SystemTf { impl SystemTf { /// Whether the call is supported in any position. pub fn is_supported(&self) -> bool { - self.statement != StatementUse::Unsupported || self.expression + self.support != Support::Unsupported } /// "system task" or "system function", for diagnostics about a call in @@ -70,47 +383,43 @@ const fn unsupported(name: &'static str, kind: SystemTfKind) -> SystemTf { SystemTf { name, kind, - statement: StatementUse::Unsupported, - expression: false, + support: Support::Unsupported, min_args: 0, max_args: None, } } -/// A task supported as a statement. +/// A supported task. const fn task( - name: &'static str, + task: SystemTask, statement: StatementUse, min_args: usize, max_args: Option, ) -> SystemTf { SystemTf { - name, + name: task.name(), kind: Task, - statement, - expression: false, + support: Support::Task(task, statement), min_args, max_args, } } -/// A function supported in expressions, and as a statement whose value is -/// discarded. -const fn function(name: &'static str, min_args: usize, max_args: usize) -> SystemTf { +/// A supported function. +const fn function(function: SystemFunction, min_args: usize, max_args: Option) -> SystemTf { SystemTf { - name, + name: function.name(), kind: Function, - statement: ProceduralAndInitial, - expression: true, + support: Support::Function(function), min_args, - max_args: Some(max_args), + max_args, } } /// The catalog, in the order of IEEE 1800-2023 clauses 20 and 21. pub const SYSTEM_TFS: &[SystemTf] = &[ // 20.2 Simulation control system tasks - task("$finish", ProceduralAndInitial, 0, Some(1)), + task(SystemTask::Finish, ProceduralAndInitial, 0, Some(1)), unsupported("$stop", Task), unsupported("$exit", Task), // 20.3 Simulation time system functions @@ -118,10 +427,10 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$stime", Function), unsupported("$realtime", Function), // 20.4 Timescale system tasks and system functions - task("$printtimescale", ProceduralAndInitial, 0, Some(1)), + task(SystemTask::Printtimescale, ProceduralAndInitial, 0, Some(1)), unsupported("$timeformat", Task), - function("$timeunit", 0, 1), - function("$timeprecision", 0, 1), + function(SystemFunction::Timeunit, 0, Some(1)), + function(SystemFunction::Timeprecision, 0, Some(1)), // 20.5 Conversion functions unsupported("$rtoi", Function), unsupported("$itor", Function), @@ -130,25 +439,29 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$shortrealtobits", Function), unsupported("$bitstoshortreal", Function), // 11.7 Signed expressions - function("$signed", 1, 1), - function("$unsigned", 1, 1), + function(SystemFunction::Signed, 1, Some(1)), + function(SystemFunction::Unsigned, 1, Some(1)), // 6.24.2 Dynamic casting unsupported("$cast", TaskOrFunction), // 20.6 Data query functions unsupported("$typename", Function), - function("$bits", 1, 1), - function("$isunbounded", 1, 1), + function(SystemFunction::Bits, 1, Some(1)), + function(SystemFunction::Isunbounded, 1, Some(1)), // 20.7 Array query functions - function("$dimensions", 1, 1), - function("$unpacked_dimensions", 1, 1), - function("$left", 1, 2), - function("$right", 1, 2), - function("$low", 1, 2), - function("$high", 1, 2), - function("$increment", 1, 2), - function("$size", 1, 2), + function(SystemFunction::Dimensions, 1, Some(1)), + function(SystemFunction::UnpackedDimensions, 1, Some(1)), + function(SystemFunction::ArrayQuery(ArrayQuery::Left), 1, Some(2)), + function(SystemFunction::ArrayQuery(ArrayQuery::Right), 1, Some(2)), + function(SystemFunction::ArrayQuery(ArrayQuery::Low), 1, Some(2)), + function(SystemFunction::ArrayQuery(ArrayQuery::High), 1, Some(2)), + function( + SystemFunction::ArrayQuery(ArrayQuery::Increment), + 1, + Some(2), + ), + function(SystemFunction::Size, 1, Some(2)), // 20.8 Math functions - function("$clog2", 1, 1), + function(SystemFunction::Clog2, 1, Some(1)), unsupported("$ln", Function), unsupported("$log10", Function), unsupported("$exp", Function), @@ -171,19 +484,31 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$acosh", Function), unsupported("$atanh", Function), // 20.9 Bit vector system functions - SystemTf { - max_args: None, - ..function("$countbits", 2, 2) - }, - function("$countones", 1, 1), - function("$onehot", 1, 1), - function("$onehot0", 1, 1), - function("$isunknown", 1, 1), + function(SystemFunction::Countbits, 2, None), + function(SystemFunction::Countones, 1, Some(1)), + function(SystemFunction::Onehot, 1, Some(1)), + function(SystemFunction::Onehot0, 1, Some(1)), + function(SystemFunction::Isunknown, 1, Some(1)), // 20.10 Severity tasks (and 20.11 elaboration system tasks) - task("$fatal", ProceduralAndInitial, 0, None), - task("$error", ProceduralAndInitial, 0, None), - task("$warning", ProceduralAndInitial, 0, None), - task("$info", ProceduralAndInitial, 0, None), + task(SystemTask::Fatal, ProceduralAndInitial, 0, None), + task( + SystemTask::Severity(Severity::Error), + ProceduralAndInitial, + 0, + None, + ), + task( + SystemTask::Severity(Severity::Warning), + ProceduralAndInitial, + 0, + None, + ), + task( + SystemTask::Severity(Severity::Info), + ProceduralAndInitial, + 0, + None, + ), // 20.12 Assertion control system tasks unsupported("$asserton", Task), unsupported("$assertoff", Task), @@ -223,7 +548,7 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$load_coverage_db", Task), // 20.15 Probabilistic distribution functions unsupported("$random", Function), - function("$urandom", 0, 1), + function(SystemFunction::Urandom, 0, Some(1)), unsupported("$urandom_range", Function), unsupported("$dist_uniform", Function), unsupported("$dist_normal", Function), @@ -258,14 +583,54 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ // 20.18 Miscellaneous tasks and functions unsupported("$system", TaskOrFunction), // 21.2 Display system tasks - task("$display", ProceduralAndInitial, 0, None), - task("$displayb", ProceduralAndInitial, 0, None), - task("$displayo", ProceduralAndInitial, 0, None), - task("$displayh", ProceduralAndInitial, 0, None), - task("$write", ProceduralAndInitial, 0, None), - task("$writeb", ProceduralAndInitial, 0, None), - task("$writeo", ProceduralAndInitial, 0, None), - task("$writeh", ProceduralAndInitial, 0, None), + task( + SystemTask::Display(Radix::Decimal), + ProceduralAndInitial, + 0, + None, + ), + task( + SystemTask::Display(Radix::Binary), + ProceduralAndInitial, + 0, + None, + ), + task( + SystemTask::Display(Radix::Octal), + ProceduralAndInitial, + 0, + None, + ), + task( + SystemTask::Display(Radix::Hexadecimal), + ProceduralAndInitial, + 0, + None, + ), + task( + SystemTask::Write(Radix::Decimal), + ProceduralAndInitial, + 0, + None, + ), + task( + SystemTask::Write(Radix::Binary), + ProceduralAndInitial, + 0, + None, + ), + task( + SystemTask::Write(Radix::Octal), + ProceduralAndInitial, + 0, + None, + ), + task( + SystemTask::Write(Radix::Hexadecimal), + ProceduralAndInitial, + 0, + None, + ), unsupported("$strobe", Task), unsupported("$strobeb", Task), unsupported("$strobeo", Task), @@ -314,8 +679,18 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$ferror", Function), unsupported("$feof", Function), // 21.4 Loading memory array data from a file - task("$readmemb", ProceduralAndInitial, 2, Some(4)), - task("$readmemh", ProceduralAndInitial, 2, Some(4)), + task( + SystemTask::Readmem(MemoryFormat::Binary), + ProceduralAndInitial, + 2, + Some(4), + ), + task( + SystemTask::Readmem(MemoryFormat::Hexadecimal), + ProceduralAndInitial, + 2, + Some(4), + ), // 21.5 Writing memory array data to a file unsupported("$writememb", Task), unsupported("$writememh", Task), @@ -339,17 +714,11 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ // Veryl's immediate assertions, emitted into SystemVerilog as calls of // these names: `$assert(condition, message...)` ends the simulation when // the condition fails and `$assert_continue` reports and continues. - task("$assert", Procedural, 1, None), - task("$assert_continue", Procedural, 1, None), + task(SystemTask::Assert, Procedural, 1, None), + task(SystemTask::AssertContinue, Procedural, 1, None), ]; /// The catalog entry for `name`, which includes the leading `$`. -/// Whether `name` names a system task or function, `$f`, rather than an -/// item of the compilation unit, `$unit::f`. -pub fn is_system_name(name: &str) -> bool { - name.starts_with('$') && !name.starts_with("$unit::") -} - pub fn lookup(name: &str) -> Option<&'static SystemTf> { SYSTEM_TFS.iter().find(|tf| tf.name == name) } @@ -382,44 +751,58 @@ pub enum Arg { Omitted, } -/// Check a call of `name` with `args` at `site` and return its entry. +/// A supported system task or function, as [`check_call`] identifies a call. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SystemCall { + Function(SystemFunction), + Task(SystemTask), +} + +impl SystemCall { + /// The function, for a call in expression position. + pub fn function(self) -> Option { + match self { + Self::Function(function) => Some(function), + Self::Task(_) => None, + } + } +} + +/// Check a call of `name` with `args` at `site` and identify it. /// /// `args` is `None` for a call that binds its arguments by name. pub fn check_call( name: &str, args: Option<&[Arg]>, site: CallSite, -) -> Result<&'static SystemTf, AnalyzerError> { +) -> Result { let tf = lookup(name).ok_or_else(|| AnalyzerError::UnknownSystemTf { name: name.to_string(), })?; - let statement = matches!(site, CallSite::Statement(_)); - let noun = tf.noun(statement); - match site { - CallSite::Statement(body) => match tf.statement { - StatementUse::Unsupported => { - return Err(AnalyzerError::Unsupported(format!("{noun} `{name}`"))); - } - StatementUse::Procedural if body == Body::Initial => { - return Err(AnalyzerError::Unsupported(format!( - "{noun} `{name}` inside an initial block" - ))); - } - StatementUse::Procedural | StatementUse::ProceduralAndInitial => {} - }, - CallSite::Expression if tf.kind == Task => { + let noun = tf.noun(matches!(site, CallSite::Statement(_))); + let checked = match (site, tf.support) { + (CallSite::Expression, _) if tf.kind == Task => { return Err(AnalyzerError::InvalidSystemTfCall { name: name.to_string(), detail: "a system task has no value".to_string(), }); } - CallSite::Expression if !tf.expression => { + (CallSite::Statement(_), Support::Unsupported) => { + return Err(AnalyzerError::Unsupported(format!("{noun} `{name}`"))); + } + (CallSite::Expression, Support::Unsupported | Support::Task(..)) => { return Err(AnalyzerError::Unsupported(format!( "{noun} `{name}` in an expression" ))); } - CallSite::Expression => {} - } + (CallSite::Statement(Body::Initial), Support::Task(_, Procedural)) => { + return Err(AnalyzerError::Unsupported(format!( + "{noun} `{name}` inside an initial block" + ))); + } + (CallSite::Statement(_), Support::Task(task, _)) => SystemCall::Task(task), + (_, Support::Function(function)) => SystemCall::Function(function), + }; let Some(args) = args else { return Err(AnalyzerError::Unsupported(format!( "named arguments of `{name}`" @@ -442,7 +825,19 @@ pub fn check_call( detail: format!("argument {} is omitted", position + 1), }); } - Ok(tf) + Ok(checked) +} + +/// Check a call of `name` with `args` in expression position and identify +/// the function. +pub fn check_function_call( + name: &str, + args: Option<&[Arg]>, +) -> Result { + match check_call(name, args, CallSite::Expression)? { + SystemCall::Function(function) => Ok(function), + SystemCall::Task(_) => unreachable!("a task is rejected in expression position"), + } } fn expected_arguments(tf: &SystemTf) -> String { @@ -471,20 +866,19 @@ mod tests { } #[test] - fn functions_are_supported_in_expressions_and_statements_together() { - // A function called as a statement is evaluated as an expression, so - // it is supported as a statement exactly when it is in expressions. - for tf in SYSTEM_TFS.iter().filter(|tf| tf.kind == Function) { - assert_eq!( - tf.expression, - tf.statement != StatementUse::Unsupported, - "{}", - tf.name - ); - } - // Tasks have no value. - for tf in SYSTEM_TFS.iter().filter(|tf| tf.kind == Task) { - assert!(!tf.expression, "{}", tf.name); + fn supported_entries_round_trip_through_their_names() { + for tf in SYSTEM_TFS { + match tf.support { + Support::Function(function) => { + assert_eq!(tf.kind, Function, "{}", tf.name); + assert_eq!(SystemFunction::from_name(tf.name), Some(function)); + } + Support::Task(task, _) => { + assert_eq!(tf.kind, Task, "{}", tf.name); + assert_eq!(SystemTask::from_name(tf.name), Some(task)); + } + Support::Unsupported => {} + } } } } diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 2459d47f6da..b7f22392912 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -3612,7 +3612,7 @@ fn package_functions_give_shapes_to_instance_connections() { .unwrap(); let connection = &top.instances()[0].port_connections()[0]; assert!( - matches!(connection.actual_expr(), Some(ir::Expr::Call { name, .. }) if name == "p::sum"), + matches!(connection.actual_expr(), Some(ir::Expr::Call { callee: ir::Callee::Subroutine(name), .. }) if name == "p::sum"), "{connection:?}" ); } diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index 568500ee22a..cdd8261f15f 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -4,7 +4,7 @@ use fxhash::FxHashMap as HashMap; use num_bigint::BigUint; -use crate::ir::{BinaryOp, ConstExpr, PackedRange, UnaryOp}; +use crate::ir::{BinaryOp, Callee, ConstExpr, PackedRange, SystemFunction, UnaryOp}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct IntegralLiteral { @@ -53,27 +53,6 @@ impl std::fmt::Display for UnpackedArrayType { } } -/// Width and signedness of the supported integral system functions. -pub fn bit_vector_function_return_type(name: &str, arity: usize) -> Option<(usize, bool)> { - if name == "$urandom" { - return (arity <= 1).then_some((32, false)); - } - if matches!(name, "$timeunit" | "$timeprecision") { - return (arity <= 1).then_some((32, true)); - } - if name == "$countbits" { - return (arity >= 2).then_some((32, true)); - } - if arity != 1 { - return None; - } - match name { - "$countones" | "$clog2" => Some((32, true)), - "$onehot" | "$onehot0" | "$isunknown" | "$isunbounded" => Some((1, false)), - _ => None, - } -} - pub fn resolve_packed_width(ranges: &[PackedRange]) -> Option { resolve_packed_width_with_env(ranges, &HashMap::default()) } @@ -212,7 +191,12 @@ pub(crate) fn eval_const_expr_in_env( let bit = u32::try_from(bit).ok()?; value.checked_shr(bit).map(|value| value & 1) } - ConstExpr::Function { name, args, .. } => eval_const_function(name, args, constants), + ConstExpr::Function { callee, args, .. } => match callee { + Callee::Subroutine(name) => { + crate::ast::const_functions::eval_call(name, args, constants) + } + Callee::System(function) => eval_system_function(*function, args, constants), + }, ConstExpr::Unary { op, expr: operand } => { if let Some(result) = integral_literal_from_const_expr(expr) && let Some(value) = integral_literal_as_i128(&result, result.signed) @@ -522,8 +506,8 @@ fn substitute_typed_constants_with_lookup( *bit, constants, types, )), }, - ConstExpr::Function { name, args, site } => ConstExpr::Function { - name, + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee, site, args: args .into_iter() @@ -1005,23 +989,25 @@ fn integral_literal_from_const_expr(expr: &ConstExpr) -> Option let extension = signed_extension(&operand, operand.signed); Some(resize_integral_literal(operand, *width, *signed, extension)) } - ConstExpr::Function { name, args, .. } => { - if matches!(name.as_str(), "$signed" | "$unsigned") { + // User functions are evaluated by the numeric fallback with the + // caller's environment. + ConstExpr::Function { + callee: Callee::System(function), + args, + .. + } => { + if let SystemFunction::Signed | SystemFunction::Unsigned = function { let [arg] = args.as_slice() else { return None }; let mut literal = self_determined_integral_literal(arg)?; - literal.signed = name == "$signed"; + literal.signed = *function == SystemFunction::Signed; return Some(literal); } - // Check support before executing: user functions are evaluated - // by the numeric fallback with the caller's environment. - let (width, signing) = match name.as_str() { - "$clog2" | "$countones" | "$countbits" => (32, "s"), - "$onehot" | "$onehot0" | "$isunknown" => (1, ""), - _ => return None, - }; - let value = eval_const_function(name, args, &HashMap::default())?; + let (width, signed) = function.result_type()?; + let value = eval_system_function(*function, args, &HashMap::default())?; + let signing = if signed { "s" } else { "" }; parse_integral_literal(&format!("{width}'{signing}d{value}")) } + ConstExpr::Function { .. } => None, ConstExpr::SelectRange { expr, msb, @@ -1346,15 +1332,13 @@ fn signed_extension(literal: &IntegralLiteral, signed: bool) -> (bool, bool) { (literal.value.bit(sign_bit), literal.mask.bit(sign_bit)) } -fn eval_const_function( - name: &str, +/// The value of a call of a system function with constant arguments. +fn eval_system_function( + function: SystemFunction, args: &[ConstExpr], constants: &dyn ConstantEnvironment, ) -> Option { - if !crate::system_functions::is_system_name(name) { - return crate::ast::const_functions::eval_call(name, args, constants); - } - if name == "$countbits" { + if function == SystemFunction::Countbits { let (arg, controls) = args.split_first()?; if controls.is_empty() { return None; @@ -1388,29 +1372,26 @@ fn eval_const_function( let [arg] = args else { return None; }; - match name { - "$signed" | "$unsigned" => { + let ones = || { + let value = const_expr_known_one_bits(arg, constants)?; + Some(value.iter_u64_digits().map(u64::count_ones).sum::()) + }; + match function { + SystemFunction::Signed | SystemFunction::Unsigned => { let literal = self_determined_integral_literal(arg)?; - integral_literal_as_i128(&literal, name == "$signed") + integral_literal_as_i128(&literal, function == SystemFunction::Signed) } - "$clog2" => clog2(eval_const_expr_in_env(arg, constants)?), - "$isunknown" => { + SystemFunction::Clog2 => clog2(eval_const_expr_in_env(arg, constants)?), + SystemFunction::Isunknown => { if let Some(literal) = self_determined_integral_literal(arg) { Some((literal.mask != BigUint::default()) as i128) } else { eval_const_expr_in_env(arg, constants).map(|_| 0) } } - "$countones" | "$onehot" | "$onehot0" => { - let value = const_expr_known_one_bits(arg, constants)?; - let ones = value.iter_u64_digits().map(u64::count_ones).sum::(); - Some(match name { - "$countones" => ones as i32 as i128, - "$onehot" => (ones == 1) as i128, - "$onehot0" => (ones <= 1) as i128, - _ => unreachable!(), - }) - } + SystemFunction::Countones => Some(ones()? as i32 as i128), + SystemFunction::Onehot => Some((ones()? == 1) as i128), + SystemFunction::Onehot0 => Some((ones()? <= 1) as i128), _ => None, } } diff --git a/crates/celox/src/simulator/mixed.rs b/crates/celox/src/simulator/mixed.rs index 8158591d976..ab2592c6331 100644 --- a/crates/celox/src/simulator/mixed.rs +++ b/crates/celox/src/simulator/mixed.rs @@ -117,14 +117,14 @@ fn const_expr(expr: &sv::ConstExpr) -> Result { }; format!("({op}{})", const_expr(expr)?) } - sv::ConstExpr::Function { name, args, .. } => { - if !name.starts_with('$') { + sv::ConstExpr::Function { callee, args, .. } => { + let sv::Callee::System(function) = callee else { return Err(unsupported(format!( - "header-dependent SV constant function `{name}` without an expression body" + "header-dependent SV constant function `{callee}` without an expression body" ))); - } + }; format!( - "{name}({})", + "{function}({})", args.iter() .map(const_expr) .collect::, _>>()? @@ -189,9 +189,6 @@ fn depends_on_header(expr: &sv::ConstExpr, signature: &InterfaceSignature) -> bo signature: &InterfaceSignature, visited: &mut fxhash::FxHashSet, ) -> bool { - if name.starts_with('$') { - return false; - } if !visited.insert(name.to_string()) { return false; } @@ -338,8 +335,10 @@ fn depends_on_header(expr: &sv::ConstExpr, signature: &InterfaceSignature) -> bo || expression(then_expr, signature, visited) || expression(else_expr, signature, visited) } - Call { name, args, .. } => { - function(name, signature, visited) + Call { callee, args, .. } => { + callee + .subroutine() + .is_some_and(|name| function(name, signature, visited)) || args .iter() .flatten() @@ -394,8 +393,10 @@ fn depends_on_header(expr: &sv::ConstExpr, signature: &InterfaceSignature) -> bo || visit(msb, signature, visited) || visit(lsb, signature, visited) } - Function { name, args, .. } => { - function(name, signature, visited) + Function { callee, args, .. } => { + callee + .subroutine() + .is_some_and(|name| function(name, signature, visited)) || args.iter().any(|arg| visit(arg, signature, visited)) } Mux {