Skip to content

Commit

Permalink
Merge branch 'master' into mv/sha256-var-opt
Browse files Browse the repository at this point in the history
  • Loading branch information
vezenovm authored Aug 26, 2024
2 parents 828a22e + a764c5b commit 5950f69
Show file tree
Hide file tree
Showing 99 changed files with 4,073 additions and 987 deletions.
26 changes: 26 additions & 0 deletions acvm-repo/acir/src/circuit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,28 @@ pub struct ResolvedOpcodeLocation {
/// map opcodes to debug information related to their context.
pub enum OpcodeLocation {
Acir(usize),
// TODO(https://github.com/noir-lang/noir/issues/5792): We can not get rid of this enum field entirely just yet as this format is still
// used for resolving assert messages which is a breaking serialization change.
Brillig { acir_index: usize, brillig_index: usize },
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct BrilligOpcodeLocation(pub usize);

impl OpcodeLocation {
// Utility method to allow easily comparing a resolved Brillig location and a debug Brillig location.
// This method is useful when fetching Brillig debug locations as this does not need an ACIR index,
// and just need the Brillig index.
pub fn to_brillig_location(self) -> Option<BrilligOpcodeLocation> {
match self {
OpcodeLocation::Brillig { brillig_index, .. } => {
Some(BrilligOpcodeLocation(brillig_index))
}
_ => None,
}
}
}

impl std::fmt::Display for OpcodeLocation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Expand Down Expand Up @@ -204,6 +223,13 @@ impl FromStr for OpcodeLocation {
}
}

impl std::fmt::Display for BrilligOpcodeLocation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let index = self.0;
write!(f, "{index}")
}
}

