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

fix: Implement constant folding during the mem2reg pass #2464

Merged
merged 20 commits into from
Aug 30, 2023
Merged
Show file tree
Hide file tree
Changes from 7 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "references"
type = "bin"
authors = [""]
compiler_version = "0.5.1"

[dependencies]
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
fn main() {
let mut x = 100;
let mut xref = &mut x;
increment(xref);
assert(*xref == 101);

regression_2445();
}

fn increment(mut r: &mut Field) {
*r = *r + 1;
}

// If aliasing within arrays and constant folding within the mem2reg pass aren't
// handled, we'll fail to optimize out all the references in this function.
fn regression_2445() {
let mut var = 0;
let ref = &mut &mut var;

let mut array = [ref, ref];

**array[0] = 1;
**array[1] = 2;

assert(var == 2);
assert(**ref == 2);
assert(**array[0] == 2);
assert(**array[1] == 2);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
H4sIAAAAAAAA/+1c8ZONVRh+WCKykYqIiFRE37f37u5dkY2IEEJEtLv2bkJKQkpCSkJKIjLGNE3TmJqpmZqpmZrRH9L/Uu907szZzfjlPO+Z98yc88u+w8yz3/O853ue93zf3fsXgL/x/zXY/ex0P4uwVQ7ysCpFW7Vab2+pl5Wyu2jp6Km1FtXWnrZaWStba629LbVKpV6r1to7ejrai46yWqmXfa0dlT4HNpiAVe/7bzX9izHoJvwHkfkP5mEV/vU2efWQAb3z//82BU4Y8HsG6th8k3+j/nKNJjUp4A4Bb/Nr8R7C71HhQZrXtLEsG99QpGd8Q6FjfLd5dTa+QMyhSkINg23jE97D+D1SNT62po1l2fiGIz3jGw4d47vdq7PxBWIOd4KycU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AnMU/JPqL+DubzZveVp0RIH3r9C5r9kn9NNELYm9LrX0szxonQFr0Ip3Qj8DnUHrU6/Og1Yg5hknKBv3LGwPWsL7LL9HyZzQP4POTcHmzNxHn0fiXIQtanCcAys44p3Qz0EnOL7w6hwcgZjnnKBs3POwHRzC+zy/R6rBwTTRL5FGcDD30QUeZ5UTujyBOQ3+SfU3cPc3m7c8LTqlwPt36NzX7BP6RaKWxF6XWvpZHqi/gu28lgy4qHCv/AHbHiF5dUGB959IwyMuEbUk9rpk68feN3I/X1LYNzcQZ98UQausdhE5Xyb25QbhumJ/1zWRf78D7ddenQ+0gZiXnaBs3CuwfaAV3lf4PVL9rmumpoMGXKO//gGokXOuaucAAA==
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -1081,7 +1081,7 @@ impl<'block> BrilligBlock<'block> {
/// Returns the type of the operation considering the types of the operands
/// TODO: SSA issues binary operations between fields and integers.
/// This probably should be explicitly casted in SSA to avoid having to coerce at this level.
pub(crate) fn type_of_binary_operation(lhs_type: Type, rhs_type: Type) -> Type {
pub(crate) fn type_of_binary_operation(lhs_type: &Type, rhs_type: &Type) -> Type {
match (lhs_type, rhs_type) {
(_, Type::Function) | (Type::Function, _) => {
unreachable!("Functions are invalid in binary operations")
Expand All @@ -1098,15 +1098,15 @@ pub(crate) fn type_of_binary_operation(lhs_type: Type, rhs_type: Type) -> Type {
// If either side is a Field constant then, we coerce into the type
// of the other operand
(Type::Numeric(NumericType::NativeField), typ)
| (typ, Type::Numeric(NumericType::NativeField)) => typ,
| (typ, Type::Numeric(NumericType::NativeField)) => typ.clone(),
// If both sides are numeric type, then we expect their types to be
// the same.
(Type::Numeric(lhs_type), Type::Numeric(rhs_type)) => {
assert_eq!(
lhs_type, rhs_type,
"lhs and rhs types in a binary operation are always the same"
);
Type::Numeric(lhs_type)
Type::Numeric(*lhs_type)
}
}
}
Expand Down
21 changes: 14 additions & 7 deletions crates/noirc_evaluator/src/ssa/ir/dfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ impl DataFlowGraph {
let parameters = self.blocks[block].parameters();

let parameters = vecmap(parameters.iter().enumerate(), |(position, param)| {
let typ = self.values[*param].get_type();
let typ = self.values[*param].get_type().clone();
self.values.insert(Value::Param { block: new_block, position, typ })
});

Expand Down Expand Up @@ -171,7 +171,7 @@ impl DataFlowGraph {
let id = self.make_instruction(instruction, ctrl_typevars);
self.blocks[block].insert_instruction(id);
self.locations.insert(id, call_stack);
InsertInstructionResult::Results(self.instruction_results(id))
InsertInstructionResult::Results(id, self.instruction_results(id))
}
}
}
Expand Down Expand Up @@ -314,7 +314,13 @@ impl DataFlowGraph {

/// Returns the type of a given value
pub(crate) fn type_of_value(&self, value: ValueId) -> Type {
self.values[value].get_type()
self.values[value].get_type().clone()
}

/// True if the type of this value is Type::Reference.
/// Using this method over type_of_value avoids cloning the value's type.
pub(crate) fn value_is_reference(&self, value: ValueId) -> bool {
matches!(self.values[value].get_type(), Type::Reference)
}

/// Appends a result type to the instruction.
Expand Down Expand Up @@ -472,7 +478,8 @@ impl std::ops::IndexMut<BasicBlockId> for DataFlowGraph {
// be a list of results or a single ValueId if the instruction was simplified
// to an existing value.
pub(crate) enum InsertInstructionResult<'dfg> {
Results(&'dfg [ValueId]),
/// Results is the standard case containing the instruction id and the results of that instruction.
Results(InstructionId, &'dfg [ValueId]),
SimplifiedTo(ValueId),
SimplifiedToMultiple(Vec<ValueId>),
InstructionRemoved,
Expand All @@ -484,7 +491,7 @@ impl<'dfg> InsertInstructionResult<'dfg> {
match self {
InsertInstructionResult::SimplifiedTo(value) => *value,
InsertInstructionResult::SimplifiedToMultiple(values) => values[0],
InsertInstructionResult::Results(results) => results[0],
InsertInstructionResult::Results(_, results) => results[0],
InsertInstructionResult::InstructionRemoved => {
panic!("Instruction was removed, no results")
}
Expand All @@ -495,7 +502,7 @@ impl<'dfg> InsertInstructionResult<'dfg> {
/// This is used for instructions returning multiple results like function calls.
pub(crate) fn results(self) -> Cow<'dfg, [ValueId]> {
match self {
InsertInstructionResult::Results(results) => Cow::Borrowed(results),
InsertInstructionResult::Results(_, results) => Cow::Borrowed(results),
InsertInstructionResult::SimplifiedTo(result) => Cow::Owned(vec![result]),
InsertInstructionResult::SimplifiedToMultiple(results) => Cow::Owned(results),
InsertInstructionResult::InstructionRemoved => Cow::Owned(vec![]),
Expand All @@ -507,7 +514,7 @@ impl<'dfg> InsertInstructionResult<'dfg> {
match self {
InsertInstructionResult::SimplifiedTo(_) => 1,
InsertInstructionResult::SimplifiedToMultiple(results) => results.len(),
InsertInstructionResult::Results(results) => results.len(),
InsertInstructionResult::Results(_, results) => results.len(),
InsertInstructionResult::InstructionRemoved => 0,
}
}
Expand Down
26 changes: 22 additions & 4 deletions crates/noirc_evaluator/src/ssa/ir/function_inserter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ impl<'f> FunctionInserter<'f> {
pub(crate) fn resolve(&mut self, mut value: ValueId) -> ValueId {
value = self.function.dfg.resolve(value);
match self.values.get(&value) {
Some(value) => *value,
Some(value) => self.resolve(*value),
jfecher marked this conversation as resolved.
Show resolved Hide resolved
None => match &self.function.dfg[value] {
super::value::Value::Array { array, typ } => {
let array = array.clone();
Expand Down Expand Up @@ -62,9 +62,27 @@ impl<'f> FunctionInserter<'f> {
)
}

pub(crate) fn push_instruction(&mut self, id: InstructionId, block: BasicBlockId) {
/// Maps a terminator in place, replacing any ValueId in the terminator with the
/// resolved version of that value id from this FunctionInserter's internal value mapping.
pub(crate) fn map_terminator_in_place(&mut self, block: BasicBlockId) {
let mut terminator = self.function.dfg[block].take_terminator();
terminator.mutate_values(|value| self.resolve(value));
self.function.dfg[block].set_terminator(terminator);
}

/// Push a new instruction to the given block and return its new InstructionId.
/// If the instruction was simplified out of the program, None is returned.
pub(crate) fn push_instruction(
&mut self,
id: InstructionId,
block: BasicBlockId,
) -> Option<InstructionId> {
let (instruction, location) = self.map_instruction(id);
self.push_instruction_value(instruction, id, block, location);

match self.push_instruction_value(instruction, id, block, location) {
InsertInstructionResult::Results(new_id, _) => Some(new_id),
_ => None,
}
}

pub(crate) fn push_instruction_value(
Expand Down Expand Up @@ -110,7 +128,7 @@ impl<'f> FunctionInserter<'f> {
values.insert(*old_result, *new_result);
}
}
InsertInstructionResult::Results(new_results) => {
InsertInstructionResult::Results(_, new_results) => {
for (old_result, new_result) in old_results.iter().zip(*new_results) {
values.insert(*old_result, *new_result);
}
Expand Down
22 changes: 21 additions & 1 deletion crates/noirc_evaluator/src/ssa/ir/instruction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,26 @@ impl TerminatorInstruction {
}
}

/// Mutate each ValueId to a new ValueId using the given mapping function
pub(crate) fn mutate_values(&mut self, mut f: impl FnMut(ValueId) -> ValueId) {
use TerminatorInstruction::*;
match self {
JmpIf { condition, .. } => {
*condition = f(*condition);
}
Jmp { arguments, .. } => {
for argument in arguments {
*argument = f(*argument);
}
}
Return { return_values } => {
for return_value in return_values {
*return_value = f(*return_value);
}
}
}
}

/// Apply a function to each value
pub(crate) fn for_each_value<T>(&self, mut f: impl FnMut(ValueId) -> T) {
use TerminatorInstruction::*;
Expand Down Expand Up @@ -837,7 +857,7 @@ pub(crate) enum SimplifyResult {
/// a function such as a tuple
SimplifiedToMultiple(Vec<ValueId>),

/// Replace this function with an simpler but equivalent function.
/// Replace this function with an simpler but equivalent instruction.
SimplifiedToInstruction(Instruction),

/// Remove the instruction, it is unnecessary
Expand Down
16 changes: 8 additions & 8 deletions crates/noirc_evaluator/src/ssa/ir/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,15 @@ pub(crate) enum Value {

impl Value {
/// Retrieves the type of this Value
pub(crate) fn get_type(&self) -> Type {
pub(crate) fn get_type(&self) -> &Type {
match self {
Value::Instruction { typ, .. } => typ.clone(),
Value::Param { typ, .. } => typ.clone(),
Value::NumericConstant { typ, .. } => typ.clone(),
Value::Array { typ, .. } => typ.clone(),
Value::Function { .. } => Type::Function,
Value::Intrinsic { .. } => Type::Function,
Value::ForeignFunction { .. } => Type::Function,
Value::Instruction { typ, .. } => typ,
Value::Param { typ, .. } => typ,
Value::NumericConstant { typ, .. } => typ,
Value::Array { typ, .. } => typ,
Value::Function { .. } => &Type::Function,
Value::Intrinsic { .. } => &Type::Function,
Value::ForeignFunction { .. } => &Type::Function,
}
}
}
2 changes: 1 addition & 1 deletion crates/noirc_evaluator/src/ssa/opt/constant_folding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ impl Context {
) {
InsertInstructionResult::SimplifiedTo(new_result) => vec![new_result],
InsertInstructionResult::SimplifiedToMultiple(new_results) => new_results,
InsertInstructionResult::Results(new_results) => new_results.to_vec(),
InsertInstructionResult::Results(_, new_results) => new_results.to_vec(),
InsertInstructionResult::InstructionRemoved => vec![],
};
assert_eq!(old_results.len(), new_results.len());
Expand Down
4 changes: 2 additions & 2 deletions crates/noirc_evaluator/src/ssa/opt/inlining.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ impl<'function> PerFunctionContext<'function> {
self.context.call_stack.pop_back();
}

let new_results = InsertInstructionResult::Results(&new_results);
let new_results = InsertInstructionResult::Results(call_id, &new_results);
Self::insert_new_instruction_results(&mut self.values, old_results, new_results);
}

Expand Down Expand Up @@ -435,7 +435,7 @@ impl<'function> PerFunctionContext<'function> {
values.insert(*old_result, new_result);
}
}
InsertInstructionResult::Results(new_results) => {
InsertInstructionResult::Results(_, new_results) => {
for (old_result, new_result) in old_results.iter().zip(new_results) {
values.insert(*old_result, *new_result);
}
Expand Down
Loading