Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: constant folding for logic extension #793

Merged
merged 1 commit into from
Jan 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion src/algorithm/const_fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,14 +217,15 @@ pub fn constant_fold_pass(h: &mut impl HugrMut, reg: &ExtensionRegistry) {
mod test {

use super::*;
use crate::extension::prelude::sum_with_error;
use crate::extension::prelude::{sum_with_error, BOOL_T};
use crate::extension::{ExtensionRegistry, PRELUDE};
use crate::ops::OpType;
use crate::std_extensions::arithmetic;
use crate::std_extensions::arithmetic::conversions::ConvertOpDef;
use crate::std_extensions::arithmetic::float_ops::FloatOps;
use crate::std_extensions::arithmetic::float_types::{ConstF64, FLOAT64_TYPE};
use crate::std_extensions::arithmetic::int_types::{ConstIntU, INT_TYPES};
use crate::std_extensions::logic::{self, const_from_bool, NaryLogic};
use rstest::rstest;

/// int to constant
Expand Down Expand Up @@ -306,6 +307,31 @@ mod test {
let expected = Const::new(expected, sum_type).unwrap();
assert_fully_folded(&h, &expected);
}

#[rstest]
#[case(NaryLogic::And, [true, true, true], true)]
#[case(NaryLogic::And, [true, false, true], false)]
#[case(NaryLogic::Or, [false, false, true], true)]
#[case(NaryLogic::Or, [false, false, false], false)]
fn test_logic_and(
#[case] op: NaryLogic,
#[case] ins: [bool; 3],
#[case] out: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let mut build = DFGBuilder::new(FunctionType::new(type_row![], vec![BOOL_T])).unwrap();

let ins = ins.map(|b| build.add_load_const(const_from_bool(b)).unwrap());
let logic_op = build.add_dataflow_op(op.with_n_inputs(ins.len() as u64), ins)?;

let reg =
ExtensionRegistry::try_new([PRELUDE.to_owned(), logic::EXTENSION.to_owned()]).unwrap();
let mut h = build.finish_hugr_with_outputs(logic_op.outputs(), &reg)?;
constant_fold_pass(&mut h, &reg);

assert_fully_folded(&h, &const_from_bool(out));
Ok(())
}

fn assert_fully_folded(h: &Hugr, expected_const: &Const) {
// check the hugr just loads and returns a single const
let mut node_count = 0;
Expand Down
45 changes: 44 additions & 1 deletion src/std_extensions/logic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use strum_macros::{EnumIter, EnumString, IntoStaticStr};

use crate::{
algorithm::const_fold::sorted_consts,
extension::{
prelude::BOOL_T,
simple_op::{try_from_name, MakeExtensionOp, MakeOpDef, MakeRegisteredOp, OpLoadError},
Expand All @@ -14,7 +15,7 @@ use crate::{
type_param::{TypeArg, TypeParam},
FunctionType,
},
Extension,
Extension, IncomingPort,
};
use lazy_static::lazy_static;
/// Name of extension false value.
Expand Down Expand Up @@ -46,6 +47,21 @@ impl MakeOpDef for NaryLogic {
fn from_def(op_def: &OpDef) -> Result<Self, OpLoadError> {
try_from_name(op_def.name())
}

fn post_opdef(&self, def: &mut OpDef) {
def.set_constant_folder(match self {
NaryLogic::And => |consts: &_| {
let inps = read_inputs(consts)?;
let res = inps.into_iter().all(|x| x);
Some(vec![(0.into(), const_from_bool(res))])
},
NaryLogic::Or => |consts: &_| {
let inps = read_inputs(consts)?;
let res = inps.into_iter().any(|x| x);
Some(vec![(0.into(), const_from_bool(res))])
},
})
}
}

/// Make a [NaryLogic] operation concrete by setting the type argument.
Expand Down Expand Up @@ -171,6 +187,33 @@ impl MakeRegisteredOp for NotOp {
}
}

fn read_inputs(consts: &[(IncomingPort, ops::Const)]) -> Option<Vec<bool>> {
let true_val = ops::Const::true_val();
let false_val = ops::Const::false_val();
let inps: Option<Vec<bool>> = sorted_consts(consts)
.into_iter()
.map(|c| {
if c == &true_val {
Some(true)
} else if c == &false_val {
Some(false)
} else {
None
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This must be correct (since it compiles), but it looks like it's making a vector of optional bools rather than an optional vector of bools... what am I missing?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

collect is able to make that conversion from the iterator of optionals

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah OK!

}
})
.collect();
let inps = inps?;
Some(inps)
}

pub(crate) fn const_from_bool(res: bool) -> ops::Const {
if res {
ops::Const::true_val()
} else {
ops::Const::false_val()
}
}

#[cfg(test)]
pub(crate) mod test {
use super::{extension, ConcreteLogicOp, NaryLogic, NotOp, FALSE_NAME, TRUE_NAME};
Expand Down
Loading