Skip to content

Implement Libfunc Counter #1267

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

Open
wants to merge 26 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
7882929
fix ci
FrancoGiachetta Jun 23, 2025
b54592b
fix daily blocks ci
FrancoGiachetta Jun 23, 2025
4478643
update starknet-replay and sequencer in staknet-blocks workflow
FrancoGiachetta Jun 23, 2025
7bcb98d
implement libfunc_counter
FrancoGiachetta Jul 1, 2025
b93ae5b
implement with mlir array
FrancoGiachetta Jul 1, 2025
09ec4d1
Merge branch 'main' into libfunc_counter
FrancoGiachetta Jul 1, 2025
951ac4c
fix implementation with mlir
FrancoGiachetta Jul 2, 2025
5f44530
add documentation
FrancoGiachetta Jul 2, 2025
f890e42
revert change
FrancoGiachetta Jul 2, 2025
81511e1
clippy
FrancoGiachetta Jul 2, 2025
06aef99
fix some docs
FrancoGiachetta Jul 3, 2025
f930c1f
update comment
FrancoGiachetta Jul 3, 2025
a3bb89b
format
FrancoGiachetta Jul 3, 2025
2061d85
change to dynamic arrays (not working yet)
FrancoGiachetta Jul 4, 2025
f7b1aeb
format
FrancoGiachetta Jul 4, 2025
71ad878
fix value increment
FrancoGiachetta Jul 7, 2025
caa1d07
implement array counter guards
FrancoGiachetta Jul 11, 2025
3a35a0e
add support for multiple contract inner calls
FrancoGiachetta Jul 15, 2025
d5a557d
add support for multiple contract inner calls
FrancoGiachetta Jul 15, 2025
99bbaa8
Merge branch 'main' into libfunc_counter
FrancoGiachetta Jul 17, 2025
16e5b34
Merge branch 'main' into libfunc_counter
FrancoGiachetta Jul 17, 2025
f51a00e
update docs
FrancoGiachetta Jul 17, 2025
14893de
Merge branch 'libfunc_counter' of github.com:lambdaclass/cairo_native…
FrancoGiachetta Jul 17, 2025
5f31ef4
use malloc and free with trackers
FrancoGiachetta Jul 17, 2025
3ef6949
fix typo
FrancoGiachetta Jul 17, 2025
ba640cd
Merge branch 'main' into libfunc_counter
FrancoGiachetta Jul 18, 2025
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ with-cheatcode = []
with-debug-utils = []
with-mem-tracing = []
with-libfunc-profiling = []
with-libfunc-counter = []
with-segfault-catcher = []
with-trace-dump = ["dep:sierra-emu"]

Expand Down
56 changes: 56 additions & 0 deletions src/bin/cairo-native-run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ struct Args {
/// The output path for the libfunc profilling results
profiler_output: Option<PathBuf>,

#[cfg(feature = "with-libfunc-counter")]
#[arg(long)]
/// The output path for the execution trace
Copy link
Contributor

Choose a reason for hiding this comment

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

Is this comment valid?

libfunc_counter_output: Option<PathBuf>,

#[cfg(feature = "with-trace-dump")]
#[arg(long)]
/// The output path for the execution trace
Expand Down Expand Up @@ -120,6 +125,17 @@ fn main() -> anyhow::Result<()> {
}
}

#[cfg(feature = "with-libfunc-counter")]
{
use cairo_native::metadata::libfunc_counter::LibfuncCounterBinding;
if let Some(counter_id) =
executor.find_symbol_ptr(LibfuncCounterBinding::CounterId.symbol())
{
let counter_id = counter_id.cast::<u64>();
unsafe { *counter_id = 0 };
}
}

