Path: blob/main/cranelift/filetests/src/function_runner.rs
1691 views
//! Provides functionality for compiling and running CLIF IR for `run` tests.1use anyhow::{Context as _, Result, anyhow};2use core::mem;3use cranelift::prelude::Imm64;4use cranelift_codegen::cursor::{Cursor, FuncCursor};5use cranelift_codegen::data_value::DataValue;6use cranelift_codegen::ir::{7ExternalName, Function, InstBuilder, InstructionData, LibCall, Opcode, Signature,8UserExternalName, UserFuncName,9};10use cranelift_codegen::isa::{OwnedTargetIsa, TargetIsa};11use cranelift_codegen::{CodegenError, Context, ir, settings};12use cranelift_control::ControlPlane;13use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};14use cranelift_jit::{JITBuilder, JITModule};15use cranelift_module::{FuncId, Linkage, Module, ModuleError};16use cranelift_native::builder_with_options;17use cranelift_reader::TestFile;18use pulley_interpreter::interp as pulley;19use std::cell::Cell;20use std::cmp::max;21use std::collections::hash_map::Entry;22use std::collections::{HashMap, HashSet};23use std::ptr::NonNull;24use target_lexicon::Architecture;25use thiserror::Error;2627const TESTFILE_NAMESPACE: u32 = 0;2829/// Holds information about a previously defined function.30#[derive(Debug)]31struct DefinedFunction {32/// This is the name that the function is internally known as.33///34/// The JIT module does not support linking / calling [TestcaseName]'s, so35/// we rename every function into a [UserExternalName].36///37/// By doing this we also have to rename functions that previously were using a38/// [UserFuncName], since they may now be in conflict after the renaming that39/// occurred.40new_name: UserExternalName,4142/// The function signature43signature: ir::Signature,4445/// JIT [FuncId]46func_id: FuncId,47}4849/// Compile a test case.50///51/// Several Cranelift functions need the ability to run Cranelift IR (e.g. `test_run`); this52/// [TestFileCompiler] provides a way for compiling Cranelift [Function]s to53/// `CompiledFunction`s and subsequently calling them through the use of a `Trampoline`. As its54/// name indicates, this compiler is limited: any functionality that requires knowledge of things55/// outside the [Function] will likely not work (e.g. global values, calls). For an example of this56/// "outside-of-function" functionality, see `cranelift_jit::backend::JITBackend`.57///58/// ```59/// # let ctrl_plane = &mut Default::default();60/// use cranelift_filetests::TestFileCompiler;61/// use cranelift_reader::parse_functions;62/// use cranelift_codegen::data_value::DataValue;63///64/// let code = "test run \n function %add(i32, i32) -> i32 { block0(v0:i32, v1:i32): v2 = iadd v0, v1 return v2 }".into();65/// let func = parse_functions(code).unwrap().into_iter().nth(0).unwrap();66/// let Ok(mut compiler) = TestFileCompiler::with_default_host_isa() else {67/// return;68/// };69/// compiler.declare_function(&func).unwrap();70/// compiler.define_function(func.clone(), ctrl_plane).unwrap();71/// compiler.create_trampoline_for_function(&func, ctrl_plane).unwrap();72/// let compiled = compiler.compile().unwrap();73/// let trampoline = compiled.get_trampoline(&func).unwrap();74///75/// let returned = trampoline.call(&compiled, &vec![DataValue::I32(2), DataValue::I32(40)]);76/// assert_eq!(vec![DataValue::I32(42)], returned);77/// ```78pub struct TestFileCompiler {79module: JITModule,80ctx: Context,8182/// Holds info about the functions that have already been defined.83/// Use look them up by their original [UserFuncName] since that's how the caller84/// passes them to us.85defined_functions: HashMap<UserFuncName, DefinedFunction>,8687/// We deduplicate trampolines by the signature of the function that they target.88/// This map holds as a key the [Signature] of the target function, and as a value89/// the [UserFuncName] of the trampoline for that [Signature].90///91/// The trampoline is defined in `defined_functions` as any other regular function.92trampolines: HashMap<Signature, UserFuncName>,93}9495impl TestFileCompiler {96/// Build a [TestFileCompiler] from a [TargetIsa]. For functions to be runnable on the97/// host machine, this [TargetIsa] must match the host machine's ISA (see98/// [TestFileCompiler::with_host_isa]).99pub fn new(isa: OwnedTargetIsa) -> Self {100let mut builder = JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());101let _ = &mut builder; // require mutability on all architectures102#[cfg(target_arch = "x86_64")]103{104builder.symbol_lookup_fn(Box::new(|name| {105if name == "__cranelift_x86_pshufb" {106Some(__cranelift_x86_pshufb as *const u8)107} else {108None109}110}));111}112113// On Unix platforms force `libm` to get linked into this executable114// because tests that use libcalls rely on this library being present.115// Without this it's been seen that when cross-compiled to riscv64 the116// final binary doesn't link in `libm`.117#[cfg(unix)]118{119unsafe extern "C" {120safe fn cosf(f: f32) -> f32;121}122let f = std::hint::black_box(1.2_f32);123assert_eq!(f.cos(), cosf(f));124}125126let module = JITModule::new(builder);127let ctx = module.make_context();128129Self {130module,131ctx,132defined_functions: HashMap::new(),133trampolines: HashMap::new(),134}135}136137/// Build a [TestFileCompiler] using the host machine's ISA and the passed flags.138pub fn with_host_isa(flags: settings::Flags) -> Result<Self> {139let builder = builder_with_options(true)140.map_err(anyhow::Error::msg)141.context("Unable to build a TargetIsa for the current host")?;142let isa = builder.finish(flags)?;143Ok(Self::new(isa))144}145146/// Build a [TestFileCompiler] using the host machine's ISA and the default flags for this147/// ISA.148pub fn with_default_host_isa() -> Result<Self> {149let flags = settings::Flags::new(settings::builder());150Self::with_host_isa(flags)151}152153/// Declares and compiles all functions in `functions`. Additionally creates a trampoline for154/// each one of them.155pub fn add_functions(156&mut self,157functions: &[Function],158ctrl_planes: Vec<ControlPlane>,159) -> Result<()> {160// Declare all functions in the file, so that they may refer to each other.161for func in functions {162self.declare_function(func)?;163}164165let ctrl_planes = ctrl_planes166.into_iter()167.chain(std::iter::repeat(ControlPlane::default()));168169// Define all functions and trampolines170for (func, ref mut ctrl_plane) in functions.iter().zip(ctrl_planes) {171self.define_function(func.clone(), ctrl_plane)?;172self.create_trampoline_for_function(func, ctrl_plane)?;173}174175Ok(())176}177178/// Registers all functions in a [TestFile]. Additionally creates a trampoline for each one179/// of them.180pub fn add_testfile(&mut self, testfile: &TestFile) -> Result<()> {181let functions = testfile182.functions183.iter()184.map(|(f, _)| f)185.cloned()186.collect::<Vec<_>>();187188self.add_functions(&functions[..], Vec::new())?;189Ok(())190}191192/// Declares a function an registers it as a linkable and callable target internally193pub fn declare_function(&mut self, func: &Function) -> Result<()> {194let next_id = self.defined_functions.len() as u32;195match self.defined_functions.entry(func.name.clone()) {196Entry::Occupied(_) => {197anyhow::bail!("Duplicate function with name {} found!", &func.name)198}199Entry::Vacant(v) => {200let name = func.name.to_string();201let func_id =202self.module203.declare_function(&name, Linkage::Local, &func.signature)?;204205v.insert(DefinedFunction {206new_name: UserExternalName::new(TESTFILE_NAMESPACE, next_id),207signature: func.signature.clone(),208func_id,209});210}211};212213Ok(())214}215216/// Renames the function to its new [UserExternalName], as well as any other function that217/// it may reference.218///219/// We have to do this since the JIT cannot link Testcase functions.220fn apply_func_rename(221&self,222mut func: Function,223defined_func: &DefinedFunction,224) -> Result<Function> {225// First, rename the function226let func_original_name = func.name;227func.name = UserFuncName::User(defined_func.new_name.clone());228229// Rename any functions that it references230// Do this in stages to appease the borrow checker231let mut redefines = Vec::with_capacity(func.dfg.ext_funcs.len());232for (ext_ref, ext_func) in &func.dfg.ext_funcs {233let old_name = match &ext_func.name {234ExternalName::TestCase(tc) => UserFuncName::Testcase(tc.clone()),235ExternalName::User(username) => {236UserFuncName::User(func.params.user_named_funcs()[*username].clone())237}238// The other cases don't need renaming, so lets just continue...239_ => continue,240};241242let target_df = self.defined_functions.get(&old_name).ok_or(anyhow!(243"Undeclared function {} is referenced by {}!",244&old_name,245&func_original_name246))?;247248redefines.push((ext_ref, target_df.new_name.clone()));249}250251// Now register the redefines252for (ext_ref, new_name) in redefines.into_iter() {253// Register the new name in the func, so that we can get a reference to it.254let new_name_ref = func.params.ensure_user_func_name(new_name);255256// Finally rename the ExtFunc257func.dfg.ext_funcs[ext_ref].name = ExternalName::User(new_name_ref);258}259260Ok(func)261}262263/// Defines the body of a function264pub fn define_function(265&mut self,266mut func: Function,267ctrl_plane: &mut ControlPlane,268) -> Result<()> {269Self::replace_hostcall_references(&mut func);270271let defined_func = self272.defined_functions273.get(&func.name)274.ok_or(anyhow!("Undeclared function {} found!", &func.name))?;275276self.ctx.func = self.apply_func_rename(func, defined_func)?;277self.module.define_function_with_control_plane(278defined_func.func_id,279&mut self.ctx,280ctrl_plane,281)?;282self.module.clear_context(&mut self.ctx);283Ok(())284}285286fn replace_hostcall_references(func: &mut Function) {287// For every `func_addr` referring to a hostcall that we288// define, replace with an `iconst` with the actual289// address. Then modify the external func references to290// harmless libcall references (that will be unused so291// ignored).292let mut funcrefs_to_remove = HashSet::new();293let mut cursor = FuncCursor::new(func);294while let Some(_block) = cursor.next_block() {295while let Some(inst) = cursor.next_inst() {296match &cursor.func.dfg.insts[inst] {297InstructionData::FuncAddr {298opcode: Opcode::FuncAddr,299func_ref,300} => {301let ext_func = &cursor.func.dfg.ext_funcs[*func_ref];302let hostcall_addr = match &ext_func.name {303ExternalName::TestCase(tc) if tc.raw() == b"__cranelift_throw" => {304Some(__cranelift_throw as usize)305}306_ => None,307};308309if let Some(addr) = hostcall_addr {310funcrefs_to_remove.insert(*func_ref);311cursor.func.dfg.insts[inst] = InstructionData::UnaryImm {312opcode: Opcode::Iconst,313imm: Imm64::new(addr as i64),314};315}316}317_ => {}318}319}320}321322for to_remove in funcrefs_to_remove {323func.dfg.ext_funcs[to_remove].name = ExternalName::LibCall(LibCall::Probestack);324}325}326327/// Creates and registers a trampoline for a function if none exists.328pub fn create_trampoline_for_function(329&mut self,330func: &Function,331ctrl_plane: &mut ControlPlane,332) -> Result<()> {333if !self.defined_functions.contains_key(&func.name) {334anyhow::bail!("Undeclared function {} found!", &func.name);335}336337// Check if a trampoline for this function signature already exists338if self.trampolines.contains_key(&func.signature) {339return Ok(());340}341342// Create a trampoline and register it343let name = UserFuncName::user(TESTFILE_NAMESPACE, self.defined_functions.len() as u32);344let trampoline = make_trampoline(name.clone(), &func.signature, self.module.isa());345346self.declare_function(&trampoline)?;347self.define_function(trampoline, ctrl_plane)?;348349self.trampolines.insert(func.signature.clone(), name);350351Ok(())352}353354/// Finalize this TestFile and link all functions.355pub fn compile(mut self) -> Result<CompiledTestFile, CompilationError> {356// Finalize the functions which we just defined, which resolves any357// outstanding relocations (patching in addresses, now that they're358// available).359self.module.finalize_definitions()?;360361Ok(CompiledTestFile {362module: Some(self.module),363defined_functions: self.defined_functions,364trampolines: self.trampolines,365})366}367}368369/// A finalized Test File370pub struct CompiledTestFile {371/// We need to store [JITModule] since it contains the underlying memory for the functions.372/// Store it in an [Option] so that we can later drop it.373module: Option<JITModule>,374375/// Holds info about the functions that have been registered in `module`.376/// See [TestFileCompiler] for more info.377defined_functions: HashMap<UserFuncName, DefinedFunction>,378379/// Trampolines available in this [JITModule].380/// See [TestFileCompiler] for more info.381trampolines: HashMap<Signature, UserFuncName>,382}383384impl CompiledTestFile {385/// Return a trampoline for calling.386///387/// Returns None if [TestFileCompiler::create_trampoline_for_function] wasn't called for this function.388pub fn get_trampoline(&self, func: &Function) -> Option<Trampoline<'_>> {389let defined_func = self.defined_functions.get(&func.name)?;390let trampoline_id = self391.trampolines392.get(&func.signature)393.and_then(|name| self.defined_functions.get(name))394.map(|df| df.func_id)?;395Some(Trampoline {396module: self.module.as_ref()?,397func_id: defined_func.func_id,398func_signature: &defined_func.signature,399trampoline_id,400})401}402}403404impl Drop for CompiledTestFile {405fn drop(&mut self) {406// Freeing the module's memory erases the compiled functions.407// This should be safe since their pointers never leave this struct.408unsafe { self.module.take().unwrap().free_memory() }409}410}411412std::thread_local! {413/// TLS slot used to store a CompiledTestFile reference so that it414/// can be recovered when a hostcall (such as the exception-throw415/// handler) is invoked.416pub static COMPILED_TEST_FILE: Cell<*const CompiledTestFile> = Cell::new(std::ptr::null());417}418419/// A callable trampoline420pub struct Trampoline<'a> {421module: &'a JITModule,422func_id: FuncId,423func_signature: &'a Signature,424trampoline_id: FuncId,425}426427impl<'a> Trampoline<'a> {428/// Call the target function of this trampoline, passing in [DataValue]s using a compiled trampoline.429pub fn call(&self, compiled: &CompiledTestFile, arguments: &[DataValue]) -> Vec<DataValue> {430let mut values = UnboxedValues::make_arguments(arguments, &self.func_signature);431let arguments_address = values.as_mut_ptr();432433let function_ptr = self.module.get_finalized_function(self.func_id);434let trampoline_ptr = self.module.get_finalized_function(self.trampoline_id);435436COMPILED_TEST_FILE.set(compiled as *const _);437unsafe {438self.call_raw(trampoline_ptr, function_ptr, arguments_address);439}440COMPILED_TEST_FILE.set(std::ptr::null());441442values.collect_returns(&self.func_signature)443}444445unsafe fn call_raw(446&self,447trampoline_ptr: *const u8,448function_ptr: *const u8,449arguments_address: *mut u128,450) {451match self.module.isa().triple().architecture {452// For the pulley target this is pulley bytecode, not machine code,453// so run the interpreter.454Architecture::Pulley32455| Architecture::Pulley64456| Architecture::Pulley32be457| Architecture::Pulley64be => {458let mut state = pulley::Vm::new();459unsafe {460state.call(461NonNull::new(trampoline_ptr.cast_mut()).unwrap(),462&[463pulley::XRegVal::new_ptr(function_ptr.cast_mut()).into(),464pulley::XRegVal::new_ptr(arguments_address).into(),465],466[],467);468}469}470471// Other targets natively execute this machine code.472_ => {473let callable_trampoline: fn(*const u8, *mut u128) -> () =474unsafe { mem::transmute(trampoline_ptr) };475callable_trampoline(function_ptr, arguments_address);476}477}478}479}480481/// Compilation Error when compiling a function.482#[derive(Error, Debug)]483pub enum CompilationError {484/// Cranelift codegen error.485#[error("Cranelift codegen error")]486CodegenError(#[from] CodegenError),487/// Module Error488#[error("Module error")]489ModuleError(#[from] ModuleError),490/// Memory mapping error.491#[error("Memory mapping error")]492IoError(#[from] std::io::Error),493}494495/// A container for laying out the [ValueData]s in memory in a way that the [Trampoline] can496/// understand.497struct UnboxedValues(Vec<u128>);498499impl UnboxedValues {500/// The size in bytes of each slot location in the allocated [DataValue]s. Though [DataValue]s501/// could be smaller than 16 bytes (e.g. `I16`), this simplifies the creation of the [DataValue]502/// array and could be used to align the slots to the largest used [DataValue] (i.e. 128-bit503/// vectors).504const SLOT_SIZE: usize = 16;505506/// Build the arguments vector for passing the [DataValue]s into the [Trampoline]. The size of507/// `u128` used here must match [Trampoline::SLOT_SIZE].508pub fn make_arguments(arguments: &[DataValue], signature: &ir::Signature) -> Self {509assert_eq!(arguments.len(), signature.params.len());510let mut values_vec = vec![0; max(signature.params.len(), signature.returns.len())];511512// Store the argument values into `values_vec`.513for ((arg, slot), param) in arguments.iter().zip(&mut values_vec).zip(&signature.params) {514assert!(515arg.ty() == param.value_type || arg.is_vector(),516"argument type mismatch: {} != {}",517arg.ty(),518param.value_type519);520unsafe {521arg.write_value_to(slot);522}523}524525Self(values_vec)526}527528/// Return a pointer to the underlying memory for passing to the trampoline.529pub fn as_mut_ptr(&mut self) -> *mut u128 {530self.0.as_mut_ptr()531}532533/// Collect the returned [DataValue]s into a [Vec]. The size of `u128` used here must match534/// [Trampoline::SLOT_SIZE].535pub fn collect_returns(&self, signature: &ir::Signature) -> Vec<DataValue> {536assert!(self.0.len() >= signature.returns.len());537let mut returns = Vec::with_capacity(signature.returns.len());538539// Extract the returned values from this vector.540for (slot, param) in self.0.iter().zip(&signature.returns) {541let value = unsafe { DataValue::read_value_from(slot, param.value_type) };542returns.push(value);543}544545returns546}547}548549/// Build the Cranelift IR for moving the memory-allocated [DataValue]s to their correct location550/// (e.g. register, stack) prior to calling a [CompiledFunction]. The [Function] returned by551/// [make_trampoline] is compiled to a [Trampoline]. Note that this uses the [TargetIsa]'s default552/// calling convention so we must also check that the [CompiledFunction] has the same calling553/// convention (see [TestFileCompiler::compile]).554fn make_trampoline(name: UserFuncName, signature: &ir::Signature, isa: &dyn TargetIsa) -> Function {555// Create the trampoline signature: (callee_address: pointer, values_vec: pointer) -> ()556let pointer_type = isa.pointer_type();557let mut wrapper_sig = ir::Signature::new(isa.frontend_config().default_call_conv);558wrapper_sig.params.push(ir::AbiParam::new(pointer_type)); // Add the `callee_address` parameter.559wrapper_sig.params.push(ir::AbiParam::new(pointer_type)); // Add the `values_vec` parameter.560561let mut func = ir::Function::with_name_signature(name, wrapper_sig);562563// The trampoline has a single block filled with loads, one call to callee_address, and some loads.564let mut builder_context = FunctionBuilderContext::new();565let mut builder = FunctionBuilder::new(&mut func, &mut builder_context);566let block0 = builder.create_block();567builder.append_block_params_for_function_params(block0);568builder.switch_to_block(block0);569builder.seal_block(block0);570571// Extract the incoming SSA values.572let (callee_value, values_vec_ptr_val) = {573let params = builder.func.dfg.block_params(block0);574(params[0], params[1])575};576577// Load the argument values out of `values_vec`.578let callee_args = signature579.params580.iter()581.enumerate()582.map(|(i, param)| {583// We always store vector types in little-endian byte order as DataValue.584let mut flags = ir::MemFlags::trusted();585if param.value_type.is_vector() {586flags.set_endianness(ir::Endianness::Little);587}588589// Load the value.590builder.ins().load(591param.value_type,592flags,593values_vec_ptr_val,594(i * UnboxedValues::SLOT_SIZE) as i32,595)596})597.collect::<Vec<_>>();598599// Call the passed function.600let new_sig = builder.import_signature(signature.clone());601let call = builder602.ins()603.call_indirect(new_sig, callee_value, &callee_args);604605// Store the return values into `values_vec`.606let results = builder.func.dfg.inst_results(call).to_vec();607for ((i, value), param) in results.iter().enumerate().zip(&signature.returns) {608// We always store vector types in little-endian byte order as DataValue.609let mut flags = ir::MemFlags::trusted();610if param.value_type.is_vector() {611flags.set_endianness(ir::Endianness::Little);612}613// Store the value.614builder.ins().store(615flags,616*value,617values_vec_ptr_val,618(i * UnboxedValues::SLOT_SIZE) as i32,619);620}621622builder.ins().return_(&[]);623builder.finalize();624625func626}627628/// Hostcall invoked directly from a compiled function body to test629/// exception throws.630///631/// This function does not return normally: it either uses the632/// unwinder to jump directly to a Cranelift frame further up the633/// stack, if a handler is found; or it panics, if not.634#[cfg(any(635target_arch = "x86_64",636target_arch = "aarch64",637target_arch = "s390x",638target_arch = "riscv64"639))]640extern "C-unwind" fn __cranelift_throw(641entry_fp: usize,642exit_fp: usize,643exit_pc: usize,644tag: u32,645payload1: usize,646payload2: usize,647) -> ! {648let compiled_test_file = unsafe { &*COMPILED_TEST_FILE.get() };649let unwind_host = wasmtime_unwinder::UnwindHost;650let frame_handler = |frame: &wasmtime_unwinder::Frame| -> Option<(usize, usize)> {651let (base, table) = compiled_test_file652.module653.as_ref()654.unwrap()655.lookup_wasmtime_exception_data(frame.pc())?;656let relative_pc = u32::try_from(657frame658.pc()659.checked_sub(base)660.expect("module lookup did not return a module base below the PC"),661)662.expect("module larger than 4GiB");663664table665.lookup_pc_tag(relative_pc, tag)666.map(|(frame_offset, handler)| {667let handler_sp = frame668.fp()669.wrapping_sub(usize::try_from(frame_offset).unwrap());670let handler_pc = base671.checked_add(usize::try_from(handler).unwrap())672.expect("Handler address computation overflowed");673(handler_pc, handler_sp)674})675};676unsafe {677match wasmtime_unwinder::Handler::find(678&unwind_host,679frame_handler,680exit_pc,681exit_fp,682entry_fp,683) {684Some(handler) => handler.resume_tailcc(payload1, payload2),685None => {686panic!("Expected a handler to exit for throw of tag {tag} at pc {exit_pc:x}");687}688}689}690}691692#[cfg(not(any(693target_arch = "x86_64",694target_arch = "aarch64",695target_arch = "s390x",696target_arch = "riscv64"697)))]698extern "C-unwind" fn __cranelift_throw(699_entry_fp: usize,700_exit_fp: usize,701_exit_pc: usize,702_tag: u32,703_payload1: usize,704_payload2: usize,705) -> ! {706panic!("Throw not implemented on platforms without native backends.");707}708709#[cfg(target_arch = "x86_64")]710use std::arch::x86_64::__m128i;711#[cfg(target_arch = "x86_64")]712#[expect(713improper_ctypes_definitions,714reason = "manually verified to work for now"715)]716extern "C" fn __cranelift_x86_pshufb(a: __m128i, b: __m128i) -> __m128i {717union U {718reg: __m128i,719mem: [u8; 16],720}721722unsafe {723let a = U { reg: a }.mem;724let b = U { reg: b }.mem;725726let select = |arr: &[u8; 16], byte: u8| {727if byte & 0x80 != 0 {7280x00729} else {730arr[(byte & 0xf) as usize]731}732};733734U {735mem: [736select(&a, b[0]),737select(&a, b[1]),738select(&a, b[2]),739select(&a, b[3]),740select(&a, b[4]),741select(&a, b[5]),742select(&a, b[6]),743select(&a, b[7]),744select(&a, b[8]),745select(&a, b[9]),746select(&a, b[10]),747select(&a, b[11]),748select(&a, b[12]),749select(&a, b[13]),750select(&a, b[14]),751select(&a, b[15]),752],753}754.reg755}756}757758#[cfg(test)]759mod test {760use super::*;761use cranelift_reader::{ParseOptions, parse_functions, parse_test};762763fn parse(code: &str) -> Function {764parse_functions(code).unwrap().into_iter().nth(0).unwrap()765}766767#[test]768fn nop() {769// Skip this test when cranelift doesn't support the native platform.770if cranelift_native::builder().is_err() {771return;772}773let code = String::from(774"775test run776function %test() -> i8 {777block0:778nop779v1 = iconst.i8 -1780return v1781}",782);783let ctrl_plane = &mut ControlPlane::default();784785// extract function786let test_file = parse_test(code.as_str(), ParseOptions::default()).unwrap();787assert_eq!(1, test_file.functions.len());788let function = test_file.functions[0].0.clone();789790// execute function791let mut compiler = TestFileCompiler::with_default_host_isa().unwrap();792compiler.declare_function(&function).unwrap();793compiler794.define_function(function.clone(), ctrl_plane)795.unwrap();796compiler797.create_trampoline_for_function(&function, ctrl_plane)798.unwrap();799let compiled = compiler.compile().unwrap();800let trampoline = compiled.get_trampoline(&function).unwrap();801let returned = trampoline.call(&compiled, &[]);802assert_eq!(returned, vec![DataValue::I8(-1)])803}804805#[test]806fn trampolines() {807// Skip this test when cranelift doesn't support the native platform.808if cranelift_native::builder().is_err() {809return;810}811let function = parse(812"813function %test(f32, i8, i64x2, i8) -> f32x4, i64 {814block0(v0: f32, v1: i8, v2: i64x2, v3: i8):815v4 = vconst.f32x4 [0x0.1 0x0.2 0x0.3 0x0.4]816v5 = iconst.i64 -1817return v4, v5818}",819);820821let compiler = TestFileCompiler::with_default_host_isa().unwrap();822let trampoline = make_trampoline(823UserFuncName::user(0, 0),824&function.signature,825compiler.module.isa(),826);827println!("{trampoline}");828assert!(format!("{trampoline}").ends_with(829"sig0 = (f32, i8, i64x2, i8) -> f32x4, i64 fast830831block0(v0: i64, v1: i64):832v2 = load.f32 notrap aligned v1833v3 = load.i8 notrap aligned v1+16834v4 = load.i64x2 notrap aligned little v1+32835v5 = load.i8 notrap aligned v1+48836v6, v7 = call_indirect sig0, v0(v2, v3, v4, v5)837store notrap aligned little v6, v1838store notrap aligned v7, v1+16839return840}841"842));843}844}845846847