Skip to content

Commit

Permalink
feat: recursive DSL initial commit (#357)
Browse files Browse the repository at this point in the history
  • Loading branch information
tamirhemo authored Mar 10, 2024
1 parent 428120a commit 809f5c4
Show file tree
Hide file tree
Showing 31 changed files with 1,622 additions and 21 deletions.
10 changes: 10 additions & 0 deletions Cargo.lock

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

11 changes: 10 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
[workspace]
members = ["core", "cli", "derive", "zkvm/*", "helper", "eval", "recursion/core"]
members = [
"core",
"cli",
"derive",
"zkvm/*",
"helper",
"eval",
"recursion/core",
"recursion/compiler",
]
exclude = ["examples/target"]
resolver = "2"

Expand Down
Binary file modified examples/chess/program/elf/riscv32im-succinct-zkvm-elf
Binary file not shown.
Binary file modified examples/ed25519/program/elf/riscv32im-succinct-zkvm-elf
Binary file not shown.
Binary file modified examples/fibonacci-io/program/elf/riscv32im-succinct-zkvm-elf
Binary file not shown.
Binary file modified examples/fibonacci/program/elf/riscv32im-succinct-zkvm-elf
Binary file not shown.
Binary file modified examples/io/program/elf/riscv32im-succinct-zkvm-elf
Binary file not shown.
Binary file modified examples/json/program/elf/riscv32im-succinct-zkvm-elf
Binary file not shown.
Binary file modified examples/regex/program/elf/riscv32im-succinct-zkvm-elf
Binary file not shown.
Binary file modified examples/rsa/program/elf/riscv32im-succinct-zkvm-elf
Binary file not shown.
Binary file modified examples/ssz-withdrawals/program/elf/riscv32im-succinct-zkvm-elf
Binary file not shown.
Binary file modified examples/tendermint/program/elf/riscv32im-succinct-zkvm-elf
Binary file not shown.
14 changes: 14 additions & 0 deletions recursion/compiler/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "sp1-recursion-compiler"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
p3-field = { workspace = true }
sp1-recursion-core = { path = "../core" }

[dev-dependencies]
p3-baby-bear = { workspace = true }
sp1-core = { path = "../../core" }
34 changes: 34 additions & 0 deletions recursion/compiler/examples/fibonacci.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use p3_baby_bear::BabyBear;
use p3_field::AbstractField;
use sp1_core::stark::StarkGenericConfig;
use sp1_core::utils::BabyBearPoseidon2;
use sp1_recursion_compiler::prelude::*;
use sp1_recursion_core::runtime::Runtime;

fn main() {
let mut builder = AsmBuilder::<BabyBear>::new();
let a: Felt<_> = builder.constant(BabyBear::zero());
let b: Felt<_> = builder.constant(BabyBear::one());
let n: Felt<_> = builder.constant(BabyBear::from_canonical_u32(12));

let start: Felt<_> = builder.constant(BabyBear::zero());
let end = n;

builder.range(start, end).for_each(|_, builder| {
let temp: Felt<_> = builder.uninit();
builder.assign(temp, b);
builder.assign(b, a + b);
builder.assign(a, temp);
});

let code = builder.code();
println!("{}", code);

let program = code.machine_code();

type SC = BabyBearPoseidon2;
type F = <SC as StarkGenericConfig>::Val;

let mut runtime = Runtime::<F>::new(&program);
runtime.run();
}
24 changes: 24 additions & 0 deletions recursion/compiler/examples/logic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use p3_baby_bear::BabyBear;
use sp1_recursion_compiler::prelude::*;

fn main() {
let mut builder = AsmBuilder::<BabyBear>::new();

let a: Bool = builder.constant(false);
let b: Bool = builder.constant(true);

let and: Bool = builder.uninit();
builder.assign(and, a & b);
let or: Bool = builder.uninit();
builder.assign(or, a | b);
let xor: Bool = builder.uninit();
builder.assign(xor, a ^ b);
let not: Bool = builder.uninit();
builder.assign(not, !a);

let expr: Bool = builder.uninit();
builder.assign(expr, (a & b) | (a ^ b));

let code = builder.code();
println!("{}", code);
}
73 changes: 73 additions & 0 deletions recursion/compiler/src/asm/builder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
use super::{AssemblyCode, BasicBlock};
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;

use p3_field::PrimeField32;

use crate::asm::AsmInstruction;
use crate::builder::Builder;

#[derive(Debug, Clone)]
pub struct AsmBuilder<F> {
fp_offset: i32,

pub basic_blocks: Vec<BasicBlock<F>>,

function_labels: BTreeMap<String, F>,
}

impl<F: PrimeField32> AsmBuilder<F> {
pub fn new() -> Self {
Self {
fp_offset: -4,
basic_blocks: vec![BasicBlock::new()],
function_labels: BTreeMap::new(),
}
}

pub fn code(self) -> AssemblyCode<F> {
let labels = self
.function_labels
.into_iter()
.map(|(k, v)| (v, k))
.collect();
AssemblyCode::new(self.basic_blocks, labels)
}
}

impl<F: PrimeField32> Builder for AsmBuilder<F> {
type F = F;

fn get_mem(&mut self, size: usize) -> i32 {
let offset = self.fp_offset;
self.fp_offset -= size as i32;
offset
}

fn basic_block(&mut self) {
self.basic_blocks.push(BasicBlock::new());
}

fn block_label(&mut self) -> F {
F::from_canonical_usize(self.basic_blocks.len() - 1)
}

fn push_to_block(&mut self, block_label: Self::F, instruction: AsmInstruction<Self::F>) {
self.basic_blocks
.get_mut(block_label.as_canonical_u32() as usize)
.unwrap_or_else(|| panic!("Missing block at label: {:?}", block_label))
.push(instruction);
}

fn push(&mut self, instruction: AsmInstruction<F>) {
self.basic_blocks.last_mut().unwrap().push(instruction);
}
}

impl<F: PrimeField32> Default for AsmBuilder<F> {
fn default() -> Self {
Self::new()
}
}
78 changes: 78 additions & 0 deletions recursion/compiler/src/asm/code.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
use super::AsmInstruction;
use alloc::format;
use alloc::{collections::BTreeMap, string::String, vec::Vec};
use core::fmt;
use core::fmt::Display;
use p3_field::PrimeField32;
use sp1_recursion_core::runtime::Program;

#[derive(Debug, Clone, Default)]
pub struct BasicBlock<F>(Vec<AsmInstruction<F>>);

#[derive(Debug, Clone)]
pub struct AssemblyCode<F> {
blocks: Vec<BasicBlock<F>>,
labels: BTreeMap<F, String>,
}

impl<F: PrimeField32> BasicBlock<F> {
pub fn new() -> Self {
Self(Vec::new())
}

pub(crate) fn push(&mut self, instruction: AsmInstruction<F>) {
self.0.push(instruction);
}
}

impl<F: PrimeField32> AssemblyCode<F> {
pub fn new(blocks: Vec<BasicBlock<F>>, labels: BTreeMap<F, String>) -> Self {
Self { blocks, labels }
}

pub fn machine_code(self) -> Program<F> {
let blocks = self.blocks;

// Make a first pass to collect all the pc rows corresponding to the labels.
let mut label_to_pc = BTreeMap::new();
let mut pc = 0;
for (i, block) in blocks.iter().enumerate() {
label_to_pc.insert(F::from_canonical_usize(i), pc);
pc += block.0.len();
}

// Make the second pass to convert the assembly code to machine code.
let mut machine_code = Vec::new();
let mut pc = 0;
for block in blocks {
for instruction in block.0 {
machine_code.push(instruction.to_machine(pc, &label_to_pc));
pc += 1;
}
}

Program {
instructions: machine_code,
}
}
}

impl<F: PrimeField32> Display for AssemblyCode<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, block) in self.blocks.iter().enumerate() {
writeln!(
f,
"{}:",
self.labels
.get(&F::from_canonical_u32(i as u32))
.unwrap_or(&format!(".L{}", i))
)?;
for instruction in &block.0 {
write!(f, " ")?;
instruction.fmt(&self.labels, f)?;
writeln!(f)?;
}
}
Ok(())
}
}
Loading

0 comments on commit 809f5c4

Please sign in to comment.