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

Refactor syscall handler meta (aka. remove it completely). #479

Merged
merged 4 commits into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
16 changes: 6 additions & 10 deletions benches/benches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,27 +37,23 @@ fn criterion_benchmark(c: &mut Criterion) {
find_function_id(&logistic_map, "logistic_map::logistic_map::main");

c.bench_function("Cached JIT factorial_2M", |b| {
b.iter(|| jit_factorial.invoke_dynamic(factorial_function_id, &[], Some(u128::MAX), None));
b.iter(|| jit_factorial.invoke_dynamic(factorial_function_id, &[], Some(u128::MAX)));
});
c.bench_function("Cached JIT fib_2M", |b| {
b.iter(|| jit_fibonacci.invoke_dynamic(fibonacci_function_id, &[], Some(u128::MAX), None));
b.iter(|| jit_fibonacci.invoke_dynamic(fibonacci_function_id, &[], Some(u128::MAX)));
});
c.bench_function("Cached JIT logistic_map", |b| {
b.iter(|| {
jit_logistic_map.invoke_dynamic(logistic_map_function_id, &[], Some(u128::MAX), None)
});
b.iter(|| jit_logistic_map.invoke_dynamic(logistic_map_function_id, &[], Some(u128::MAX)));
});

c.bench_function("Cached AOT factorial_2M", |b| {
b.iter(|| aot_factorial.invoke_dynamic(factorial_function_id, &[], Some(u128::MAX), None));
b.iter(|| aot_factorial.invoke_dynamic(factorial_function_id, &[], Some(u128::MAX)));
});
c.bench_function("Cached AOT fib_2M", |b| {
b.iter(|| aot_fibonacci.invoke_dynamic(fibonacci_function_id, &[], Some(u128::MAX), None));
b.iter(|| aot_fibonacci.invoke_dynamic(fibonacci_function_id, &[], Some(u128::MAX)));
});
c.bench_function("Cached AOT logistic_map", |b| {
b.iter(|| {
aot_logistic_map.invoke_dynamic(logistic_map_function_id, &[], Some(u128::MAX), None)
});
b.iter(|| aot_logistic_map.invoke_dynamic(logistic_map_function_id, &[], Some(u128::MAX)));
});

#[cfg(target_arch = "x86_64")]
Expand Down
6 changes: 3 additions & 3 deletions benches/libfuncs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ pub fn bench_libfuncs(c: &mut Criterion) {

// Execute the program.
let result = native_executor
.invoke_dynamic(&entry.id, &[], Some(u64::MAX as u128), None)
.invoke_dynamic(&entry.id, &[], Some(u64::MAX as u128))
.unwrap();
black_box(result)
})
Expand All @@ -77,14 +77,14 @@ pub fn bench_libfuncs(c: &mut Criterion) {
// warmup
for _ in 0..5 {
native_executor
.invoke_dynamic(&entry.id, &[], Some(u64::MAX as u128), None)
.invoke_dynamic(&entry.id, &[], Some(u64::MAX as u128))
.unwrap();
}

b.iter(|| {
// Execute the program.
let result = native_executor
.invoke_dynamic(&entry.id, &[], Some(u64::MAX as u128), None)
.invoke_dynamic(&entry.id, &[], Some(u64::MAX as u128))
.unwrap();
black_box(result)
})
Expand Down
2 changes: 1 addition & 1 deletion examples/easy_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ fn main() {

// Execute the program.
let result = native_executor
.invoke_dynamic(entry_point_id, params, None, None)
.invoke_dynamic(entry_point_id, params, None)
.unwrap();

println!("Cairo program was compiled and executed successfully.");
Expand Down
7 changes: 3 additions & 4 deletions examples/erc20.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ use cairo_lang_starknet::contract_class::compile_path;
use cairo_native::{
context::NativeContext,
executor::JitNativeExecutor,
metadata::syscall_handler::SyscallHandlerMeta,
starknet::{
BlockInfo, ExecutionInfo, ExecutionInfoV2, ResourceBounds, Secp256k1Point, Secp256r1Point,
StarkNetSyscallHandler, SyscallResult, TxInfo, TxV2Info, U256,
StarknetSyscallHandler, SyscallResult, TxInfo, TxV2Info, U256,
},
utils::find_entry_point_by_idx,
};
Expand All @@ -17,7 +16,7 @@ use tracing_subscriber::{EnvFilter, FmtSubscriber};
#[derive(Debug)]
struct SyscallHandler;

impl StarkNetSyscallHandler for SyscallHandler {
impl StarknetSyscallHandler for SyscallHandler {
fn get_block_hash(&mut self, block_number: u64, _gas: &mut u128) -> SyscallResult<Felt> {
println!("Called `get_block_hash({block_number})` from MLIR.");
Ok(Felt::from_bytes_be_slice(b"get_block_hash ok"))
Expand Down Expand Up @@ -317,7 +316,7 @@ fn main() {
Felt::from(6),
],
Some(u128::MAX),
Some(&SyscallHandlerMeta::new(&mut SyscallHandler)),
SyscallHandler,
)
.expect("failed to execute the given contract");

Expand Down
2 changes: 1 addition & 1 deletion examples/invoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ fn main() {

let native_executor = JitNativeExecutor::from_native_module(native_program, Default::default());

let output = native_executor.invoke_dynamic(fn_id, &[JitValue::Felt252(1.into())], None, None);
let output = native_executor.invoke_dynamic(fn_id, &[JitValue::Felt252(1.into())], None);

println!();
println!("Cairo program was compiled and executed successfully.");
Expand Down
12 changes: 3 additions & 9 deletions examples/starknet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ use cairo_lang_starknet::contract_class::compile_path;
use cairo_native::{
context::NativeContext,
executor::JitNativeExecutor,
metadata::syscall_handler::SyscallHandlerMeta,
starknet::{
BlockInfo, ExecutionInfo, ExecutionInfoV2, ResourceBounds, Secp256k1Point, Secp256r1Point,
StarkNetSyscallHandler, SyscallResult, TxInfo, TxV2Info, U256,
StarknetSyscallHandler, SyscallResult, TxInfo, TxV2Info, U256,
},
utils::find_entry_point_by_idx,
};
Expand All @@ -17,7 +16,7 @@ use tracing_subscriber::{EnvFilter, FmtSubscriber};
#[derive(Debug)]
struct SyscallHandler;

impl StarkNetSyscallHandler for SyscallHandler {
impl StarknetSyscallHandler for SyscallHandler {
fn get_block_hash(&mut self, block_number: u64, _gas: &mut u128) -> SyscallResult<Felt> {
println!("Called `get_block_hash({block_number})` from MLIR.");
Ok(Felt::from_bytes_be_slice(b"get_block_hash ok"))
Expand Down Expand Up @@ -306,12 +305,7 @@ fn main() {
let native_executor = JitNativeExecutor::from_native_module(native_program, Default::default());

let result = native_executor
.invoke_contract_dynamic(
fn_id,
&[Felt::from(1)],
Some(u128::MAX),
Some(&SyscallHandlerMeta::new(&mut SyscallHandler)),
)
.invoke_contract_dynamic(fn_id, &[Felt::from(1)], Some(u128::MAX), SyscallHandler)
.expect("failed to execute the given contract");

println!();
Expand Down
2 changes: 1 addition & 1 deletion src/arch/aarch64.s
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ _aot_trampoline:
ldr x3, [x10, #-8]! // Decrement pointer, then load the value.
str x3, [x4, #-8]! // Reserve stack memory, then write the value.

cmp x2, 8 // Check if there are more than 8 arguments.
cmp x2, 8 // Check if there are more than 8 arguments.
bgt 1b // If there still are, loop back and repeat.

mov sp, x4
Expand Down
51 changes: 12 additions & 39 deletions src/bin/cairo-native-dump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,17 @@ use cairo_lang_compiler::{
};
use cairo_lang_defs::plugin::NamedPlugin;
use cairo_lang_semantic::plugin::PluginSuite;
use cairo_lang_sierra::{
extensions::core::{CoreLibfunc, CoreType},
program::Program,
program_registry::ProgramRegistry,
ProgramParser,
};
use cairo_lang_sierra::{program::Program, ProgramParser};
use cairo_lang_starknet::{
contract_class::compile_contract_in_prepared_db, inline_macros::selector::SelectorMacro,
plugin::StarkNetPlugin,
};
use cairo_native::{
context::NativeContext,
debug_info::{DebugInfo, DebugLocations},
metadata::{runtime_bindings::RuntimeBindingsMeta, MetadataStorage},
};
use clap::Parser;
use melior::{
dialect::DialectRegistry,
ir::{operation::OperationPrintingFlags, Location, Module},
utility::register_all_dialects,
Context,
};
use melior::{ir::operation::OperationPrintingFlags, Context};
use std::{
ffi::OsStr,
fs,
Expand All @@ -45,37 +35,20 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
)?;

// Load the program.
let context = Context::new();
let (program, debug_info) =
load_program(Path::new(&args.input), Some(&context), args.starknet)?;

// Initialize MLIR.
context.append_dialect_registry(&{
let registry = DialectRegistry::new();
register_all_dialects(&registry);
registry
});
context.load_all_available_dialects();
let context = NativeContext::new();
// TODO: Reconnect debug information.
let (program, _debug_info) = load_program(
Path::new(&args.input),
Some(context.context()),
args.starknet,
)?;

// Compile the program.
let module = Module::new(Location::unknown(&context));
let mut metadata = MetadataStorage::new();
let registry = ProgramRegistry::<CoreType, CoreLibfunc>::new(&program)?;

// Make the runtime library available.
metadata.insert(RuntimeBindingsMeta::default()).unwrap();

cairo_native::compile(
&context,
&module,
&program,
&registry,
&mut metadata,
debug_info.as_ref(),
)?;
let module = context.compile(&program)?;

// Write the output.
let output_str = module
.module()
.as_operation()
.to_string_with_flags(OperationPrintingFlags::new().enable_debug_info(true, false))?;
match args.output {
Expand Down
2 changes: 1 addition & 1 deletion src/bin/cairo-native-run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ fn main() -> anyhow::Result<()> {
.with_context(|| "not enough gas to run")?;

let result = native_executor
.invoke_dynamic(&func.id, &[], Some(initial_gas), None)
.invoke_dynamic(&func.id, &[], Some(initial_gas))
.with_context(|| "Failed to run the function.")?;

let run_result = result_to_runresult(&result)?;
Expand Down
2 changes: 1 addition & 1 deletion src/bin/cairo-native-test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ fn run_tests(
.with_context(|| "not enough gas to run")?;

let result = native_executor
.invoke_dynamic(&func.id, &[], Some(initial_gas), None)
.invoke_dynamic(&func.id, &[], Some(initial_gas))
.with_context(|| format!("Failed to run the function `{}`.", name.as_str()))?;

let run_result = result_to_runresult(&result)?;
Expand Down
4 changes: 4 additions & 0 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ impl NativeContext {
Self { context }
}

pub fn context(&self) -> &Context {
&self.context
}

/// Compiles a sierra program into MLIR and then lowers to LLVM.
/// Returns the corresponding NativeModule struct.
pub fn compile(&self, program: &Program) -> Result<NativeModule, CompileError> {
Expand Down
58 changes: 41 additions & 17 deletions src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ pub use self::{aot::AotNativeExecutor, jit::JitNativeExecutor};
use crate::{
error::jit_engine::RunnerError,
execution_result::{BuiltinStats, ContractExecutionResult, ExecutionResult},
metadata::syscall_handler::SyscallHandlerMeta,
starknet::{handler::StarknetSyscallHandlerCallbacks, StarknetSyscallHandler},
types::TypeBuilder,
utils::get_integer_layout,
values::JitValue,
Expand Down Expand Up @@ -59,15 +59,33 @@ impl<'a> NativeExecutor<'a> {
function_id: &FunctionId,
args: &[JitValue],
gas: Option<u128>,
syscall_handler: Option<&SyscallHandlerMeta>,
) -> Result<ExecutionResult, RunnerError> {
match self {
NativeExecutor::Aot(executor) => {
executor.invoke_dynamic(function_id, args, gas, syscall_handler)
}
NativeExecutor::Jit(executor) => {
executor.invoke_dynamic(function_id, args, gas, syscall_handler)
}
NativeExecutor::Aot(executor) => executor.invoke_dynamic(function_id, args, gas),
NativeExecutor::Jit(executor) => executor.invoke_dynamic(function_id, args, gas),
}
}

pub fn invoke_dynamic_with_syscall_handler(
&self,
function_id: &FunctionId,
args: &[JitValue],
gas: Option<u128>,
syscall_handler: impl StarknetSyscallHandler,
) -> Result<ExecutionResult, RunnerError> {
match self {
NativeExecutor::Aot(executor) => executor.invoke_dynamic_with_syscall_handler(
function_id,
args,
gas,
syscall_handler,
),
NativeExecutor::Jit(executor) => executor.invoke_dynamic_with_syscall_handler(
function_id,
args,
gas,
syscall_handler,
),
}
}

Expand All @@ -76,7 +94,7 @@ impl<'a> NativeExecutor<'a> {
function_id: &FunctionId,
args: &[Felt],
gas: Option<u128>,
syscall_handler: Option<&SyscallHandlerMeta>,
syscall_handler: impl StarknetSyscallHandler,
) -> Result<ContractExecutionResult, RunnerError> {
match self {
NativeExecutor::Aot(executor) => {
Expand Down Expand Up @@ -107,7 +125,7 @@ fn invoke_dynamic(
function_signature: &FunctionSignature,
args: &[JitValue],
gas: u128,
syscall_handler: Option<NonNull<()>>,
mut syscall_handler: Option<impl StarknetSyscallHandler>,
) -> ExecutionResult {
tracing::info!("Invoking function with signature: {function_signature:?}.");

Expand Down Expand Up @@ -176,13 +194,19 @@ fn invoke_dynamic(
get_integer_layout(128).align(),
&[gas as u64, (gas >> 64) as u64],
),
CoreTypeConcrete::StarkNet(StarkNetTypeConcrete::System(_)) => match syscall_handler {
Some(syscall_handler) => invoke_data.push_aligned(
get_integer_layout(64).align(),
&[syscall_handler.as_ptr() as u64],
),
None => panic!("Syscall handler is required"),
},
CoreTypeConcrete::StarkNet(StarkNetTypeConcrete::System(_)) => {
match syscall_handler.as_mut() {
Some(syscall_handler) => {
let syscall_handler =
arena.alloc(StarknetSyscallHandlerCallbacks::new(syscall_handler));
invoke_data.push_aligned(
get_integer_layout(64).align(),
&[syscall_handler as *mut _ as u64],
)
}
None => panic!("Syscall handler is required"),
}
}
_ if is_builtin(type_info) => invoke_data
.push(type_id, type_info, &JitValue::Uint64(0))
.unwrap(),
Expand Down
Loading
Loading