impl<F> Circuit<F> {
pub fn num_vars(&self) -> u32 {
self.current_witness_index + 1
Expand Down
3 changes: 2 additions & 1 deletion aztec_macros/src/transforms/note_interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ pub fn generate_note_interface_impl(
let mut note_fields = vec![];
let note_interface_generics = trait_impl
.trait_generics
.ordered_args
.iter()
.map(|gen| match gen.typ.clone() {
UnresolvedTypeData::Named(path, _, _) => Ok(path.last_name().to_string()),
Expand Down Expand Up @@ -120,7 +121,7 @@ pub fn generate_note_interface_impl(
ident("header"),
make_type(UnresolvedTypeData::Named(
chained_dep!("aztec", "note", "note_header", "NoteHeader"),
vec![],
Default::default(),
false,
)),
);
Expand Down
32 changes: 19 additions & 13 deletions aztec_macros/src/transforms/storage.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use acvm::acir::AcirField;
use noirc_errors::Span;
use noirc_frontend::ast::{
BlockExpression, Expression, ExpressionKind, FunctionDefinition, Ident, Literal, NoirFunction,
NoirStruct, Pattern, StatementKind, TypeImpl, UnresolvedType, UnresolvedTypeData,
BlockExpression, Expression, ExpressionKind, FunctionDefinition, GenericTypeArgs, Ident,
Literal, NoirFunction, NoirStruct, Pattern, StatementKind, TypeImpl, UnresolvedType,
UnresolvedTypeData,
};
use noirc_frontend::{
graph::CrateId,
Expand Down Expand Up @@ -54,13 +55,13 @@ pub fn check_for_storage_definition(
fn inject_context_in_storage_field(field: &mut UnresolvedType) -> Result<(), AztecMacroError> {
match &mut field.typ {
UnresolvedTypeData::Named(path, generics, _) => {
generics.push(make_type(UnresolvedTypeData::Named(
generics.ordered_args.push(make_type(UnresolvedTypeData::Named(
ident_path("Context"),
vec![],
GenericTypeArgs::default(),
false,
)));
match path.last_name() {
"Map" => inject_context_in_storage_field(&mut generics[1]),
"Map" => inject_context_in_storage_field(&mut generics.ordered_args[1]),
_ => Ok(()),
}
}
Expand Down Expand Up @@ -144,7 +145,10 @@ pub fn generate_storage_field_constructor(
generate_storage_field_constructor(
// Map is expected to have three generic parameters: key, value and context (i.e.
// Map<K, V, Context>. Here `get(1)` fetches the value type.
&(type_ident.clone(), generics.get(1).unwrap().clone()),
&(
type_ident.clone(),
generics.ordered_args.get(1).unwrap().clone(),
),
variable("slot"),
)?,
),
Expand Down Expand Up @@ -219,8 +223,11 @@ pub fn generate_storage_implementation(

// This is the type over which the impl is generic.
let generic_context_ident = ident("Context");
let generic_context_type =
make_type(UnresolvedTypeData::Named(ident_path("Context"), vec![], true));
let generic_context_type = make_type(UnresolvedTypeData::Named(
ident_path("Context"),
GenericTypeArgs::default(),
true,
));

let init = NoirFunction::normal(FunctionDefinition::normal(
&ident("init"),
Expand All @@ -231,13 +238,12 @@ pub fn generate_storage_implementation(
&return_type(chained_path!("Self")),
));

let ordered_args = vec![generic_context_type.clone()];
let generics = GenericTypeArgs { ordered_args, named_args: Vec::new() };

let storage_impl = TypeImpl {
object_type: UnresolvedType {
typ: UnresolvedTypeData::Named(
chained_path!(storage_struct_name),
vec![generic_context_type.clone()],
true,
),
typ: UnresolvedTypeData::Named(chained_path!(storage_struct_name), generics, true),
span: Span::default(),
},
type_span: Span::default(),
Expand Down
30 changes: 22 additions & 8 deletions aztec_macros/src/utils/parse_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ use noirc_frontend::{
ast::{
ArrayLiteral, AssignStatement, BlockExpression, CallExpression, CastExpression,
ConstrainStatement, ConstructorExpression, Expression, ExpressionKind, ForLoopStatement,
ForRange, FunctionReturnType, Ident, IfExpression, IndexExpression, InfixExpression,
LValue, Lambda, LetStatement, Literal, MemberAccessExpression, MethodCallExpression,
ModuleDeclaration, NoirFunction, NoirStruct, NoirTrait, NoirTraitImpl, NoirTypeAlias, Path,
PathSegment, Pattern, PrefixExpression, Statement, StatementKind, TraitImplItem, TraitItem,
TypeImpl, UnresolvedGeneric, UnresolvedGenerics, UnresolvedTraitConstraint, UnresolvedType,
UnresolvedTypeData, UnresolvedTypeExpression, UseTree, UseTreeKind,
ForRange, FunctionReturnType, GenericTypeArgs, Ident, IfExpression, IndexExpression,
InfixExpression, LValue, Lambda, LetStatement, Literal, MemberAccessExpression,
MethodCallExpression, ModuleDeclaration, NoirFunction, NoirStruct, NoirTrait,
NoirTraitImpl, NoirTypeAlias, Path, PathSegment, Pattern, PrefixExpression, Statement,
StatementKind, TraitImplItem, TraitItem, TypeImpl, UnresolvedGeneric, UnresolvedGenerics,
UnresolvedTraitConstraint, UnresolvedType, UnresolvedTypeData, UnresolvedTypeExpression,
UseTree, UseTreeKind,
},
parser::{Item, ItemKind, ParsedSubModule, ParserError},
ParsedModule,
Expand Down Expand Up @@ -297,6 +298,14 @@ fn empty_unresolved_types(unresolved_types: &mut [UnresolvedType]) {
}
}

fn empty_type_args(generics: &mut GenericTypeArgs) {
empty_unresolved_types(&mut generics.ordered_args);
for (name, typ) in &mut generics.named_args {
empty_ident(name);
empty_unresolved_type(typ);
}
}

fn empty_unresolved_type(unresolved_type: &mut UnresolvedType) {
unresolved_type.span = Default::default();

Expand All @@ -318,11 +327,11 @@ fn empty_unresolved_type(unresolved_type: &mut UnresolvedType) {
}
UnresolvedTypeData::Named(path, unresolved_types, _) => {
empty_path(path);
empty_unresolved_types(unresolved_types);
empty_type_args(unresolved_types);
}
UnresolvedTypeData::TraitAsType(path, unresolved_types) => {
empty_path(path);
empty_unresolved_types(unresolved_types);
empty_type_args(unresolved_types);
}
UnresolvedTypeData::MutableReference(unresolved_type) => {
empty_unresolved_type(unresolved_type)
Expand Down Expand Up @@ -543,5 +552,10 @@ fn empty_unresolved_type_expression(unresolved_type_expression: &mut UnresolvedT
empty_unresolved_type_expression(rhs);
}
UnresolvedTypeExpression::Constant(_, _) => (),
UnresolvedTypeExpression::AsTraitPath(path) => {
empty_unresolved_type(&mut path.typ);
empty_path(&mut path.trait_path);
empty_ident(&mut path.impl_item);
}
}
}
10 changes: 7 additions & 3 deletions compiler/noirc_errors/src/debug_info.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use acvm::acir::circuit::brillig::BrilligFunctionId;
use acvm::acir::circuit::BrilligOpcodeLocation;
use acvm::acir::circuit::OpcodeLocation;
use acvm::compiler::AcirTransformationMap;

Expand Down Expand Up @@ -98,8 +99,8 @@ pub struct DebugInfo {
/// that they should be serialized to/from strings.
#[serde_as(as = "BTreeMap<DisplayFromStr, _>")]
pub locations: BTreeMap<OpcodeLocation, Vec<Location>>,
#[serde_as(as = "BTreeMap<_, BTreeMap<DisplayFromStr, _>>")]
pub brillig_locations: BTreeMap<BrilligFunctionId, BTreeMap<OpcodeLocation, Vec<Location>>>,
pub brillig_locations:
BTreeMap<BrilligFunctionId, BTreeMap<BrilligOpcodeLocation, Vec<Location>>>,
pub variables: DebugVariables,
pub functions: DebugFunctions,
pub types: DebugTypes,
Expand All @@ -116,7 +117,10 @@ pub struct OpCodesCount {
impl DebugInfo {
pub fn new(
locations: BTreeMap<OpcodeLocation, Vec<Location>>,
brillig_locations: BTreeMap<BrilligFunctionId, BTreeMap<OpcodeLocation, Vec<Location>>>,
brillig_locations: BTreeMap<
BrilligFunctionId,
BTreeMap<BrilligOpcodeLocation, Vec<Location>>,
>,
variables: DebugVariables,
functions: DebugFunctions,
types: DebugTypes,
Expand Down
15 changes: 13 additions & 2 deletions compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/acir_variable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1933,6 +1933,9 @@ impl<F: AcirField> AcirContext<F> {
}
Some(optional_value) => {
let mut values = Vec::new();
if let AcirValue::DynamicArray(_) = optional_value {
unreachable!("Dynamic array should already be initialized");
}
self.initialize_array_inner(&mut values, optional_value)?;
values
}
Expand Down Expand Up @@ -1962,8 +1965,16 @@ impl<F: AcirField> AcirContext<F> {
self.initialize_array_inner(witnesses, value)?;
}
}
AcirValue::DynamicArray(_) => {
unreachable!("Dynamic array should already be initialized");
AcirValue::DynamicArray(AcirDynamicArray { block_id, len, .. }) => {
let dynamic_array_values = try_vecmap(0..len, |i| {
let index_var = self.add_constant(i);

let read = self.read_from_memory(block_id, &index_var)?;
Ok::<AcirValue, InternalError>(AcirValue::Var(read, AcirType::field()))
})?;
for value in dynamic_array_values {
self.initialize_array_inner(witnesses, value)?;
}
}
}
Ok(())
Expand Down
21 changes: 11 additions & 10 deletions compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/generated_acir.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! `GeneratedAcir` is constructed as part of the `acir_gen` pass to accumulate all of the ACIR
//! program as it is being converted from SSA form.
use std::collections::BTreeMap;
use std::{collections::BTreeMap, u32};

use crate::{
brillig::{brillig_gen::brillig_directive, brillig_ir::artifact::GeneratedBrillig},
Expand All @@ -11,7 +11,7 @@ use acvm::acir::{
circuit::{
brillig::{BrilligFunctionId, BrilligInputs, BrilligOutputs},
opcodes::{BlackBoxFuncCall, FunctionInput, Opcode as AcirOpcode},
AssertionPayload, OpcodeLocation,
AssertionPayload, BrilligOpcodeLocation, OpcodeLocation,
},
native_types::Witness,
BlackBoxFunc,
Expand Down Expand Up @@ -53,7 +53,7 @@ pub(crate) struct GeneratedAcir<F: AcirField> {

/// Brillig function id -> Opcodes locations map
/// This map is used to prevent redundant locations being stored for the same Brillig entry point.
pub(crate) brillig_locations: BTreeMap<BrilligFunctionId, OpcodeToLocationsMap>,
pub(crate) brillig_locations: BTreeMap<BrilligFunctionId, BrilligOpcodeToLocationsMap>,

/// Source code location of the current instruction being processed
/// None if we do not know the location
Expand All @@ -77,6 +77,8 @@ pub(crate) struct GeneratedAcir<F: AcirField> {
/// Correspondence between an opcode index (in opcodes) and the source code call stack which generated it
pub(crate) type OpcodeToLocationsMap = BTreeMap<OpcodeLocation, CallStack>;

pub(crate) type BrilligOpcodeToLocationsMap = BTreeMap<BrilligOpcodeLocation, CallStack>;

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub(crate) enum BrilligStdlibFunc {
Inverse,
Expand Down Expand Up @@ -590,6 +592,7 @@ impl<F: AcirField> GeneratedAcir<F> {
return;
}

// TODO(https://github.com/noir-lang/noir/issues/5792)
for (brillig_index, message) in generated_brillig.assert_messages.iter() {
self.assertion_payloads.insert(
OpcodeLocation::Brillig {
Expand All @@ -605,13 +608,10 @@ impl<F: AcirField> GeneratedAcir<F> {
}

for (brillig_index, call_stack) in generated_brillig.locations.iter() {
self.brillig_locations.entry(brillig_function_index).or_default().insert(
OpcodeLocation::Brillig {
acir_index: self.opcodes.len() - 1,
brillig_index: *brillig_index,
},
call_stack.clone(),
);
self.brillig_locations
.entry(brillig_function_index)
.or_default()
.insert(BrilligOpcodeLocation(*brillig_index), call_stack.clone());
}
}

Expand All @@ -625,6 +625,7 @@ impl<F: AcirField> GeneratedAcir<F> {
OpcodeLocation::Acir(index) => index,
_ => panic!("should not have brillig index"),
};

match &mut self.opcodes[acir_index] {
AcirOpcode::BrilligCall { id, .. } => *id = brillig_function_index,
_ => panic!("expected brillig call opcode"),
Expand Down
Loading

0 comments on commit 5950f69

Please sign in to comment.