Skip to content
Open
63 changes: 56 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions scripts/zx_tests/vector_add.zx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from "EMBED" import vector_add

def main() -> u32[5]:
u32[5] a = [1, 2, 3, 4, 5]
u32[5] b = [2, 3, 4, 5, 6]
assert(vector_add(a, b) == [3, 5, 7, 9, 11])
return vector_add(a,b)
6 changes: 6 additions & 0 deletions scripts/zx_tests/vector_add.zxf
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from "EMBED" import vector_add

def main() -> u32[5]:
u32[5] a = [1, 2, 3, 4, 5]
u32[5] b = []
return vector_add(a,b)
21 changes: 19 additions & 2 deletions src/front/zsharp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ impl<'ast> ZGen<'ast> {
"bit_array_le" => {
if args.len() != 2 {
Err(format!(
"Got {} args to EMBED/bit_array_le, expected 1",
"Got {} args to EMBED/bit_array_le, expected 2",
args.len()
))
} else if generics.len() != 1 {
Expand Down Expand Up @@ -305,6 +305,24 @@ impl<'ast> ZGen<'ast> {
Ok(uint_lit(DFL_T.modulus().significant_bits(), 32))
}
}
"vector_add" => {
Comment thread
edwjchen marked this conversation as resolved.
Outdated
if args.len() != 2 {
Err(format!(
"Got {} args to EMBED/vector_add, expected 2",
args.len()
))
} else if generics.len() != 1 {
Err(format!(
"Got {} generic args to EMBED/vector_add, expected 1",
generics.len()
))
} else {
assert!(args.iter().all(|t| matches!(t.type_(), Ty::Array(_, _))));
let a = args.pop().unwrap();
let b = args.pop().unwrap();
Comment thread
edwjchen marked this conversation as resolved.
Outdated
vector_op(BV_ADD, a, b)
}
}
_ => Err(format!("Unknown or unimplemented builtin '{}'", f_name)),
}
}
Expand Down Expand Up @@ -891,7 +909,6 @@ impl<'ast> ZGen<'ast> {
} else {
debug!("Expr: {}", e.span().as_str());
}

match e {
ast::Expression::Ternary(u) => {
match self.expr_impl_::<true>(&u.first).ok().and_then(const_bool) {
Expand Down
14 changes: 14 additions & 0 deletions src/front/zsharp/term.rs
Original file line number Diff line number Diff line change
Expand Up @@ -908,6 +908,20 @@ pub fn bit_array_le(a: T, b: T, n: usize) -> Result<T, String> {
))
}

pub fn vector_op(op: Op, a: T, b: T) -> Result<T, String> {
match (&a.ty, &b.ty) {
(Ty::Array(a_s, a_ty), Ty::Array(b_s, b_ty)) => {
if a_s == b_s && a_ty == b_ty {
let t = term![Op::Map(Box::new(op)); a.term, b.term];
Ok(T::new(Ty::Array(*a_s, a_ty.clone()), t))
Comment thread
edwjchen marked this conversation as resolved.
Outdated
} else {
panic!("Mismatched array types (this is a bug: type checking should have caught this!)");
}
}
_ => Err("Cannot do vector_add on non-array types".to_string()),
}
}

pub struct ZSharp {
values: Option<HashMap<String, Integer>>,
}
Expand Down
30 changes: 30 additions & 0 deletions src/ir/opt/cfold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::ir::term::*;
use circ_fields::FieldV;
use lazy_static::lazy_static;
use rug::Integer;
use std::collections::BTreeMap;
use std::ops::DerefMut;
use std::sync::RwLock;

Expand Down Expand Up @@ -244,6 +245,35 @@ pub fn fold_cache(node: &Term, cache: &mut TermCache<Term>) -> Term {
b.width() + w,
))))
}),
Op::Map(op) => match (get(0).as_array_opt(), get(1).as_array_opt()) {
Comment thread
edwjchen marked this conversation as resolved.
Outdated
(Some(a), Some(b)) => {
assert!(a.size == b.size);
let mut new_map: BTreeMap<Value, Value> = BTreeMap::new();
for (a_ind, a_val) in &a.map {
let b_val = &b.map[a_ind];
let res = fold_cache(

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

@kwantam How would I evaluate the operation on va and vb without the recursive call to fold_cache here?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

High-level answer: the Op::Map(op) match clause starting on line 248 should push a new term onto the stack that is equivalent to the term containing the Op::Map(_), but which eliminates the map. I can give you more details later.

&term![*op.clone(); leaf_term(Op::Const(a_val.clone())), leaf_term(Op::Const(b_val.clone()))],
cache,
);
match res.as_value_opt() {
Some(r) => {
new_map.insert(a_ind.clone(), r.clone());
}
None => {
panic!("Unale to constant constant fold idx: {}", a_ind);
}
}
}
let new_arr = Array::new(
a.key_sort.clone(),
Box::new(a.key_sort.default_value()),
new_map,
a.size,
);
Some(leaf_term(Op::Const(Value::Array(new_arr))))
}
_ => None,
},
Comment thread
edwjchen marked this conversation as resolved.
Outdated
_ => None,
};
let new_t = {
Expand Down
4 changes: 4 additions & 0 deletions third_party/ZoKrates/zokrates_stdlib/stdlib/EMBED.zok
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,7 @@ def u16_to_u32(u16 i) -> u32:

def u8_to_u16(u8 i) -> u16:
return 0u16

// vector functions
def vector_add<N>(u32[N] a, u32[N] b) -> u32[N]:
return [0; N]
Comment on lines +79 to +90

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think if you're only going to support one type here it should be field, not u32.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I think only BV are currently supported in the FHE backend, which is why I left it as u32.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Still, it might make sense to support all the basic types, no? It wouldn't be much extra work:

  • add vadd_field, vadd_u64, vadd_u32, vadd_u16, vadd_u8 stubs in EMBED
  • in builtin_call_, extend the current match clause to catch all of these
  • extend the function in zsharp/term.rs to support both bitvector and field types
  • the current constant folder may or may not work, but I bet there's a small edit distance to working if no

Since this is so simple, I don't see a reason to leave it half-done. But I could be missing something!

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I see, updated!