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: decompose Instruction::Cast to have an explicit truncation instruction #3946

Merged
merged 16 commits into from
Jan 8, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
41 changes: 3 additions & 38 deletions compiler/noirc_evaluator/src/ssa/acir_gen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -469,9 +469,9 @@ impl Context {
self.acir_context.assert_eq_var(lhs, rhs, assert_message.clone())?;
}
}
Instruction::Cast(value_id, typ) => {
let result_acir_var = self.convert_ssa_cast(value_id, typ, dfg)?;
self.define_result_var(dfg, instruction_id, result_acir_var);
Instruction::Cast(value_id, _) => {
let acir_var = self.convert_numeric_value(*value_id, dfg)?;
self.define_result_var(dfg, instruction_id, acir_var);
}
Instruction::Call { func, arguments } => {
let result_ids = dfg.instruction_results(instruction_id);
Expand Down Expand Up @@ -1633,41 +1633,6 @@ impl Context {
}
}

/// Returns an `AcirVar` that is constrained to fit in the target type by truncating the input.
/// If the target cast is to a `NativeField`, no truncation is required so the cast becomes a
/// no-op.
fn convert_ssa_cast(
&mut self,
value_id: &ValueId,
typ: &Type,
dfg: &DataFlowGraph,
) -> Result<AcirVar, RuntimeError> {
let (variable, incoming_type) = match self.convert_value(*value_id, dfg) {
AcirValue::Var(variable, typ) => (variable, typ),
AcirValue::DynamicArray(_) | AcirValue::Array(_) => {
unreachable!("Cast is only applied to numerics")
}
};
let target_numeric = match typ {
Type::Numeric(numeric) => numeric,
_ => unreachable!("Can only cast to a numeric"),
};
match target_numeric {
NumericType::NativeField => {
// Casting into a Field as a no-op
Ok(variable)
}
NumericType::Unsigned { bit_size } | NumericType::Signed { bit_size } => {
let max_bit_size = incoming_type.bit_size();
if max_bit_size <= *bit_size {
// Incoming variable already fits into target bit size - this is a no-op
return Ok(variable);
}
self.acir_context.truncate_var(variable, *bit_size, max_bit_size)
}
}
}

/// Returns an `AcirVar`that is constrained to be result of the truncation.
fn convert_ssa_truncate(
&mut self,
Expand Down
19 changes: 19 additions & 0 deletions compiler/noirc_evaluator/src/ssa/function_builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,25 @@ impl FunctionBuilder {
/// Insert a cast instruction at the end of the current block.
/// Returns the result of the cast instruction.
pub(crate) fn insert_cast(&mut self, value: ValueId, typ: Type) -> ValueId {
fn get_type_size(typ: &Type) -> u32 {
match typ {
Type::Numeric(NumericType::NativeField) => FieldElement::max_num_bits(),
Type::Numeric(
NumericType::Unsigned { bit_size } | NumericType::Signed { bit_size },
) => *bit_size,
_ => unreachable!("Should only be called with primitive types"),
}
}
TomAFrench marked this conversation as resolved.
Show resolved Hide resolved

let incoming_type = self.type_of_value(value);
let incoming_type_size = get_type_size(&incoming_type);
let target_type_size = get_type_size(&typ);
let value = if target_type_size < incoming_type_size {
self.insert_truncate(value, target_type_size, incoming_type_size)
} else {
value
};
TomAFrench marked this conversation as resolved.
Show resolved Hide resolved

self.insert_instruction(Instruction::Cast(value, typ), None).first()
}
TomAFrench marked this conversation as resolved.
Show resolved Hide resolved

Expand Down
5 changes: 1 addition & 4 deletions compiler/noirc_evaluator/src/ssa/ir/instruction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,10 +236,7 @@ impl Instruction {
// In ACIR, a division with a false predicate outputs (0,0), so it cannot replace another instruction unless they have the same predicate
bin.operator != BinaryOp::Div
}
Cast(_, _) | Not(_) | ArrayGet { .. } | ArraySet { .. } => true,

// Unclear why this instruction causes problems.
Truncate { .. } => false,
TomAFrench marked this conversation as resolved.
Show resolved Hide resolved
Cast(_, _) | Truncate { .. } | Not(_) | ArrayGet { .. } | ArraySet { .. } => true,

// These either have side-effects or interact with memory
Constrain(..)
Expand Down
32 changes: 30 additions & 2 deletions compiler/noirc_evaluator/src/ssa/ir/instruction/call.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::{collections::VecDeque, rc::Rc};

use acvm::{acir::BlackBoxFunc, BlackBoxResolutionError, FieldElement};
use im::Vector;
use iter_extended::vecmap;
use num_bigint::BigUint;

Expand All @@ -10,7 +11,7 @@
dfg::{CallStack, DataFlowGraph},
instruction::Intrinsic,
map::Id,
types::Type,
types::{NumericType, Type},
value::{Value, ValueId},
},
opt::flatten_cfg::value_merger::ValueMerger,
Expand Down Expand Up @@ -242,7 +243,34 @@
SimplifyResult::SimplifiedToInstruction(instruction)
}
Intrinsic::FromField => {
let instruction = Instruction::Cast(arguments[0], ctrl_typevars.unwrap().remove(0));
let incoming_type = Type::field();
let target_type = ctrl_typevars.unwrap().remove(0);

fn get_type_size(typ: &Type) -> u32 {
match typ {
Type::Numeric(NumericType::NativeField) => FieldElement::max_num_bits(),
Type::Numeric(
NumericType::Unsigned { bit_size } | NumericType::Signed { bit_size },
) => *bit_size,
_ => unreachable!("Should only be called with primitive types"),
}
}

let truncate = Instruction::Truncate {
value: arguments[0],
bit_size: get_type_size(&target_type),
max_bit_size: get_type_size(&incoming_type),
};
let truncated_value = dfg
.insert_instruction_and_results(
truncate,
block,
Some(vec![incoming_type]),
Vector::default(), // needs a callstack

Check warning on line 269 in compiler/noirc_evaluator/src/ssa/ir/instruction/call.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (callstack)
)
.first();

let instruction = Instruction::Cast(truncated_value, target_type);
SimplifyResult::SimplifiedToInstruction(instruction)
}
}
Expand Down
29 changes: 19 additions & 10 deletions compiler/noirc_evaluator/src/ssa/opt/constant_folding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,16 +294,18 @@ mod test {
fn instruction_deduplication() {
// fn main f0 {
// b0(v0: Field):
// v1 = cast v0 as u32
// v2 = cast v0 as u32
// constrain v1 v2
// v1 = truncate v0 to 32 bits, max_bit_size: 254
// v2 = cast v1 as u32
// v3 = truncate v0 to 32 bits, max_bit_size: 254
// v4 = cast v3 as u32
// constrain v2 v4
// }
//
// After constructing this IR, we run constant folding which should replace the second cast
// After constructing this IR, we run constant folding which should replace the second truncation and cast
// with a reference to the results to the first. This then allows us to optimize away
// the constrain instruction as both inputs are known to be equal.
//
// The first cast instruction is retained and will be removed in the dead instruction elimination pass.
// The first truncation and cast instructions are retained and will be removed in the dead instruction elimination pass.
let main_id = Id::test_new(0);

// Compiling main
Expand All @@ -317,21 +319,28 @@ mod test {
let mut ssa = builder.finish();
let main = ssa.main_mut();
let instructions = main.dfg[main.entry_block()].instructions();
assert_eq!(instructions.len(), 3);
assert_eq!(instructions.len(), 5);

// Expected output:
//
// fn main f0 {
// b0(v0: Field):
// v1 = cast v0 as u32
// v1 = truncate v0 to 32 bits, max_bit_size: 254
// v2 = cast v1 as u32
// }
let ssa = ssa.fold_constants();
let main = ssa.main();
let instructions = main.dfg[main.entry_block()].instructions();

assert_eq!(instructions.len(), 1);
let instruction = &main.dfg[instructions[0]];
assert_eq!(instructions.len(), 2);

assert_eq!(instruction, &Instruction::Cast(ValueId::test_new(0), Type::unsigned(32)));
assert_eq!(
&main.dfg[instructions[0]],
&Instruction::Truncate { value: v0, bit_size: 32, max_bit_size: 254 }
);
assert_eq!(
&main.dfg[instructions[1]],
&Instruction::Cast(ValueId::test_new(5), Type::unsigned(32))
);
}
}
Loading