implement immutable variables codegen (#70)

This commit is contained in:
Cyrill Leutwiler
2024-10-10 13:33:00 +02:00
committed by GitHub
parent 8b7fe8e3d7
commit d5d419cefc
24 changed files with 920 additions and 510 deletions
Generated
+350 -350
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -67,7 +67,7 @@ log = { version = "0.4" }
# polkadot-sdk and friends # polkadot-sdk and friends
codec = { version = "3.6.12", default-features = false, package = "parity-scale-codec" } codec = { version = "3.6.12", default-features = false, package = "parity-scale-codec" }
scale-info = { version = "2.11.1", default-features = false } scale-info = { version = "2.11.1", default-features = false }
polkadot-sdk = { git = "https://github.com/paritytech/polkadot-sdk", rev = "c77095f51119d2eccdc54d2f3518bed0ffbd6d53" } polkadot-sdk = { git = "https://github.com/paritytech/polkadot-sdk", rev = "fe0bfb79f4c883abbc3214519d19e46617c20bd2" }
# llvm # llvm
[workspace.dependencies.inkwell] [workspace.dependencies.inkwell]
+8 -8
View File
@@ -1,10 +1,10 @@
{ {
"Baseline": 912, "Baseline": 962,
"Computation": 4413, "Computation": 4463,
"DivisionArithmetics": 40689, "DivisionArithmetics": 40756,
"ERC20": 54374, "ERC20": 54427,
"Events": 1726, "Events": 1792,
"FibonacciIterative": 3015, "FibonacciIterative": 3065,
"Flipper": 3612, "Flipper": 3665,
"SHA1": 32865 "SHA1": 32923
} }
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
/* runner.json
{
"differential": true,
"actions": [
{
"Upload": {
"code": {
"Solidity": {
"contract": "ImmutablesTester"
}
}
}
},
{
"Instantiate": {
"code": {
"Solidity": {
"contract": "Immutables"
}
}
}
},
{
"Call": {
"dest": {
"Instantiated": 0
}
}
}
]
}
*/
contract ImmutablesTester {
// Read should work in the runtime code
uint public immutable foo;
// Read should work in the runtime code
uint public immutable bar;
// Read should work in the runtime code
uint public immutable zoo;
// Assign and read should work in the constructor
constructor(uint _foo) payable {
foo = _foo;
bar = foo + 1;
zoo = bar + 2;
assert(zoo == _foo + 3);
}
}
contract Immutables {
fallback() external {
ImmutablesTester tester = new ImmutablesTester(127);
assert(tester.foo() == 127);
assert(tester.bar() == tester.foo() + 1);
assert(tester.zoo() == tester.bar() + 2);
}
}
+1
View File
@@ -42,6 +42,7 @@ test_spec!(create, "CreateB", "Create.sol");
test_spec!(call, "Caller", "Call.sol"); test_spec!(call, "Caller", "Call.sol");
test_spec!(transfer, "Transfer", "Transfer.sol"); test_spec!(transfer, "Transfer", "Transfer.sol");
test_spec!(return_data_oob, "ReturnDataOob", "ReturnDataOob.sol"); test_spec!(return_data_oob, "ReturnDataOob", "ReturnDataOob.sol");
test_spec!(immutables, "Immutables", "Immutables.sol");
fn instantiate(path: &str, contract: &str) -> Vec<SpecsAction> { fn instantiate(path: &str, contract: &str) -> Vec<SpecsAction> {
vec![Instantiate { vec![Instantiate {
+2
View File
@@ -27,9 +27,11 @@ pub use self::polkavm::context::function::llvm_runtime::LLVMRuntime as PolkaVMLL
pub use self::polkavm::context::function::r#return::Return as PolkaVMFunctionReturn; pub use self::polkavm::context::function::r#return::Return as PolkaVMFunctionReturn;
pub use self::polkavm::context::function::runtime::deploy_code::DeployCode as PolkaVMDeployCodeFunction; pub use self::polkavm::context::function::runtime::deploy_code::DeployCode as PolkaVMDeployCodeFunction;
pub use self::polkavm::context::function::runtime::entry::Entry as PolkaVMEntryFunction; pub use self::polkavm::context::function::runtime::entry::Entry as PolkaVMEntryFunction;
pub use self::polkavm::context::function::runtime::immutable_data_load::ImmutableDataLoad as PolkaVMImmutableDataLoadFunction;
pub use self::polkavm::context::function::runtime::runtime_code::RuntimeCode as PolkaVMRuntimeCodeFunction; pub use self::polkavm::context::function::runtime::runtime_code::RuntimeCode as PolkaVMRuntimeCodeFunction;
pub use self::polkavm::context::function::runtime::FUNCTION_DEPLOY_CODE as PolkaVMFunctionDeployCode; pub use self::polkavm::context::function::runtime::FUNCTION_DEPLOY_CODE as PolkaVMFunctionDeployCode;
pub use self::polkavm::context::function::runtime::FUNCTION_ENTRY as PolkaVMFunctionEntry; pub use self::polkavm::context::function::runtime::FUNCTION_ENTRY as PolkaVMFunctionEntry;
pub use self::polkavm::context::function::runtime::FUNCTION_LOAD_IMMUTABLE_DATA as PolkaVMFunctionImmutableDataLoad;
pub use self::polkavm::context::function::runtime::FUNCTION_RUNTIME_CODE as PolkaVMFunctionRuntimeCode; pub use self::polkavm::context::function::runtime::FUNCTION_RUNTIME_CODE as PolkaVMFunctionRuntimeCode;
pub use self::polkavm::context::function::yul_data::YulData as PolkaVMFunctionYulData; pub use self::polkavm::context::function::yul_data::YulData as PolkaVMFunctionYulData;
pub use self::polkavm::context::function::Function as PolkaVMFunction; pub use self::polkavm::context::function::Function as PolkaVMFunction;
@@ -29,6 +29,8 @@ pub mod imports {
pub static DEPOSIT_EVENT: &str = "deposit_event"; pub static DEPOSIT_EVENT: &str = "deposit_event";
pub static GET_IMMUTABLE_DATA: &str = "get_immutable_data";
pub static GET_STORAGE: &str = "get_storage"; pub static GET_STORAGE: &str = "get_storage";
pub static HASH_KECCAK_256: &str = "hash_keccak_256"; pub static HASH_KECCAK_256: &str = "hash_keccak_256";
@@ -47,11 +49,13 @@ pub mod imports {
pub static SET_STORAGE: &str = "set_storage"; pub static SET_STORAGE: &str = "set_storage";
pub static SET_IMMUTABLE_DATA: &str = "set_immutable_data";
pub static VALUE_TRANSFERRED: &str = "value_transferred"; pub static VALUE_TRANSFERRED: &str = "value_transferred";
/// All imported runtime API symbols. /// All imported runtime API symbols.
/// Useful for configuring common attributes and linkage. /// Useful for configuring common attributes and linkage.
pub static IMPORTS: [&str; 18] = [ pub static IMPORTS: [&str; 20] = [
ADDRESS, ADDRESS,
BALANCE, BALANCE,
BLOCK_NUMBER, BLOCK_NUMBER,
@@ -60,6 +64,7 @@ pub mod imports {
CHAIN_ID, CHAIN_ID,
CODE_SIZE, CODE_SIZE,
DEPOSIT_EVENT, DEPOSIT_EVENT,
GET_IMMUTABLE_DATA,
GET_STORAGE, GET_STORAGE,
HASH_KECCAK_256, HASH_KECCAK_256,
INPUT, INPUT,
@@ -68,6 +73,7 @@ pub mod imports {
RETURN, RETURN,
RETURNDATACOPY, RETURNDATACOPY,
RETURNDATASIZE, RETURNDATASIZE,
SET_IMMUTABLE_DATA,
SET_STORAGE, SET_STORAGE,
VALUE_TRANSFERRED, VALUE_TRANSFERRED,
]; ];
@@ -91,7 +91,8 @@ impl<'ctx> Function<'ctx> {
|| (name.starts_with("__") || (name.starts_with("__")
&& name != self::runtime::FUNCTION_ENTRY && name != self::runtime::FUNCTION_ENTRY
&& name != self::runtime::FUNCTION_DEPLOY_CODE && name != self::runtime::FUNCTION_DEPLOY_CODE
&& name != self::runtime::FUNCTION_RUNTIME_CODE) && name != self::runtime::FUNCTION_RUNTIME_CODE
&& name != self::runtime::FUNCTION_LOAD_IMMUTABLE_DATA)
} }
/// Checks whether the function is related to the near call ABI. /// Checks whether the function is related to the near call ABI.
@@ -31,6 +31,18 @@ impl Entry {
where where
D: Dependency + Clone, D: Dependency + Clone,
{ {
context.declare_global(
revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER,
context.word_type().array_type(0),
AddressSpace::Stack,
);
context.declare_global(
revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_SIZE,
context.xlen_type(),
AddressSpace::Stack,
);
let calldata_type = context.array_type(context.byte_type(), Self::MAX_CALLDATA_SIZE); let calldata_type = context.array_type(context.byte_type(), Self::MAX_CALLDATA_SIZE);
context.set_global( context.set_global(
crate::polkavm::GLOBAL_CALLDATA_POINTER, crate::polkavm::GLOBAL_CALLDATA_POINTER,
@@ -0,0 +1,116 @@
//! The immutable data runtime function.
use crate::polkavm::context::address_space::AddressSpace;
use crate::polkavm::context::function::runtime;
use crate::polkavm::context::pointer::Pointer;
use crate::polkavm::context::Context;
use crate::polkavm::WriteLLVM;
use crate::polkavm::{runtime_api, Dependency};
/// A function for requesting the immutable data from the runtime.
/// This is a special function that is only used by the front-end generated code.
///
/// The runtime API is called lazily and subsequent calls are no-ops.
///
/// The bytes written is asserted to match the expected length.
/// This should never fail; the length is known.
/// However, this is a one time assertion, hence worth it.
#[derive(Debug)]
pub struct ImmutableDataLoad;
impl<D> WriteLLVM<D> for ImmutableDataLoad
where
D: Dependency + Clone,
{
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
context.add_function(
runtime::FUNCTION_LOAD_IMMUTABLE_DATA,
context.void_type().fn_type(Default::default(), false),
0,
Some(inkwell::module::Linkage::Private),
)?;
Ok(())
}
fn into_llvm(self, context: &mut Context<D>) -> anyhow::Result<()> {
context.set_current_function(runtime::FUNCTION_LOAD_IMMUTABLE_DATA)?;
context.set_basic_block(context.current_function().borrow().entry_block());
let immutable_data_size_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_SIZE)?
.value
.as_pointer_value();
let immutable_data_size = context.build_load(
Pointer::new(
context.xlen_type(),
AddressSpace::Stack,
immutable_data_size_pointer,
),
"immutable_data_size_load",
)?;
let load_immutable_data_block = context.append_basic_block("load_immutables_block");
let return_block = context.current_function().borrow().return_block();
let immutable_data_size_is_zero = context.builder().build_int_compare(
inkwell::IntPredicate::EQ,
context.xlen_type().const_zero(),
immutable_data_size.into_int_value(),
"immutable_data_size_is_zero",
)?;
context.build_conditional_branch(
immutable_data_size_is_zero,
return_block,
load_immutable_data_block,
)?;
context.set_basic_block(load_immutable_data_block);
let output_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
.value
.as_pointer_value();
context.build_runtime_call(
runtime_api::imports::GET_IMMUTABLE_DATA,
&[
context
.builder()
.build_ptr_to_int(output_pointer, context.xlen_type(), "ptr_to_xlen")?
.into(),
context
.builder()
.build_ptr_to_int(
immutable_data_size_pointer,
context.xlen_type(),
"ptr_to_xlen",
)?
.into(),
],
);
let bytes_written = context.builder().build_load(
context.xlen_type(),
immutable_data_size_pointer,
"bytes_written",
)?;
context.builder().build_store(
immutable_data_size_pointer,
context.xlen_type().const_zero(),
)?;
let overflow_block = context.append_basic_block("immutable_data_overflow");
let is_overflow = context.builder().build_int_compare(
inkwell::IntPredicate::UGT,
immutable_data_size.into_int_value(),
bytes_written.into_int_value(),
"is_overflow",
)?;
context.build_conditional_branch(is_overflow, overflow_block, return_block)?;
context.set_basic_block(overflow_block);
context.build_call(context.intrinsics().trap, &[], "invalid_trap");
context.build_unreachable();
context.set_basic_block(return_block);
context.build_return(None);
Ok(())
}
}
@@ -2,6 +2,7 @@
pub mod deploy_code; pub mod deploy_code;
pub mod entry; pub mod entry;
pub mod immutable_data_load;
pub mod runtime_code; pub mod runtime_code;
/// The main entry function name. /// The main entry function name.
@@ -12,3 +13,6 @@ pub const FUNCTION_DEPLOY_CODE: &str = "__deploy";
/// The runtime code function name. /// The runtime code function name.
pub const FUNCTION_RUNTIME_CODE: &str = "__runtime"; pub const FUNCTION_RUNTIME_CODE: &str = "__runtime";
/// The immutable data load function name.
pub const FUNCTION_LOAD_IMMUTABLE_DATA: &str = "__immutable_data_load";
@@ -51,4 +51,31 @@ impl<'ctx> Global<'ctx> {
global global
} }
/// Construct an external global.
pub fn declare<D, T>(
context: &mut Context<'ctx, D>,
r#type: T,
address_space: AddressSpace,
name: &str,
) -> Self
where
D: PolkaVMDependency + Clone,
T: BasicType<'ctx>,
{
let r#type = r#type.as_basic_type_enum();
let value = context
.module()
.add_global(r#type, Some(address_space.into()), name);
let global = Self { r#type, value };
global.value.set_linkage(inkwell::module::Linkage::External);
global
.value
.set_visibility(inkwell::GlobalVisibility::Default);
global.value.set_externally_initialized(true);
global
}
} }
@@ -162,6 +162,18 @@ where
}) })
} }
fn link_immutable_data(&self, contract_path: &str) -> anyhow::Result<()> {
let size = self.solidity().immutables_size() as u32;
let exports = revive_runtime_api::immutable_data::module(self.llvm(), size);
self.module.link_in_module(exports).map_err(|error| {
anyhow::anyhow!(
"The contract `{}` immutable data module linking error: {}",
contract_path,
error
)
})
}
/// Configure the PolkaVM minimum stack size. /// Configure the PolkaVM minimum stack size.
fn set_polkavm_stack_size( fn set_polkavm_stack_size(
llvm: &'ctx inkwell::context::Context, llvm: &'ctx inkwell::context::Context,
@@ -239,6 +251,7 @@ where
let module_clone = self.module.clone(); let module_clone = self.module.clone();
self.link_polkavm_exports(contract_path)?; self.link_polkavm_exports(contract_path)?;
self.link_immutable_data(contract_path)?;
let target_machine = TargetMachine::new(Target::PVM, self.optimizer.settings())?; let target_machine = TargetMachine::new(Target::PVM, self.optimizer.settings())?;
target_machine.set_target_data(self.module()); target_machine.set_target_data(self.module());
@@ -381,6 +394,15 @@ where
} }
} }
/// Declare an external global.
pub fn declare_global<T>(&mut self, name: &str, r#type: T, address_space: AddressSpace)
where
T: BasicType<'ctx> + Clone + Copy,
{
let global = Global::declare(self, r#type, address_space, name);
self.globals.insert(name.to_owned(), global);
}
/// Returns the LLVM intrinsics collection reference. /// Returns the LLVM intrinsics collection reference.
pub fn intrinsics(&self) -> &Intrinsics<'ctx> { pub fn intrinsics(&self) -> &Intrinsics<'ctx> {
&self.intrinsics &self.intrinsics
@@ -17,7 +17,7 @@ impl SolidityData {
Self::default() Self::default()
} }
/// Returns the current number of immutables values in the contract. /// Returns the current size of immutable values in the contract.
pub fn immutables_size(&self) -> usize { pub fn immutables_size(&self) -> usize {
self.immutables.len() * revive_common::BYTE_LENGTH_WORD self.immutables.len() * revive_common::BYTE_LENGTH_WORD
} }
@@ -1,14 +1,19 @@
//! Translates the contract immutable operations. //! Translates the contract immutable operations.
use inkwell::types::BasicType;
use crate::polkavm::context::address_space::AddressSpace; use crate::polkavm::context::address_space::AddressSpace;
use crate::polkavm::context::code_type::CodeType; use crate::polkavm::context::code_type::CodeType;
use crate::polkavm::context::function::runtime;
use crate::polkavm::context::pointer::Pointer; use crate::polkavm::context::pointer::Pointer;
use crate::polkavm::context::Context; use crate::polkavm::context::Context;
use crate::polkavm::Dependency; use crate::polkavm::Dependency;
/// Translates the contract immutable load. /// Translates the contract immutable load.
/// In the deploy code the values are read from the auxiliary heap. ///
/// In the runtime code they are requested from the system contract. /// In deploy code the values are read from the stack.
///
/// In runtime code they are loaded lazily with the `get_immutable_data` syscall.
pub fn load<'ctx, D>( pub fn load<'ctx, D>(
context: &mut Context<'ctx, D>, context: &mut Context<'ctx, D>,
index: inkwell::values::IntValue<'ctx>, index: inkwell::values::IntValue<'ctx>,
@@ -20,38 +25,27 @@ where
None => { None => {
anyhow::bail!("Immutables are not available if the contract part is undefined"); anyhow::bail!("Immutables are not available if the contract part is undefined");
} }
Some(CodeType::Deploy) => { Some(CodeType::Deploy) => load_from_memory(context, index),
let index_double = context.builder().build_int_mul(
index,
context.word_const(2),
"immutable_load_index_double",
)?;
let offset_absolute = context.builder().build_int_add(
index_double,
context.word_const(
crate::polkavm::HEAP_AUX_OFFSET_CONSTRUCTOR_RETURN_DATA
+ (3 * revive_common::BYTE_LENGTH_WORD) as u64,
),
"immutable_offset_absolute",
)?;
let immutable_pointer = Pointer::new_with_offset(
context,
AddressSpace::default(),
context.word_type(),
offset_absolute,
"immutable_pointer",
);
context.build_load(immutable_pointer, "immutable_value")
}
Some(CodeType::Runtime) => { Some(CodeType::Runtime) => {
todo!() context.build_call(
context
.get_function(runtime::FUNCTION_LOAD_IMMUTABLE_DATA)
.expect("is always declared for runtime code")
.borrow()
.declaration(),
&[],
runtime::FUNCTION_LOAD_IMMUTABLE_DATA,
);
load_from_memory(context, index)
} }
} }
} }
/// Translates the contract immutable store. /// Translates the contract immutable store.
/// In the deploy code the values are written to the auxiliary heap at the predefined offset, ///
/// being prepared for returning to the system contract for saving. /// In deploy code the values are written to the stack at the predefined offset,
/// being prepared for storing them using the `set_immutable_data` syscall.
///
/// Ignored in the runtime code. /// Ignored in the runtime code.
pub fn store<'ctx, D>( pub fn store<'ctx, D>(
context: &mut Context<'ctx, D>, context: &mut Context<'ctx, D>,
@@ -66,46 +60,48 @@ where
anyhow::bail!("Immutables are not available if the contract part is undefined"); anyhow::bail!("Immutables are not available if the contract part is undefined");
} }
Some(CodeType::Deploy) => { Some(CodeType::Deploy) => {
let index_double = context.builder().build_int_mul( let immutable_data_pointer = context
index, .get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
context.word_const(2), .value
"immutable_load_index_double", .as_pointer_value();
)?; let immutable_pointer = context.build_gep(
let index_offset_absolute = context.builder().build_int_add( Pointer::new(
index_double, context.word_type(),
context.word_const( AddressSpace::Stack,
crate::polkavm::HEAP_AUX_OFFSET_CONSTRUCTOR_RETURN_DATA immutable_data_pointer,
+ (2 * revive_common::BYTE_LENGTH_WORD) as u64,
), ),
"index_offset_absolute", &[index],
)?; context.word_type().as_basic_type_enum(),
let index_offset_pointer = Pointer::new_with_offset( "immutable_variable_pointer",
context,
AddressSpace::default(),
context.word_type(),
index_offset_absolute,
"immutable_index_pointer",
); );
context.build_store(index_offset_pointer, index)?; context.build_store(immutable_pointer, value)
let value_offset_absolute = context.builder().build_int_add(
index_offset_absolute,
context.word_const(revive_common::BYTE_LENGTH_WORD as u64),
"value_offset_absolute",
)?;
let value_offset_pointer = Pointer::new_with_offset(
context,
AddressSpace::default(),
context.word_type(),
value_offset_absolute,
"immutable_value_pointer",
);
context.build_store(value_offset_pointer, value)?;
Ok(())
} }
Some(CodeType::Runtime) => { Some(CodeType::Runtime) => {
anyhow::bail!("Immutable writes are not available in the runtime code"); anyhow::bail!("Immutable writes are not available in the runtime code");
} }
} }
} }
pub fn load_from_memory<'ctx, D>(
context: &mut Context<'ctx, D>,
index: inkwell::values::IntValue<'ctx>,
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
where
D: Dependency + Clone,
{
let immutable_data_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
.value
.as_pointer_value();
let immutable_pointer = context.build_gep(
Pointer::new(
context.word_type(),
AddressSpace::Stack,
immutable_data_pointer,
),
&[index],
context.word_type().as_basic_type_enum(),
"immutable_variable_pointer",
);
context.build_load(immutable_pointer, "immutable_value")
}
+58 -3
View File
@@ -1,7 +1,10 @@
//! Translates the transaction return operations. //! Translates the transaction return operations.
use crate::polkavm::context::address_space::AddressSpace;
use crate::polkavm::context::code_type::CodeType;
use crate::polkavm::context::pointer::Pointer;
use crate::polkavm::context::Context; use crate::polkavm::context::Context;
use crate::polkavm::Dependency; use crate::polkavm::{runtime_api, Dependency};
/// Translates the `return` instruction. /// Translates the `return` instruction.
pub fn r#return<'ctx, D>( pub fn r#return<'ctx, D>(
@@ -12,8 +15,60 @@ pub fn r#return<'ctx, D>(
where where
D: Dependency + Clone, D: Dependency + Clone,
{ {
if context.code_type().is_none() { match context.code_type() {
anyhow::bail!("Return is not available if the contract part is undefined"); None => anyhow::bail!("Return is not available if the contract part is undefined"),
Some(CodeType::Deploy) => {
let immutable_data_size_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_SIZE)?
.value
.as_pointer_value();
let immutable_data_size = context.build_load(
Pointer::new(
context.xlen_type(),
AddressSpace::Stack,
immutable_data_size_pointer,
),
"immutable_data_size_load",
)?;
let write_immutable_data_block = context.append_basic_block("write_immutables_block");
let join_return_block = context.append_basic_block("join_return_block");
let immutable_data_size_is_zero = context.builder().build_int_compare(
inkwell::IntPredicate::EQ,
context.xlen_type().const_zero(),
immutable_data_size.into_int_value(),
"immutable_data_size_is_zero",
)?;
context.build_conditional_branch(
immutable_data_size_is_zero,
join_return_block,
write_immutable_data_block,
)?;
context.set_basic_block(write_immutable_data_block);
let immutable_data_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
.value
.as_pointer_value();
context.build_runtime_call(
runtime_api::imports::SET_IMMUTABLE_DATA,
&[
context
.builder()
.build_ptr_to_int(
immutable_data_pointer,
context.xlen_type(),
"immutable_data_pointer_to_xlen",
)?
.into(),
immutable_data_size,
],
);
context.build_unconditional_branch(join_return_block);
context.set_basic_block(join_return_block);
}
Some(CodeType::Runtime) => {}
} }
context.build_exit( context.build_exit(
+3 -1
View File
@@ -12,4 +12,6 @@ riscv-64 = []
[dependencies] [dependencies]
anyhow = { workspace = true } anyhow = { workspace = true }
inkwell = { workspace = true, features = ["target-riscv", "no-libffi-linking", "llvm18-0"] } inkwell = { workspace = true, features = ["target-riscv", "no-libffi-linking", "llvm18-0"] }
revive-common = { workspace = true }
+89
View File
@@ -0,0 +1,89 @@
//! Allocates memory for the immutable data in a separate module.
//!
//! Because we only know how many immutable variables were set after
//! translating the whole contract code, we want to set the size at
//! last. However, array types need a size upon declaration.
//!
//! A simple work around is to replace it during link time.
//! To quote the [LLVM docs][0]:
//!
//! > For global variable declarations [..] the allocation size and
//! > alignment of the definition it resolves to must be greater than
//! > or equal to that of the declaration [..]
//!
//! To adhere to this we initially declare a length of 0 in
//! `revive-llvm-context`.
//!
//! [0]: https://llvm.org/docs/LangRef.html#global-variables
/// The immutable data module name.
pub static MODULE_NAME: &str = "__evm_immutables";
/// The immutable data global pointer.
pub static GLOBAL_IMMUTABLE_DATA_POINTER: &str = "__immutable_data_ptr";
/// The immutable data global size.
pub static GLOBAL_IMMUTABLE_DATA_SIZE: &str = "__immutable_data_size";
/// The immutable data maximum size in bytes.
pub static IMMUTABLE_DATA_MAX_SIZE: u32 = 4 * 1024;
/// Returns the immutable data global type.
pub fn data_type(context: &inkwell::context::Context, size: u32) -> inkwell::types::ArrayType {
context
.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
.array_type(size)
}
/// Returns the immutable data size global type.
pub fn size_type(context: &inkwell::context::Context) -> inkwell::types::IntType {
context.custom_width_int_type(revive_common::BIT_LENGTH_X32 as u32)
}
/// Creates a LLVM module with the immutable data and its `size` in bytes.
pub fn module(context: &inkwell::context::Context, size: u32) -> inkwell::module::Module {
let module = context.create_module(MODULE_NAME);
let length = size / revive_common::BYTE_LENGTH_WORD as u32;
let immutable_data = module.add_global(
data_type(context, length),
Default::default(),
GLOBAL_IMMUTABLE_DATA_POINTER,
);
immutable_data.set_linkage(inkwell::module::Linkage::External);
immutable_data.set_visibility(inkwell::GlobalVisibility::Default);
immutable_data.set_initializer(&data_type(context, length).get_undef());
let immutable_data_size = module.add_global(
size_type(context),
Default::default(),
GLOBAL_IMMUTABLE_DATA_SIZE,
);
immutable_data_size.set_linkage(inkwell::module::Linkage::External);
immutable_data_size.set_visibility(inkwell::GlobalVisibility::Default);
immutable_data_size.set_initializer(&size_type(context).const_int(size as u64, false));
module
}
#[cfg(test)]
mod tests {
use crate::immutable_data::*;
#[test]
fn it_works() {
inkwell::targets::Target::initialize_riscv(&Default::default());
let context = inkwell::context::Context::create();
let size = 512;
let module = crate::immutable_data::module(&context, size);
let immutable_data_pointer = module.get_global(GLOBAL_IMMUTABLE_DATA_POINTER).unwrap();
assert_eq!(
immutable_data_pointer.get_initializer().unwrap(),
data_type(&context, size / 32).get_undef()
);
let immutable_data_size = module.get_global(GLOBAL_IMMUTABLE_DATA_SIZE).unwrap();
assert_eq!(
immutable_data_size.get_initializer().unwrap(),
size_type(&context).const_int(size as u64, false)
);
}
}
+1
View File
@@ -7,5 +7,6 @@
//! [1]: [https://docs.rs/pallet-contracts/26.0.0/pallet_contracts/api_doc/index.html] //! [1]: [https://docs.rs/pallet-contracts/26.0.0/pallet_contracts/api_doc/index.html]
pub mod calling_convention; pub mod calling_convention;
pub mod immutable_data;
pub mod polkavm_exports; pub mod polkavm_exports;
pub mod polkavm_imports; pub mod polkavm_imports;
+4
View File
@@ -59,6 +59,10 @@ POLKAVM_IMPORT(void, return_data_copy, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(void, return_data_size, uint32_t) POLKAVM_IMPORT(void, return_data_size, uint32_t)
POLKAVM_IMPORT(void, set_immutable_data, uint32_t, uint32_t);
POLKAVM_IMPORT(void, get_immutable_data, uint32_t, uint32_t);
POLKAVM_IMPORT(void, value_transferred, uint32_t) POLKAVM_IMPORT(void, value_transferred, uint32_t)
POLKAVM_IMPORT(uint32_t, set_storage, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t) POLKAVM_IMPORT(uint32_t, set_storage, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
@@ -199,6 +199,7 @@ where
revive_llvm_context::PolkaVMDummyLLVMWritable::default(), revive_llvm_context::PolkaVMDummyLLVMWritable::default(),
) )
.declare(context)?; .declare(context)?;
revive_llvm_context::PolkaVMImmutableDataLoadFunction.declare(context)?;
entry.into_llvm(context)?; entry.into_llvm(context)?;
@@ -266,6 +267,7 @@ where
revive_llvm_context::PolkaVMCodeType::Runtime, revive_llvm_context::PolkaVMCodeType::Runtime,
)) ))
.into_llvm(context)?; .into_llvm(context)?;
revive_llvm_context::PolkaVMImmutableDataLoadFunction.into_llvm(context)?;
Ok(()) Ok(())
} }
@@ -45,7 +45,7 @@ impl Element {
fn pop_arguments_llvm<'ctx, D>( fn pop_arguments_llvm<'ctx, D>(
&mut self, &mut self,
context: &mut revive_llvm_context::PolkaVMContext<'ctx, D>, context: &mut revive_llvm_context::PolkaVMContext<'ctx, D>,
) -> Vec<inkwell::values::BasicValueEnum<'ctx>> ) -> anyhow::Result<Vec<inkwell::values::BasicValueEnum<'ctx>>>
where where
D: revive_llvm_context::PolkaVMDependency + Clone, D: revive_llvm_context::PolkaVMDependency + Clone,
{ {
@@ -57,15 +57,13 @@ impl Element {
[self.stack.elements.len() + input_size - output_size - 1 - index] [self.stack.elements.len() + input_size - output_size - 1 - index]
.to_llvm() .to_llvm()
.into_pointer_value(); .into_pointer_value();
let value = context let value = context.build_load(
.build_load( revive_llvm_context::PolkaVMPointer::new_stack_field(context, pointer),
revive_llvm_context::PolkaVMPointer::new_stack_field(context, pointer), format!("argument_{index}").as_str(),
format!("argument_{index}").as_str(), )?;
)
.unwrap();
arguments.push(value); arguments.push(value);
} }
arguments Ok(arguments)
} }
} }
@@ -426,7 +424,7 @@ where
InstructionName::JUMPDEST => Ok(None), InstructionName::JUMPDEST => Ok(None),
InstructionName::ADD => { InstructionName::ADD => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::addition( revive_llvm_context::polkavm_evm_arithmetic::addition(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -435,7 +433,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::SUB => { InstructionName::SUB => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::subtraction( revive_llvm_context::polkavm_evm_arithmetic::subtraction(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -444,7 +442,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::MUL => { InstructionName::MUL => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::multiplication( revive_llvm_context::polkavm_evm_arithmetic::multiplication(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -453,7 +451,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::DIV => { InstructionName::DIV => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::division( revive_llvm_context::polkavm_evm_arithmetic::division(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -462,7 +460,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::MOD => { InstructionName::MOD => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::remainder( revive_llvm_context::polkavm_evm_arithmetic::remainder(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -471,7 +469,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::SDIV => { InstructionName::SDIV => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::division_signed( revive_llvm_context::polkavm_evm_arithmetic::division_signed(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -480,7 +478,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::SMOD => { InstructionName::SMOD => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::remainder_signed( revive_llvm_context::polkavm_evm_arithmetic::remainder_signed(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -490,7 +488,7 @@ where
} }
InstructionName::LT => { InstructionName::LT => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare( revive_llvm_context::polkavm_evm_comparison::compare(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -500,7 +498,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::GT => { InstructionName::GT => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare( revive_llvm_context::polkavm_evm_comparison::compare(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -510,7 +508,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::EQ => { InstructionName::EQ => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare( revive_llvm_context::polkavm_evm_comparison::compare(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -520,7 +518,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::ISZERO => { InstructionName::ISZERO => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare( revive_llvm_context::polkavm_evm_comparison::compare(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -530,7 +528,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::SLT => { InstructionName::SLT => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare( revive_llvm_context::polkavm_evm_comparison::compare(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -540,7 +538,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::SGT => { InstructionName::SGT => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare( revive_llvm_context::polkavm_evm_comparison::compare(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -551,7 +549,7 @@ where
} }
InstructionName::OR => { InstructionName::OR => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::or( revive_llvm_context::polkavm_evm_bitwise::or(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -560,7 +558,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::XOR => { InstructionName::XOR => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::xor( revive_llvm_context::polkavm_evm_bitwise::xor(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -569,7 +567,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::NOT => { InstructionName::NOT => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::xor( revive_llvm_context::polkavm_evm_bitwise::xor(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -578,7 +576,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::AND => { InstructionName::AND => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::and( revive_llvm_context::polkavm_evm_bitwise::and(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -587,7 +585,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::SHL => { InstructionName::SHL => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::shift_left( revive_llvm_context::polkavm_evm_bitwise::shift_left(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -596,7 +594,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::SHR => { InstructionName::SHR => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::shift_right( revive_llvm_context::polkavm_evm_bitwise::shift_right(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -605,7 +603,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::SAR => { InstructionName::SAR => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::shift_right_arithmetic( revive_llvm_context::polkavm_evm_bitwise::shift_right_arithmetic(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -614,7 +612,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::BYTE => { InstructionName::BYTE => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::byte( revive_llvm_context::polkavm_evm_bitwise::byte(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -624,7 +622,7 @@ where
} }
InstructionName::ADDMOD => { InstructionName::ADDMOD => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_math::add_mod( revive_llvm_context::polkavm_evm_math::add_mod(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -634,7 +632,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::MULMOD => { InstructionName::MULMOD => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_math::mul_mod( revive_llvm_context::polkavm_evm_math::mul_mod(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -644,7 +642,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::EXP => { InstructionName::EXP => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_math::exponent( revive_llvm_context::polkavm_evm_math::exponent(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -653,7 +651,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::SIGNEXTEND => { InstructionName::SIGNEXTEND => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_math::sign_extend( revive_llvm_context::polkavm_evm_math::sign_extend(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -663,7 +661,7 @@ where
} }
InstructionName::SHA3 | InstructionName::KECCAK256 => { InstructionName::SHA3 | InstructionName::KECCAK256 => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_crypto::sha3( revive_llvm_context::polkavm_evm_crypto::sha3(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -673,7 +671,7 @@ where
} }
InstructionName::MLOAD => { InstructionName::MLOAD => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_memory::load( revive_llvm_context::polkavm_evm_memory::load(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -681,7 +679,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::MSTORE => { InstructionName::MSTORE => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_memory::store( revive_llvm_context::polkavm_evm_memory::store(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -690,7 +688,7 @@ where
.map(|_| None) .map(|_| None)
} }
InstructionName::MSTORE8 => { InstructionName::MSTORE8 => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_memory::store_byte( revive_llvm_context::polkavm_evm_memory::store_byte(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -699,7 +697,7 @@ where
.map(|_| None) .map(|_| None)
} }
InstructionName::MCOPY => { InstructionName::MCOPY => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
let destination = revive_llvm_context::PolkaVMPointer::new_with_offset( let destination = revive_llvm_context::PolkaVMPointer::new_with_offset(
context, context,
revive_llvm_context::PolkaVMAddressSpace::Heap, revive_llvm_context::PolkaVMAddressSpace::Heap,
@@ -725,7 +723,7 @@ where
} }
InstructionName::SLOAD => { InstructionName::SLOAD => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_storage::load( revive_llvm_context::polkavm_evm_storage::load(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -733,7 +731,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::SSTORE => { InstructionName::SSTORE => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_storage::store( revive_llvm_context::polkavm_evm_storage::store(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -742,7 +740,7 @@ where
.map(|_| None) .map(|_| None)
} }
InstructionName::TLOAD => { InstructionName::TLOAD => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_storage::transient_load( revive_llvm_context::polkavm_evm_storage::transient_load(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -750,7 +748,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::TSTORE => { InstructionName::TSTORE => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_storage::transient_store( revive_llvm_context::polkavm_evm_storage::transient_store(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -766,27 +764,28 @@ where
let offset = context let offset = context
.solidity_mut() .solidity_mut()
.get_or_allocate_immutable(key.as_str()); .get_or_allocate_immutable(key.as_str())
/ revive_common::BYTE_LENGTH_WORD;
let index = context.word_const(offset as u64); let index = context.xlen_type().const_int(offset as u64, false);
revive_llvm_context::polkavm_evm_immutable::load(context, index).map(Some) revive_llvm_context::polkavm_evm_immutable::load(context, index).map(Some)
} }
InstructionName::ASSIGNIMMUTABLE => { InstructionName::ASSIGNIMMUTABLE => {
let mut arguments = self.pop_arguments_llvm(context); let mut arguments = self.pop_arguments_llvm(context)?;
let key = self let key = self
.instruction .instruction
.value .value
.ok_or_else(|| anyhow::anyhow!("Instruction value missing"))?; .ok_or_else(|| anyhow::anyhow!("Instruction value missing"))?;
let offset = context.solidity_mut().allocate_immutable(key.as_str()); let offset = context.solidity_mut().allocate_immutable(key.as_str())
/ revive_common::BYTE_LENGTH_WORD;
let index = context.word_const(offset as u64); let index = context.xlen_type().const_int(offset as u64, false);
let value = arguments.pop().expect("Always exists").into_int_value(); let value = arguments.pop().expect("Always exists").into_int_value();
revive_llvm_context::polkavm_evm_immutable::store(context, index, value) revive_llvm_context::polkavm_evm_immutable::store(context, index, value)
.map(|_| None) .map(|_| None)
} }
InstructionName::CALLDATALOAD => { InstructionName::CALLDATALOAD => {
match context match context
.code_type() .code_type()
@@ -796,7 +795,7 @@ where
Ok(Some(context.word_const(0).as_basic_value_enum())) Ok(Some(context.word_const(0).as_basic_value_enum()))
} }
revive_llvm_context::PolkaVMCodeType::Runtime => { revive_llvm_context::PolkaVMCodeType::Runtime => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_calldata::load( revive_llvm_context::polkavm_evm_calldata::load(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -819,7 +818,7 @@ where
} }
} }
InstructionName::CALLDATACOPY => { InstructionName::CALLDATACOPY => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
match context match context
.code_type() .code_type()
@@ -862,7 +861,7 @@ where
} }
} }
InstructionName::CODECOPY => { InstructionName::CODECOPY => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
let parent = context.module().get_name().to_str().expect("Always valid"); let parent = context.module().get_name().to_str().expect("Always valid");
let source = &self.stack_input.elements[1]; let source = &self.stack_input.elements[1];
@@ -917,7 +916,7 @@ where
revive_llvm_context::polkavm_evm_return_data::size(context).map(Some) revive_llvm_context::polkavm_evm_return_data::size(context).map(Some)
} }
InstructionName::RETURNDATACOPY => { InstructionName::RETURNDATACOPY => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_return_data::copy( revive_llvm_context::polkavm_evm_return_data::copy(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -927,7 +926,7 @@ where
.map(|_| None) .map(|_| None)
} }
InstructionName::EXTCODESIZE => { InstructionName::EXTCODESIZE => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_ext_code::size( revive_llvm_context::polkavm_evm_ext_code::size(
context, context,
Some(arguments[0].into_int_value()), Some(arguments[0].into_int_value()),
@@ -935,7 +934,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::EXTCODEHASH => { InstructionName::EXTCODEHASH => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_ext_code::hash( revive_llvm_context::polkavm_evm_ext_code::hash(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -944,7 +943,7 @@ where
} }
InstructionName::RETURN => { InstructionName::RETURN => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_return::r#return( revive_llvm_context::polkavm_evm_return::r#return(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -953,7 +952,7 @@ where
.map(|_| None) .map(|_| None)
} }
InstructionName::REVERT => { InstructionName::REVERT => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_return::revert( revive_llvm_context::polkavm_evm_return::revert(
context, context,
arguments[0].into_int_value(), arguments[0].into_int_value(),
@@ -969,7 +968,7 @@ where
} }
InstructionName::LOG0 => { InstructionName::LOG0 => {
let mut arguments = self.pop_arguments_llvm(context); let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log( revive_llvm_context::polkavm_evm_event::log(
context, context,
arguments.remove(0).into_int_value(), arguments.remove(0).into_int_value(),
@@ -982,7 +981,7 @@ where
.map(|_| None) .map(|_| None)
} }
InstructionName::LOG1 => { InstructionName::LOG1 => {
let mut arguments = self.pop_arguments_llvm(context); let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log( revive_llvm_context::polkavm_evm_event::log(
context, context,
arguments.remove(0).into_int_value(), arguments.remove(0).into_int_value(),
@@ -995,7 +994,7 @@ where
.map(|_| None) .map(|_| None)
} }
InstructionName::LOG2 => { InstructionName::LOG2 => {
let mut arguments = self.pop_arguments_llvm(context); let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log( revive_llvm_context::polkavm_evm_event::log(
context, context,
arguments.remove(0).into_int_value(), arguments.remove(0).into_int_value(),
@@ -1008,7 +1007,7 @@ where
.map(|_| None) .map(|_| None)
} }
InstructionName::LOG3 => { InstructionName::LOG3 => {
let mut arguments = self.pop_arguments_llvm(context); let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log( revive_llvm_context::polkavm_evm_event::log(
context, context,
arguments.remove(0).into_int_value(), arguments.remove(0).into_int_value(),
@@ -1021,7 +1020,7 @@ where
.map(|_| None) .map(|_| None)
} }
InstructionName::LOG4 => { InstructionName::LOG4 => {
let mut arguments = self.pop_arguments_llvm(context); let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log( revive_llvm_context::polkavm_evm_event::log(
context, context,
arguments.remove(0).into_int_value(), arguments.remove(0).into_int_value(),
@@ -1035,7 +1034,7 @@ where
} }
InstructionName::CALL => { InstructionName::CALL => {
let mut arguments = self.pop_arguments_llvm(context); let mut arguments = self.pop_arguments_llvm(context)?;
let gas = arguments.remove(0).into_int_value(); let gas = arguments.remove(0).into_int_value();
let address = arguments.remove(0).into_int_value(); let address = arguments.remove(0).into_int_value();
@@ -1060,7 +1059,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::STATICCALL => { InstructionName::STATICCALL => {
let mut arguments = self.pop_arguments_llvm(context); let mut arguments = self.pop_arguments_llvm(context)?;
let gas = arguments.remove(0).into_int_value(); let gas = arguments.remove(0).into_int_value();
let address = arguments.remove(0).into_int_value(); let address = arguments.remove(0).into_int_value();
@@ -1084,7 +1083,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::DELEGATECALL => { InstructionName::DELEGATECALL => {
let mut arguments = self.pop_arguments_llvm(context); let mut arguments = self.pop_arguments_llvm(context)?;
let gas = arguments.remove(0).into_int_value(); let gas = arguments.remove(0).into_int_value();
let address = arguments.remove(0).into_int_value(); let address = arguments.remove(0).into_int_value();
@@ -1108,7 +1107,7 @@ where
} }
InstructionName::CREATE | InstructionName::ZK_CREATE => { InstructionName::CREATE | InstructionName::ZK_CREATE => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
let value = arguments[0].into_int_value(); let value = arguments[0].into_int_value();
let input_offset = arguments[1].into_int_value(); let input_offset = arguments[1].into_int_value();
@@ -1124,7 +1123,7 @@ where
.map(Some) .map(Some)
} }
InstructionName::CREATE2 | InstructionName::ZK_CREATE2 => { InstructionName::CREATE2 | InstructionName::ZK_CREATE2 => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
let value = arguments[0].into_int_value(); let value = arguments[0].into_int_value();
let input_offset = arguments[1].into_int_value(); let input_offset = arguments[1].into_int_value();
@@ -1155,7 +1154,7 @@ where
revive_llvm_context::polkavm_evm_ether_gas::gas(context).map(Some) revive_llvm_context::polkavm_evm_ether_gas::gas(context).map(Some)
} }
InstructionName::BALANCE => { InstructionName::BALANCE => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
let address = arguments[0].into_int_value(); let address = arguments[0].into_int_value();
revive_llvm_context::polkavm_evm_ether_gas::balance(context, address).map(Some) revive_llvm_context::polkavm_evm_ether_gas::balance(context, address).map(Some)
@@ -1184,7 +1183,7 @@ where
revive_llvm_context::polkavm_evm_contract_context::block_number(context).map(Some) revive_llvm_context::polkavm_evm_contract_context::block_number(context).map(Some)
} }
InstructionName::BLOCKHASH => { InstructionName::BLOCKHASH => {
let arguments = self.pop_arguments_llvm(context); let arguments = self.pop_arguments_llvm(context)?;
let index = arguments[0].into_int_value(); let index = arguments[0].into_int_value();
revive_llvm_context::polkavm_evm_contract_context::block_hash(context, index) revive_llvm_context::polkavm_evm_contract_context::block_hash(context, index)
@@ -1222,7 +1221,7 @@ where
anyhow::bail!("The `EXTCODECOPY` instruction is not supported"); anyhow::bail!("The `EXTCODECOPY` instruction is not supported");
} }
InstructionName::SELFDESTRUCT => { InstructionName::SELFDESTRUCT => {
let _arguments = self.pop_arguments_llvm(context); let _arguments = self.pop_arguments_llvm(context)?;
anyhow::bail!("The `SELFDESTRUCT` instruction is not supported"); anyhow::bail!("The `SELFDESTRUCT` instruction is not supported");
} }
@@ -1234,7 +1233,7 @@ where
return_address, return_address,
.. ..
} => { } => {
let mut arguments = self.pop_arguments_llvm(context); let mut arguments = self.pop_arguments_llvm(context)?;
arguments.pop(); arguments.pop();
arguments.reverse(); arguments.reverse();
arguments.pop(); arguments.pop();
@@ -1297,7 +1296,7 @@ where
return Ok(()); return Ok(());
} }
InstructionName::RecursiveReturn { .. } => { InstructionName::RecursiveReturn { .. } => {
let mut arguments = self.pop_arguments_llvm(context); let mut arguments = self.pop_arguments_llvm(context)?;
arguments.reverse(); arguments.reverse();
arguments.pop(); arguments.pop();
@@ -501,25 +501,30 @@ impl FunctionCall {
) )
.map(|_| None) .map(|_| None)
} }
Name::LoadImmutable => todo!(), Name::LoadImmutable => {
let mut arguments = self.pop_arguments::<D, 1>(context)?;
let key = arguments[0].original.take().ok_or_else(|| {
anyhow::anyhow!("{} `load_immutable` literal is missing", location)
})?;
let offset = context
.solidity_mut()
.get_or_allocate_immutable(key.as_str())
/ revive_common::BYTE_LENGTH_WORD;
let index = context.xlen_type().const_int(offset as u64, false);
revive_llvm_context::polkavm_evm_immutable::load(context, index).map(Some)
}
Name::SetImmutable => { Name::SetImmutable => {
let mut arguments = self.pop_arguments::<D, 3>(context)?; let mut arguments = self.pop_arguments::<D, 3>(context)?;
let key = arguments[1].original.take().ok_or_else(|| { let key = arguments[1].original.take().ok_or_else(|| {
anyhow::anyhow!("{} `load_immutable` literal is missing", location) anyhow::anyhow!("{} `load_immutable` literal is missing", location)
})?; })?;
let offset = context.solidity_mut().allocate_immutable(key.as_str())
if key.as_str() == "library_deploy_address" { / revive_common::BYTE_LENGTH_WORD;
return Ok(None); let index = context.xlen_type().const_int(offset as u64, false);
}
let offset = context.solidity_mut().allocate_immutable(key.as_str());
let index = context.word_const(offset as u64);
let value = arguments[2].value.into_int_value(); let value = arguments[2].value.into_int_value();
revive_llvm_context::polkavm_evm_immutable::store(context, index, value) revive_llvm_context::polkavm_evm_immutable::store(context, index, value)
.map(|_| None) .map(|_| None)
} }
Name::CallDataLoad => { Name::CallDataLoad => {
let arguments = self.pop_arguments_llvm::<D, 1>(context)?; let arguments = self.pop_arguments_llvm::<D, 1>(context)?;
@@ -183,6 +183,7 @@ where
&mut self, &mut self,
context: &mut revive_llvm_context::PolkaVMContext<D>, context: &mut revive_llvm_context::PolkaVMContext<D>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
revive_llvm_context::PolkaVMImmutableDataLoadFunction.declare(context)?;
let mut entry = revive_llvm_context::PolkaVMEntryFunction::default(); let mut entry = revive_llvm_context::PolkaVMEntryFunction::default();
entry.declare(context)?; entry.declare(context)?;
@@ -199,6 +200,7 @@ where
revive_llvm_context::PolkaVMFunctionDeployCode, revive_llvm_context::PolkaVMFunctionDeployCode,
revive_llvm_context::PolkaVMFunctionRuntimeCode, revive_llvm_context::PolkaVMFunctionRuntimeCode,
revive_llvm_context::PolkaVMFunctionEntry, revive_llvm_context::PolkaVMFunctionEntry,
revive_llvm_context::PolkaVMFunctionImmutableDataLoad,
] ]
.into_iter() .into_iter()
{ {
@@ -216,6 +218,7 @@ where
fn into_llvm(self, context: &mut revive_llvm_context::PolkaVMContext<D>) -> anyhow::Result<()> { fn into_llvm(self, context: &mut revive_llvm_context::PolkaVMContext<D>) -> anyhow::Result<()> {
if self.identifier.ends_with("_deployed") { if self.identifier.ends_with("_deployed") {
revive_llvm_context::PolkaVMImmutableDataLoadFunction.into_llvm(context)?;
revive_llvm_context::PolkaVMRuntimeCodeFunction::new(self.code).into_llvm(context)?; revive_llvm_context::PolkaVMRuntimeCodeFunction::new(self.code).into_llvm(context)?;
} else { } else {
revive_llvm_context::PolkaVMDeployCodeFunction::new(self.code).into_llvm(context)?; revive_llvm_context::PolkaVMDeployCodeFunction::new(self.code).into_llvm(context)?;