Box::new(move |function_id, args, gas, syscall_handler| {
executor.invoke_dynamic_with_syscall_handler(
function_id,
Expand Down Expand Up @@ -154,6 +170,17 @@ fn main() -> anyhow::Result<()> {
}
}

#[cfg(feature = "with-libfunc-counter")]
{
use cairo_native::metadata::libfunc_counter::LibfuncCounterBinding;
if let Some(counter_id) =
executor.find_symbol_ptr(LibfuncCounterBinding::CounterId.symbol())
{
let counter_id = counter_id.cast::<u64>();
unsafe { *counter_id = 0 };
}
}

Box::new(move |function_id, args, gas, syscall_handler| {
executor.invoke_dynamic_with_syscall_handler(
function_id,
Expand Down Expand Up @@ -281,6 +308,35 @@ fn main() -> anyhow::Result<()> {
}
}

#[cfg(feature = "with-libfunc-counter")]
if let Some(libfunc_counter_output) = args.libfunc_counter_output {
use std::collections::HashMap;

let counters =
cairo_native::metadata::libfunc_counter::libfunc_counter_runtime::LIBFUNC_COUNTER
.lock()
.unwrap();
assert_eq!(counters.len(), 1);

let libfunc_counter = counters.values().next().unwrap();

let libfunc_counts = libfunc_counter
.iter()
.enumerate()
.map(|(i, count)| {
let libfunc = &sierra_program.libfunc_declarations[i];
let debug_name = libfunc.id.debug_name.clone().unwrap().to_string();

(debug_name, *count)
})
.collect::<HashMap<String, u32>>();
serde_json::to_writer_pretty(
std::fs::File::create(libfunc_counter_output).unwrap(),
&libfunc_counts,
)
.unwrap();
}

#[cfg(feature = "with-trace-dump")]
if let Some(trace_output) = args.trace_output {
let traces = cairo_native::metadata::trace_dump::trace_dump_runtime::TRACE_DUMP
Expand Down
49 changes: 49 additions & 0 deletions src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ use crate::{
utils::{generate_function_name, walk_ir::walk_mlir_block, BlockExt},
};
use bumpalo::Bump;
#[cfg(feature = "with-libfunc-counter")]
use cairo_lang_sierra::ids::ConcreteLibfuncId;
use cairo_lang_sierra::{
edit_state,
extensions::{
Expand Down Expand Up @@ -151,6 +153,14 @@ pub fn compile(
let n_libfuncs = program.libfunc_declarations.len() + 1;
let sierra_stmt_start_offset = num_types + n_libfuncs + 1;

#[cfg(feature = "with-libfunc-counter")]
let libfunc_indexes = program
.libfunc_declarations
.iter()
.enumerate()
.map(|(idx, libf)| (libf.id.clone(), idx))
.collect::<HashMap<ConcreteLibfuncId, usize>>();

Comment on lines +156 to +163
Copy link
Contributor

Choose a reason for hiding this comment

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

Is this mapping necessary? The libfunc ID already seems to be autoincremental, so maybe we can use the libfunc ID directly.

for function in &program.funcs {
tracing::info!("Compiling function `{}`.", function.id);
compile_func(
Expand All @@ -159,6 +169,8 @@ pub fn compile(
registry,
function,
&program.statements,
#[cfg(feature = "with-libfunc-counter")]
&libfunc_indexes,
metadata,
di_compile_unit_id,
sierra_stmt_start_offset,
Expand Down Expand Up @@ -186,6 +198,7 @@ fn compile_func(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
function: &Function,
statements: &[Statement],
#[cfg(feature = "with-libfunc-counter")] libfunc_indexes: &HashMap<ConcreteLibfuncId, usize>,
metadata: &mut MetadataStorage,
di_compile_unit_id: Attribute,
sierra_stmt_start_offset: usize,
Expand Down Expand Up @@ -640,6 +653,22 @@ fn compile_func(
},
};

#[cfg(feature = "with-libfunc-counter")]
{
// Can't fail since that would we got a libfunc which is not defined in the program
let libfunc_idx = libfunc_indexes.get(&invocation.libfunc_id).unwrap();

crate::metadata::libfunc_counter::libfunc_counter_runtime::count_libfunc(
context,
module,
block,
location,
metadata,
*libfunc_idx,
libfunc_indexes.len() as u32,
)?;
}

libfunc.build(
context,
registry,
Expand Down Expand Up @@ -1033,6 +1062,10 @@ fn compile_func(
sierra_stmt_start_offset + function.entry_point.0,
0,
),
#[cfg(feature = "with-libfunc-counter")]
libfunc_indexes,
#[cfg(feature = "with-libfunc-counter")]
metadata,
)?;

tracing::debug!("Done generating function {}.", function.id);
Expand Down Expand Up @@ -1414,6 +1447,8 @@ fn generate_entry_point_wrapper<'c>(
arg_types: &[(Type<'c>, Location<'c>)],
ret_types: &[Type<'c>],
location: Location<'c>,
#[cfg(feature = "with-libfunc-counter")] libfunc_indexes: &HashMap<ConcreteLibfuncId, usize>,
#[cfg(feature = "with-libfunc-counter")] metadata: &mut MetadataStorage,
) -> Result<(), Error> {
let region = Region::new();
let block = region.append_block(Block::new(arg_types));
Expand Down Expand Up @@ -1446,6 +1481,20 @@ fn generate_entry_point_wrapper<'c>(
returns.push(block.extract_value(context, location, result, *ty, i)?);
}

#[cfg(feature = "with-libfunc-counter")]
{
use crate::metadata::libfunc_counter::LibfuncCounterMeta;

let libfunc_counter = metadata.get_mut::<LibfuncCounterMeta>().unwrap();
libfunc_counter.store_array_counter(
context,
module,
&block,
location,
libfunc_indexes.len() as u32,
)?;
}

block.append_operation(func::r#return(&returns, location));

module.body().append_operation(func::func(
Expand Down
3 changes: 3 additions & 0 deletions src/executor/aot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ impl AotNativeExecutor {
#[cfg(feature = "with-libfunc-profiling")]
crate::metadata::profiler::setup_runtime(|name| executor.find_symbol_ptr(name));

#[cfg(feature = "with-libfunc-counter")]
crate::metadata::libfunc_counter::setup_runtime(|name| executor.find_symbol_ptr(name));

executor
}

Expand Down
3 changes: 3 additions & 0 deletions src/executor/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,9 @@ impl AotContractExecutor {
#[cfg(feature = "with-libfunc-profiling")]
crate::metadata::profiler::setup_runtime(|name| executor.find_symbol_ptr(name));

#[cfg(feature = "with-libfunc-counter")]
crate::metadata::libfunc_counter::setup_runtime(|name| executor.find_symbol_ptr(name));

Ok(Some(executor))
}

Expand Down
3 changes: 3 additions & 0 deletions src/executor/jit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ impl<'m> JitNativeExecutor<'m> {
#[cfg(feature = "with-libfunc-profiling")]
crate::metadata::profiler::setup_runtime(|name| executor.find_symbol_ptr(name));

#[cfg(feature = "with-libfunc-counter")]
crate::metadata::libfunc_counter::setup_runtime(|name| executor.find_symbol_ptr(name));

Ok(executor)
}

Expand Down
1 change: 1 addition & 0 deletions src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub mod dup_overrides;
pub mod enum_snapshot_variants;
pub mod felt252_dict;
pub mod gas;
pub mod libfunc_counter;
pub mod profiler;
pub mod realloc_bindings;
pub mod runtime_bindings;
Expand Down
Loading
Loading