From 04714a7d4917e08f79b771e0f1176df7387845ac Mon Sep 17 00:00:00 2001 From: guipublic <47281315+guipublic@users.noreply.github.com> Date: Mon, 6 Jan 2025 22:30:32 +0100 Subject: [PATCH] chore: simplify boolean in a mul of a mul (#6951) Co-authored-by: Tom French <15848336+TomAFrench@users.noreply.github.com> --- .../src/ssa/ir/instruction/binary.rs | 36 ++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/compiler/noirc_evaluator/src/ssa/ir/instruction/binary.rs b/compiler/noirc_evaluator/src/ssa/ir/instruction/binary.rs index ce65343c7ef..ab37080ac1d 100644 --- a/compiler/noirc_evaluator/src/ssa/ir/instruction/binary.rs +++ b/compiler/noirc_evaluator/src/ssa/ir/instruction/binary.rs @@ -131,11 +131,39 @@ impl Binary { let zero = dfg.make_constant(FieldElement::zero(), operand_type); return SimplifyResult::SimplifiedTo(zero); } - if dfg.resolve(self.lhs) == dfg.resolve(self.rhs) - && dfg.get_value_max_num_bits(self.lhs) == 1 - { + if dfg.get_value_max_num_bits(self.lhs) == 1 { // Squaring a boolean value is a noop. - return SimplifyResult::SimplifiedTo(self.lhs); + if dfg.resolve(self.lhs) == dfg.resolve(self.rhs) { + return SimplifyResult::SimplifiedTo(self.lhs); + } + // b*(b*x) = b*x if b is boolean + if let super::Value::Instruction { instruction, .. } = &dfg[self.rhs] { + if let Instruction::Binary(Binary { lhs, rhs, operator }) = + dfg[*instruction] + { + if operator == BinaryOp::Mul + && (dfg.resolve(self.lhs) == dfg.resolve(lhs) + || dfg.resolve(self.lhs) == dfg.resolve(rhs)) + { + return SimplifyResult::SimplifiedTo(self.rhs); + } + } + } + } + // (b*x)*b = b*x if b is boolean + if dfg.get_value_max_num_bits(self.rhs) == 1 { + if let super::Value::Instruction { instruction, .. } = &dfg[self.lhs] { + if let Instruction::Binary(Binary { lhs, rhs, operator }) = + dfg[*instruction] + { + if operator == BinaryOp::Mul + && (dfg.resolve(self.rhs) == dfg.resolve(lhs) + || dfg.resolve(self.rhs) == dfg.resolve(rhs)) + { + return SimplifyResult::SimplifiedTo(self.lhs); + } + } + } } } BinaryOp::Div => {