/src/wasmtime/cranelift/filetests/src/function_runner.rs
Line | Count | Source |
1 | | //! Provides functionality for compiling and running CLIF IR for `run` tests. |
2 | | use anyhow::{Context as _, Result, anyhow}; |
3 | | use core::mem; |
4 | | use cranelift::prelude::Imm64; |
5 | | use cranelift_codegen::cursor::{Cursor, FuncCursor}; |
6 | | use cranelift_codegen::data_value::DataValue; |
7 | | use cranelift_codegen::ir::{ |
8 | | ExternalName, Function, InstBuilder, InstructionData, LibCall, Opcode, Signature, |
9 | | UserExternalName, UserFuncName, |
10 | | }; |
11 | | use cranelift_codegen::isa::{OwnedTargetIsa, TargetIsa}; |
12 | | use cranelift_codegen::{CodegenError, Context, ir, settings}; |
13 | | use cranelift_control::ControlPlane; |
14 | | use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext}; |
15 | | use cranelift_jit::{JITBuilder, JITModule}; |
16 | | use cranelift_module::{FuncId, Linkage, Module, ModuleError}; |
17 | | use cranelift_native::builder_with_options; |
18 | | use cranelift_reader::TestFile; |
19 | | use pulley_interpreter::interp as pulley; |
20 | | use std::cell::Cell; |
21 | | use std::cmp::max; |
22 | | use std::collections::hash_map::Entry; |
23 | | use std::collections::{HashMap, HashSet}; |
24 | | use std::ptr::NonNull; |
25 | | use target_lexicon::Architecture; |
26 | | use thiserror::Error; |
27 | | |
28 | | const TESTFILE_NAMESPACE: u32 = 0; |
29 | | |
30 | | /// Holds information about a previously defined function. |
31 | | #[derive(Debug)] |
32 | | struct DefinedFunction { |
33 | | /// This is the name that the function is internally known as. |
34 | | /// |
35 | | /// The JIT module does not support linking / calling [TestcaseName]'s, so |
36 | | /// we rename every function into a [UserExternalName]. |
37 | | /// |
38 | | /// By doing this we also have to rename functions that previously were using a |
39 | | /// [UserFuncName], since they may now be in conflict after the renaming that |
40 | | /// occurred. |
41 | | new_name: UserExternalName, |
42 | | |
43 | | /// The function signature |
44 | | signature: ir::Signature, |
45 | | |
46 | | /// JIT [FuncId] |
47 | | func_id: FuncId, |
48 | | } |
49 | | |
50 | | /// Compile a test case. |
51 | | /// |
52 | | /// Several Cranelift functions need the ability to run Cranelift IR (e.g. `test_run`); this |
53 | | /// [TestFileCompiler] provides a way for compiling Cranelift [Function]s to |
54 | | /// `CompiledFunction`s and subsequently calling them through the use of a `Trampoline`. As its |
55 | | /// name indicates, this compiler is limited: any functionality that requires knowledge of things |
56 | | /// outside the [Function] will likely not work (e.g. global values, calls). For an example of this |
57 | | /// "outside-of-function" functionality, see `cranelift_jit::backend::JITBackend`. |
58 | | /// |
59 | | /// ``` |
60 | | /// # let ctrl_plane = &mut Default::default(); |
61 | | /// use cranelift_filetests::TestFileCompiler; |
62 | | /// use cranelift_reader::parse_functions; |
63 | | /// use cranelift_codegen::data_value::DataValue; |
64 | | /// |
65 | | /// let code = "test run \n function %add(i32, i32) -> i32 { block0(v0:i32, v1:i32): v2 = iadd v0, v1 return v2 }".into(); |
66 | | /// let func = parse_functions(code).unwrap().into_iter().nth(0).unwrap(); |
67 | | /// let Ok(mut compiler) = TestFileCompiler::with_default_host_isa() else { |
68 | | /// return; |
69 | | /// }; |
70 | | /// compiler.declare_function(&func).unwrap(); |
71 | | /// compiler.define_function(func.clone(), ctrl_plane).unwrap(); |
72 | | /// compiler.create_trampoline_for_function(&func, ctrl_plane).unwrap(); |
73 | | /// let compiled = compiler.compile().unwrap(); |
74 | | /// let trampoline = compiled.get_trampoline(&func).unwrap(); |
75 | | /// |
76 | | /// let returned = trampoline.call(&compiled, &vec![DataValue::I32(2), DataValue::I32(40)]); |
77 | | /// assert_eq!(vec![DataValue::I32(42)], returned); |
78 | | /// ``` |
79 | | pub struct TestFileCompiler { |
80 | | module: JITModule, |
81 | | ctx: Context, |
82 | | |
83 | | /// Holds info about the functions that have already been defined. |
84 | | /// Use look them up by their original [UserFuncName] since that's how the caller |
85 | | /// passes them to us. |
86 | | defined_functions: HashMap<UserFuncName, DefinedFunction>, |
87 | | |
88 | | /// We deduplicate trampolines by the signature of the function that they target. |
89 | | /// This map holds as a key the [Signature] of the target function, and as a value |
90 | | /// the [UserFuncName] of the trampoline for that [Signature]. |
91 | | /// |
92 | | /// The trampoline is defined in `defined_functions` as any other regular function. |
93 | | trampolines: HashMap<Signature, UserFuncName>, |
94 | | } |
95 | | |
96 | | impl TestFileCompiler { |
97 | | /// Build a [TestFileCompiler] from a [TargetIsa]. For functions to be runnable on the |
98 | | /// host machine, this [TargetIsa] must match the host machine's ISA (see |
99 | | /// [TestFileCompiler::with_host_isa]). |
100 | 8.59k | pub fn new(isa: OwnedTargetIsa) -> Self { |
101 | 8.59k | let mut builder = JITBuilder::with_isa(isa, cranelift_module::default_libcall_names()); |
102 | 8.59k | builder.symbol_lookup_fn(Box::new(lookup_libcall)); |
103 | | |
104 | | // On Unix platforms force `libm` to get linked into this executable |
105 | | // because tests that use libcalls rely on this library being present. |
106 | | // Without this it's been seen that when cross-compiled to riscv64 the |
107 | | // final binary doesn't link in `libm`. |
108 | | #[cfg(unix)] |
109 | | { |
110 | | unsafe extern "C" { |
111 | | safe fn cosf(f: f32) -> f32; |
112 | | } |
113 | 8.59k | let f = std::hint::black_box(1.2_f32); |
114 | 8.59k | assert_eq!(f.cos(), cosf(f)); |
115 | | } |
116 | | |
117 | 8.59k | let module = JITModule::new(builder); |
118 | 8.59k | let ctx = module.make_context(); |
119 | | |
120 | 8.59k | Self { |
121 | 8.59k | module, |
122 | 8.59k | ctx, |
123 | 8.59k | defined_functions: HashMap::new(), |
124 | 8.59k | trampolines: HashMap::new(), |
125 | 8.59k | } |
126 | 8.59k | } |
127 | | |
128 | | /// Build a [TestFileCompiler] using the host machine's ISA and the passed flags. |
129 | 0 | pub fn with_host_isa(flags: settings::Flags) -> Result<Self> { |
130 | 0 | let builder = builder_with_options(true) |
131 | 0 | .map_err(anyhow::Error::msg) |
132 | 0 | .context("Unable to build a TargetIsa for the current host")?; |
133 | 0 | let isa = builder.finish(flags)?; |
134 | 0 | Ok(Self::new(isa)) |
135 | 0 | } |
136 | | |
137 | | /// Build a [TestFileCompiler] using the host machine's ISA and the default flags for this |
138 | | /// ISA. |
139 | 0 | pub fn with_default_host_isa() -> Result<Self> { |
140 | 0 | let flags = settings::Flags::new(settings::builder()); |
141 | 0 | Self::with_host_isa(flags) |
142 | 0 | } |
143 | | |
144 | | /// Declares and compiles all functions in `functions`. Additionally creates a trampoline for |
145 | | /// each one of them. |
146 | 8.59k | pub fn add_functions( |
147 | 8.59k | &mut self, |
148 | 8.59k | functions: &[Function], |
149 | 8.59k | ctrl_planes: Vec<ControlPlane>, |
150 | 8.59k | ) -> Result<()> { |
151 | | // Declare all functions in the file, so that they may refer to each other. |
152 | 14.1k | for func in functions { |
153 | 14.1k | self.declare_function(func)?; |
154 | | } |
155 | | |
156 | 8.59k | let ctrl_planes = ctrl_planes |
157 | 8.59k | .into_iter() |
158 | 8.59k | .chain(std::iter::repeat(ControlPlane::default())); |
159 | | |
160 | | // Define all functions and trampolines |
161 | 14.1k | for (func, ref mut ctrl_plane) in functions.iter().zip(ctrl_planes) { |
162 | 14.1k | self.define_function(func.clone(), ctrl_plane)?; |
163 | 14.1k | self.create_trampoline_for_function(func, ctrl_plane)?; |
164 | | } |
165 | | |
166 | 8.59k | Ok(()) |
167 | 8.59k | } |
168 | | |
169 | | /// Registers all functions in a [TestFile]. Additionally creates a trampoline for each one |
170 | | /// of them. |
171 | 0 | pub fn add_testfile(&mut self, testfile: &TestFile) -> Result<()> { |
172 | 0 | let functions = testfile |
173 | 0 | .functions |
174 | 0 | .iter() |
175 | 0 | .map(|(f, _)| f) |
176 | 0 | .cloned() |
177 | 0 | .collect::<Vec<_>>(); |
178 | | |
179 | 0 | self.add_functions(&functions[..], Vec::new())?; |
180 | 0 | Ok(()) |
181 | 0 | } |
182 | | |
183 | | /// Declares a function an registers it as a linkable and callable target internally |
184 | 24.3k | pub fn declare_function(&mut self, func: &Function) -> Result<()> { |
185 | 24.3k | let next_id = self.defined_functions.len() as u32; |
186 | 24.3k | match self.defined_functions.entry(func.name.clone()) { |
187 | | Entry::Occupied(_) => { |
188 | 0 | anyhow::bail!("Duplicate function with name {} found!", &func.name) |
189 | | } |
190 | 24.3k | Entry::Vacant(v) => { |
191 | 24.3k | let name = func.name.to_string(); |
192 | 24.3k | let func_id = |
193 | 24.3k | self.module |
194 | 24.3k | .declare_function(&name, Linkage::Local, &func.signature)?; |
195 | | |
196 | 24.3k | v.insert(DefinedFunction { |
197 | 24.3k | new_name: UserExternalName::new(TESTFILE_NAMESPACE, next_id), |
198 | 24.3k | signature: func.signature.clone(), |
199 | 24.3k | func_id, |
200 | 24.3k | }); |
201 | | } |
202 | | }; |
203 | | |
204 | 24.3k | Ok(()) |
205 | 24.3k | } |
206 | | |
207 | | /// Renames the function to its new [UserExternalName], as well as any other function that |
208 | | /// it may reference. |
209 | | /// |
210 | | /// We have to do this since the JIT cannot link Testcase functions. |
211 | 24.3k | fn apply_func_rename( |
212 | 24.3k | &self, |
213 | 24.3k | mut func: Function, |
214 | 24.3k | defined_func: &DefinedFunction, |
215 | 24.3k | ) -> Result<Function> { |
216 | | // First, rename the function |
217 | 24.3k | let func_original_name = func.name; |
218 | 24.3k | func.name = UserFuncName::User(defined_func.new_name.clone()); |
219 | | |
220 | | // Rename any functions that it references |
221 | | // Do this in stages to appease the borrow checker |
222 | 24.3k | let mut redefines = Vec::with_capacity(func.dfg.ext_funcs.len()); |
223 | 102k | for (ext_ref, ext_func) in &func.dfg.ext_funcs { |
224 | 102k | let old_name = match &ext_func.name { |
225 | 0 | ExternalName::TestCase(tc) => UserFuncName::Testcase(tc.clone()), |
226 | 17.0k | ExternalName::User(username) => { |
227 | 17.0k | UserFuncName::User(func.params.user_named_funcs()[*username].clone()) |
228 | | } |
229 | | // The other cases don't need renaming, so lets just continue... |
230 | 85.0k | _ => continue, |
231 | | }; |
232 | | |
233 | 17.0k | let target_df = self.defined_functions.get(&old_name).ok_or(anyhow!( |
234 | | "Undeclared function {} is referenced by {}!", |
235 | 17.0k | &old_name, |
236 | 17.0k | &func_original_name |
237 | 0 | ))?; |
238 | | |
239 | 17.0k | redefines.push((ext_ref, target_df.new_name.clone())); |
240 | | } |
241 | | |
242 | | // Now register the redefines |
243 | 24.3k | for (ext_ref, new_name) in redefines.into_iter() { |
244 | 17.0k | // Register the new name in the func, so that we can get a reference to it. |
245 | 17.0k | let new_name_ref = func.params.ensure_user_func_name(new_name); |
246 | 17.0k | |
247 | 17.0k | // Finally rename the ExtFunc |
248 | 17.0k | func.dfg.ext_funcs[ext_ref].name = ExternalName::User(new_name_ref); |
249 | 17.0k | } |
250 | | |
251 | 24.3k | Ok(func) |
252 | 24.3k | } |
253 | | |
254 | | /// Defines the body of a function |
255 | 24.3k | pub fn define_function( |
256 | 24.3k | &mut self, |
257 | 24.3k | mut func: Function, |
258 | 24.3k | ctrl_plane: &mut ControlPlane, |
259 | 24.3k | ) -> Result<()> { |
260 | 24.3k | Self::replace_hostcall_references(&mut func); |
261 | | |
262 | 24.3k | let defined_func = self |
263 | 24.3k | .defined_functions |
264 | 24.3k | .get(&func.name) |
265 | 24.3k | .ok_or(anyhow!("Undeclared function {} found!", &func.name))?; |
266 | | |
267 | 24.3k | self.ctx.func = self.apply_func_rename(func, defined_func)?; |
268 | 24.3k | self.module.define_function_with_control_plane( |
269 | 24.3k | defined_func.func_id, |
270 | 24.3k | &mut self.ctx, |
271 | 24.3k | ctrl_plane, |
272 | 0 | )?; |
273 | 24.3k | self.module.clear_context(&mut self.ctx); |
274 | 24.3k | Ok(()) |
275 | 24.3k | } |
276 | | |
277 | 24.3k | fn replace_hostcall_references(func: &mut Function) { |
278 | | // For every `func_addr` referring to a hostcall that we |
279 | | // define, replace with an `iconst` with the actual |
280 | | // address. Then modify the external func references to |
281 | | // harmless libcall references (that will be unused so |
282 | | // ignored). |
283 | 24.3k | let mut funcrefs_to_remove = HashSet::new(); |
284 | 24.3k | let mut cursor = FuncCursor::new(func); |
285 | 271k | while let Some(_block) = cursor.next_block() { |
286 | 3.48M | while let Some(inst) = cursor.next_inst() { |
287 | 3.24M | match &cursor.func.dfg.insts[inst] { |
288 | | InstructionData::FuncAddr { |
289 | | opcode: Opcode::FuncAddr, |
290 | 18.6k | func_ref, |
291 | | } => { |
292 | 18.6k | let ext_func = &cursor.func.dfg.ext_funcs[*func_ref]; |
293 | 18.6k | let hostcall_addr = match &ext_func.name { |
294 | 0 | ExternalName::TestCase(tc) if tc.raw() == b"__cranelift_throw" => { |
295 | 0 | Some((__cranelift_throw as *const ()).addr()) |
296 | | } |
297 | 18.6k | _ => None, |
298 | | }; |
299 | | |
300 | 18.6k | if let Some(addr) = hostcall_addr { |
301 | 0 | funcrefs_to_remove.insert(*func_ref); |
302 | 0 | cursor.func.dfg.insts[inst] = InstructionData::UnaryImm { |
303 | 0 | opcode: Opcode::Iconst, |
304 | 0 | imm: Imm64::new(addr as i64), |
305 | 0 | }; |
306 | 18.6k | } |
307 | | } |
308 | 3.22M | _ => {} |
309 | | } |
310 | | } |
311 | | } |
312 | | |
313 | 24.3k | for to_remove in funcrefs_to_remove { |
314 | 0 | func.dfg.ext_funcs[to_remove].name = ExternalName::LibCall(LibCall::Probestack); |
315 | 0 | } |
316 | 24.3k | } |
317 | | |
318 | | /// Creates and registers a trampoline for a function if none exists. |
319 | 14.1k | pub fn create_trampoline_for_function( |
320 | 14.1k | &mut self, |
321 | 14.1k | func: &Function, |
322 | 14.1k | ctrl_plane: &mut ControlPlane, |
323 | 14.1k | ) -> Result<()> { |
324 | 14.1k | if !self.defined_functions.contains_key(&func.name) { |
325 | 0 | anyhow::bail!("Undeclared function {} found!", &func.name); |
326 | 14.1k | } |
327 | | |
328 | | // Check if a trampoline for this function signature already exists |
329 | 14.1k | if self.trampolines.contains_key(&func.signature) { |
330 | 4.00k | return Ok(()); |
331 | 10.1k | } |
332 | | |
333 | | // Create a trampoline and register it |
334 | 10.1k | let name = UserFuncName::user(TESTFILE_NAMESPACE, self.defined_functions.len() as u32); |
335 | 10.1k | let trampoline = make_trampoline(name.clone(), &func.signature, self.module.isa()); |
336 | | |
337 | 10.1k | self.declare_function(&trampoline)?; |
338 | 10.1k | self.define_function(trampoline, ctrl_plane)?; |
339 | | |
340 | 10.1k | self.trampolines.insert(func.signature.clone(), name); |
341 | | |
342 | 10.1k | Ok(()) |
343 | 14.1k | } |
344 | | |
345 | | /// Finalize this TestFile and link all functions. |
346 | 8.59k | pub fn compile(mut self) -> Result<CompiledTestFile, CompilationError> { |
347 | | // Finalize the functions which we just defined, which resolves any |
348 | | // outstanding relocations (patching in addresses, now that they're |
349 | | // available). |
350 | 8.59k | self.module.finalize_definitions()?; |
351 | | |
352 | 8.59k | Ok(CompiledTestFile { |
353 | 8.59k | module: Some(self.module), |
354 | 8.59k | defined_functions: self.defined_functions, |
355 | 8.59k | trampolines: self.trampolines, |
356 | 8.59k | }) |
357 | 8.59k | } |
358 | | } |
359 | | |
360 | | /// A finalized Test File |
361 | | pub struct CompiledTestFile { |
362 | | /// We need to store [JITModule] since it contains the underlying memory for the functions. |
363 | | /// Store it in an [Option] so that we can later drop it. |
364 | | module: Option<JITModule>, |
365 | | |
366 | | /// Holds info about the functions that have been registered in `module`. |
367 | | /// See [TestFileCompiler] for more info. |
368 | | defined_functions: HashMap<UserFuncName, DefinedFunction>, |
369 | | |
370 | | /// Trampolines available in this [JITModule]. |
371 | | /// See [TestFileCompiler] for more info. |
372 | | trampolines: HashMap<Signature, UserFuncName>, |
373 | | } |
374 | | |
375 | | impl CompiledTestFile { |
376 | | /// Return a trampoline for calling. |
377 | | /// |
378 | | /// Returns None if [TestFileCompiler::create_trampoline_for_function] wasn't called for this function. |
379 | 8.59k | pub fn get_trampoline(&self, func: &Function) -> Option<Trampoline<'_>> { |
380 | 8.59k | let defined_func = self.defined_functions.get(&func.name)?; |
381 | 8.59k | let trampoline_id = self |
382 | 8.59k | .trampolines |
383 | 8.59k | .get(&func.signature) |
384 | 8.59k | .and_then(|name| self.defined_functions.get(name)) |
385 | 8.59k | .map(|df| df.func_id)?; |
386 | | Some(Trampoline { |
387 | 8.59k | module: self.module.as_ref()?, |
388 | 8.59k | func_id: defined_func.func_id, |
389 | 8.59k | func_signature: &defined_func.signature, |
390 | 8.59k | trampoline_id, |
391 | | }) |
392 | 8.59k | } |
393 | | } |
394 | | |
395 | | impl Drop for CompiledTestFile { |
396 | 8.59k | fn drop(&mut self) { |
397 | | // Freeing the module's memory erases the compiled functions. |
398 | | // This should be safe since their pointers never leave this struct. |
399 | 8.59k | unsafe { self.module.take().unwrap().free_memory() } |
400 | 8.59k | } |
401 | | } |
402 | | |
403 | | std::thread_local! { |
404 | | /// TLS slot used to store a CompiledTestFile reference so that it |
405 | | /// can be recovered when a hostcall (such as the exception-throw |
406 | | /// handler) is invoked. |
407 | | pub static COMPILED_TEST_FILE: Cell<*const CompiledTestFile> = Cell::new(std::ptr::null()); |
408 | | } |
409 | | |
410 | | /// A callable trampoline |
411 | | pub struct Trampoline<'a> { |
412 | | module: &'a JITModule, |
413 | | func_id: FuncId, |
414 | | func_signature: &'a Signature, |
415 | | trampoline_id: FuncId, |
416 | | } |
417 | | |
418 | | impl<'a> Trampoline<'a> { |
419 | | /// Call the target function of this trampoline, passing in [DataValue]s using a compiled trampoline. |
420 | 13.2k | pub fn call(&self, compiled: &CompiledTestFile, arguments: &[DataValue]) -> Vec<DataValue> { |
421 | 13.2k | let mut values = UnboxedValues::make_arguments(arguments, &self.func_signature); |
422 | 13.2k | let arguments_address = values.as_mut_ptr(); |
423 | | |
424 | 13.2k | let function_ptr = self.module.get_finalized_function(self.func_id); |
425 | 13.2k | let trampoline_ptr = self.module.get_finalized_function(self.trampoline_id); |
426 | | |
427 | 13.2k | COMPILED_TEST_FILE.set(compiled as *const _); |
428 | 13.2k | unsafe { |
429 | 13.2k | self.call_raw(trampoline_ptr, function_ptr, arguments_address); |
430 | 13.2k | } |
431 | 13.2k | COMPILED_TEST_FILE.set(std::ptr::null()); |
432 | | |
433 | 13.2k | values.collect_returns(&self.func_signature) |
434 | 13.2k | } |
435 | | |
436 | 13.2k | unsafe fn call_raw( |
437 | 13.2k | &self, |
438 | 13.2k | trampoline_ptr: *const u8, |
439 | 13.2k | function_ptr: *const u8, |
440 | 13.2k | arguments_address: *mut u128, |
441 | 13.2k | ) { |
442 | 13.2k | match self.module.isa().triple().architecture { |
443 | | // For the pulley target this is pulley bytecode, not machine code, |
444 | | // so run the interpreter. |
445 | | Architecture::Pulley32 |
446 | | | Architecture::Pulley64 |
447 | | | Architecture::Pulley32be |
448 | | | Architecture::Pulley64be => { |
449 | 0 | let mut state = pulley::Vm::new().unwrap(); |
450 | 0 | unsafe { |
451 | 0 | state.call( |
452 | 0 | NonNull::new(trampoline_ptr.cast_mut()).unwrap(), |
453 | 0 | &[ |
454 | 0 | pulley::XRegVal::new_ptr(function_ptr.cast_mut()).into(), |
455 | 0 | pulley::XRegVal::new_ptr(arguments_address).into(), |
456 | 0 | ], |
457 | 0 | [], |
458 | 0 | ); |
459 | 0 | } |
460 | | } |
461 | | |
462 | | // Other targets natively execute this machine code. |
463 | 13.2k | _ => { |
464 | 13.2k | let callable_trampoline: fn(*const u8, *mut u128) -> () = |
465 | 13.2k | unsafe { mem::transmute(trampoline_ptr) }; |
466 | 13.2k | callable_trampoline(function_ptr, arguments_address); |
467 | 13.2k | } |
468 | | } |
469 | 13.2k | } |
470 | | } |
471 | | |
472 | | /// Compilation Error when compiling a function. |
473 | | #[derive(Error, Debug)] |
474 | | pub enum CompilationError { |
475 | | /// Cranelift codegen error. |
476 | | #[error("Cranelift codegen error")] |
477 | | CodegenError(#[from] CodegenError), |
478 | | /// Module Error |
479 | | #[error("Module error")] |
480 | | ModuleError(#[from] ModuleError), |
481 | | /// Memory mapping error. |
482 | | #[error("Memory mapping error")] |
483 | | IoError(#[from] std::io::Error), |
484 | | } |
485 | | |
486 | | /// A container for laying out the [ValueData]s in memory in a way that the [Trampoline] can |
487 | | /// understand. |
488 | | struct UnboxedValues(Vec<u128>); |
489 | | |
490 | | impl UnboxedValues { |
491 | | /// The size in bytes of each slot location in the allocated [DataValue]s. Though [DataValue]s |
492 | | /// could be smaller than 16 bytes (e.g. `I16`), this simplifies the creation of the [DataValue] |
493 | | /// array and could be used to align the slots to the largest used [DataValue] (i.e. 128-bit |
494 | | /// vectors). |
495 | | const SLOT_SIZE: usize = 16; |
496 | | |
497 | | /// Build the arguments vector for passing the [DataValue]s into the [Trampoline]. The size of |
498 | | /// `u128` used here must match [Trampoline::SLOT_SIZE]. |
499 | 13.2k | pub fn make_arguments(arguments: &[DataValue], signature: &ir::Signature) -> Self { |
500 | 13.2k | assert_eq!(arguments.len(), signature.params.len()); |
501 | 13.2k | let mut values_vec = vec![0; max(signature.params.len(), signature.returns.len())]; |
502 | | |
503 | | // Store the argument values into `values_vec`. |
504 | 154k | for ((arg, slot), param) in arguments.iter().zip(&mut values_vec).zip(&signature.params) { |
505 | 154k | assert!( |
506 | 154k | arg.ty() == param.value_type || arg.is_vector(), |
507 | | "argument type mismatch: {} != {}", |
508 | 0 | arg.ty(), |
509 | | param.value_type |
510 | | ); |
511 | 154k | unsafe { |
512 | 154k | arg.write_value_to(slot); |
513 | 154k | } |
514 | | } |
515 | | |
516 | 13.2k | Self(values_vec) |
517 | 13.2k | } |
518 | | |
519 | | /// Return a pointer to the underlying memory for passing to the trampoline. |
520 | 13.2k | pub fn as_mut_ptr(&mut self) -> *mut u128 { |
521 | 13.2k | self.0.as_mut_ptr() |
522 | 13.2k | } |
523 | | |
524 | | /// Collect the returned [DataValue]s into a [Vec]. The size of `u128` used here must match |
525 | | /// [Trampoline::SLOT_SIZE]. |
526 | 13.2k | pub fn collect_returns(&self, signature: &ir::Signature) -> Vec<DataValue> { |
527 | 13.2k | assert!(self.0.len() >= signature.returns.len()); |
528 | 13.2k | let mut returns = Vec::with_capacity(signature.returns.len()); |
529 | | |
530 | | // Extract the returned values from this vector. |
531 | 138k | for (slot, param) in self.0.iter().zip(&signature.returns) { |
532 | 138k | let value = unsafe { DataValue::read_value_from(slot, param.value_type) }; |
533 | 138k | returns.push(value); |
534 | 138k | } |
535 | | |
536 | 13.2k | returns |
537 | 13.2k | } |
538 | | } |
539 | | |
540 | | /// Build the Cranelift IR for moving the memory-allocated [DataValue]s to their correct location |
541 | | /// (e.g. register, stack) prior to calling a [CompiledFunction]. The [Function] returned by |
542 | | /// [make_trampoline] is compiled to a [Trampoline]. Note that this uses the [TargetIsa]'s default |
543 | | /// calling convention so we must also check that the [CompiledFunction] has the same calling |
544 | | /// convention (see [TestFileCompiler::compile]). |
545 | 10.1k | fn make_trampoline(name: UserFuncName, signature: &ir::Signature, isa: &dyn TargetIsa) -> Function { |
546 | | // Create the trampoline signature: (callee_address: pointer, values_vec: pointer) -> () |
547 | 10.1k | let pointer_type = isa.pointer_type(); |
548 | 10.1k | let mut wrapper_sig = ir::Signature::new(isa.frontend_config().default_call_conv); |
549 | 10.1k | wrapper_sig.params.push(ir::AbiParam::new(pointer_type)); // Add the `callee_address` parameter. |
550 | 10.1k | wrapper_sig.params.push(ir::AbiParam::new(pointer_type)); // Add the `values_vec` parameter. |
551 | | |
552 | 10.1k | let mut func = ir::Function::with_name_signature(name, wrapper_sig); |
553 | | |
554 | | // The trampoline has a single block filled with loads, one call to callee_address, and some loads. |
555 | 10.1k | let mut builder_context = FunctionBuilderContext::new(); |
556 | 10.1k | let mut builder = FunctionBuilder::new(&mut func, &mut builder_context); |
557 | 10.1k | let block0 = builder.create_block(); |
558 | 10.1k | builder.append_block_params_for_function_params(block0); |
559 | 10.1k | builder.switch_to_block(block0); |
560 | 10.1k | builder.seal_block(block0); |
561 | | |
562 | | // Extract the incoming SSA values. |
563 | 10.1k | let (callee_value, values_vec_ptr_val) = { |
564 | 10.1k | let params = builder.func.dfg.block_params(block0); |
565 | 10.1k | (params[0], params[1]) |
566 | 10.1k | }; |
567 | | |
568 | | // Load the argument values out of `values_vec`. |
569 | 10.1k | let callee_args = signature |
570 | 10.1k | .params |
571 | 10.1k | .iter() |
572 | 10.1k | .enumerate() |
573 | 123k | .map(|(i, param)| { |
574 | | // We always store vector types in little-endian byte order as DataValue. |
575 | 123k | let mut flags = ir::MemFlagsData::trusted(); |
576 | 123k | if param.value_type.is_vector() { |
577 | 53.0k | flags.set_endianness(ir::Endianness::Little); |
578 | 70.4k | } |
579 | | |
580 | | // Load the value. |
581 | 123k | builder.ins().load( |
582 | 123k | param.value_type, |
583 | 123k | flags, |
584 | 123k | values_vec_ptr_val, |
585 | 123k | (i * UnboxedValues::SLOT_SIZE) as i32, |
586 | | ) |
587 | 123k | }) |
588 | 10.1k | .collect::<Vec<_>>(); |
589 | | |
590 | | // Call the passed function. |
591 | 10.1k | let new_sig = builder.import_signature(signature.clone()); |
592 | 10.1k | let call = builder |
593 | 10.1k | .ins() |
594 | 10.1k | .call_indirect(new_sig, callee_value, &callee_args); |
595 | | |
596 | | // Store the return values into `values_vec`. |
597 | 10.1k | let results = builder.func.dfg.inst_results(call).to_vec(); |
598 | 112k | for ((i, value), param) in results.iter().enumerate().zip(&signature.returns) { |
599 | | // We always store vector types in little-endian byte order as DataValue. |
600 | 112k | let mut flags = ir::MemFlagsData::trusted(); |
601 | 112k | if param.value_type.is_vector() { |
602 | 70.4k | flags.set_endianness(ir::Endianness::Little); |
603 | 70.4k | } |
604 | | // Store the value. |
605 | 112k | builder.ins().store( |
606 | 112k | flags, |
607 | 112k | *value, |
608 | 112k | values_vec_ptr_val, |
609 | 112k | (i * UnboxedValues::SLOT_SIZE) as i32, |
610 | | ); |
611 | | } |
612 | | |
613 | 10.1k | builder.ins().return_(&[]); |
614 | 10.1k | builder.finalize(isa.frontend_config()); |
615 | | |
616 | 10.1k | func |
617 | 10.1k | } |
618 | | |
619 | | /// Hostcall invoked directly from a compiled function body to test |
620 | | /// exception throws. |
621 | | /// |
622 | | /// This function does not return normally: it either uses the |
623 | | /// unwinder to jump directly to a Cranelift frame further up the |
624 | | /// stack, if a handler is found; or it panics, if not. |
625 | | #[cfg(any( |
626 | | target_arch = "x86_64", |
627 | | target_arch = "aarch64", |
628 | | target_arch = "s390x", |
629 | | target_arch = "riscv64" |
630 | | ))] |
631 | 0 | extern "C-unwind" fn __cranelift_throw( |
632 | 0 | entry_fp: usize, |
633 | 0 | exit_fp: usize, |
634 | 0 | exit_pc: usize, |
635 | 0 | tag: u32, |
636 | 0 | payload1: usize, |
637 | 0 | payload2: usize, |
638 | 0 | ) -> ! { |
639 | 0 | let compiled_test_file = unsafe { &*COMPILED_TEST_FILE.get() }; |
640 | 0 | let unwind_host = wasmtime_unwinder::UnwindHost; |
641 | 0 | let frame_handler = |frame: &wasmtime_unwinder::Frame| -> Option<(usize, usize)> { |
642 | 0 | let (base, table) = compiled_test_file |
643 | 0 | .module |
644 | 0 | .as_ref() |
645 | 0 | .unwrap() |
646 | 0 | .lookup_wasmtime_exception_data(frame.pc())?; |
647 | 0 | let relative_pc = u32::try_from( |
648 | 0 | frame |
649 | 0 | .pc() |
650 | 0 | .checked_sub(base) |
651 | 0 | .expect("module lookup did not return a module base below the PC"), |
652 | | ) |
653 | 0 | .expect("module larger than 4GiB"); |
654 | | |
655 | 0 | let (frame_offset, mut handlers) = table.lookup_pc(relative_pc); |
656 | 0 | handlers |
657 | 0 | .find(|handler| handler.tag == Some(tag) || handler.tag.is_none()) |
658 | 0 | .map(|handler| { |
659 | 0 | let handler_sp = frame |
660 | 0 | .fp() |
661 | 0 | .wrapping_sub(usize::try_from(frame_offset.unwrap_or(0)).unwrap()); |
662 | 0 | let handler_pc = base |
663 | 0 | .checked_add(usize::try_from(handler.handler_offset).unwrap()) |
664 | 0 | .expect("Handler address computation overflowed"); |
665 | 0 | (handler_pc, handler_sp) |
666 | 0 | }) |
667 | 0 | }; |
668 | | unsafe { |
669 | 0 | match wasmtime_unwinder::Handler::find( |
670 | 0 | &unwind_host, |
671 | 0 | frame_handler, |
672 | 0 | exit_pc, |
673 | 0 | exit_fp, |
674 | 0 | entry_fp, |
675 | 0 | ) { |
676 | 0 | Some(handler) => handler.resume_tailcc(payload1, payload2), |
677 | | None => { |
678 | 0 | panic!("Expected a handler to exit for throw of tag {tag} at pc {exit_pc:x}"); |
679 | | } |
680 | | } |
681 | | } |
682 | | } |
683 | | |
684 | | #[cfg(not(any( |
685 | | target_arch = "x86_64", |
686 | | target_arch = "aarch64", |
687 | | target_arch = "s390x", |
688 | | target_arch = "riscv64" |
689 | | )))] |
690 | | extern "C-unwind" fn __cranelift_throw( |
691 | | _entry_fp: usize, |
692 | | _exit_fp: usize, |
693 | | _exit_pc: usize, |
694 | | _tag: u32, |
695 | | _payload1: usize, |
696 | | _payload2: usize, |
697 | | ) -> ! { |
698 | | panic!("Throw not implemented on platforms without native backends."); |
699 | | } |
700 | | |
701 | | // Manually define all libcalls here to avoid relying on `libm` or diverging |
702 | | // behavior across platforms from libm-like functionality. Note that this also |
703 | | // serves as insurance that the libcall implementation in the Cranelift |
704 | | // interpreter is the same as the libcall implementation used by compiled code. |
705 | | // This is important for differential fuzzing where manual invocations of |
706 | | // libcalls are expected to return the same result, so here they get identical |
707 | | // implementations. |
708 | 8.13k | fn lookup_libcall(name: &str) -> Option<*const u8> { |
709 | 8.13k | match name { |
710 | 8.13k | "ceil" => { |
711 | 1.60k | extern "C" fn ceil(a: f64) -> f64 { |
712 | 1.60k | a.ceil() |
713 | 1.60k | } |
714 | 1.34k | Some(ceil as *const u8) |
715 | | } |
716 | 6.79k | "ceilf" => { |
717 | 49.4k | extern "C" fn ceilf(a: f32) -> f32 { |
718 | 49.4k | a.ceil() |
719 | 49.4k | } |
720 | 4.71k | Some(ceilf as *const u8) |
721 | | } |
722 | 2.08k | "trunc" => { |
723 | 371 | extern "C" fn trunc(a: f64) -> f64 { |
724 | 371 | a.trunc() |
725 | 371 | } |
726 | 310 | Some(trunc as *const u8) |
727 | | } |
728 | 1.77k | "truncf" => { |
729 | 2.22k | extern "C" fn truncf(a: f32) -> f32 { |
730 | 2.22k | a.trunc() |
731 | 2.22k | } |
732 | 485 | Some(truncf as *const u8) |
733 | | } |
734 | 1.28k | "floor" => { |
735 | 1.02k | extern "C" fn floor(a: f64) -> f64 { |
736 | 1.02k | a.floor() |
737 | 1.02k | } |
738 | 635 | Some(floor as *const u8) |
739 | | } |
740 | 651 | "floorf" => { |
741 | 808 | extern "C" fn floorf(a: f32) -> f32 { |
742 | 808 | a.floor() |
743 | 808 | } |
744 | 651 | Some(floorf as *const u8) |
745 | | } |
746 | 0 | "nearbyint" => { |
747 | 0 | extern "C" fn nearbyint(a: f64) -> f64 { |
748 | 0 | a.round_ties_even() |
749 | 0 | } |
750 | 0 | Some(nearbyint as *const u8) |
751 | | } |
752 | 0 | "nearbyintf" => { |
753 | 0 | extern "C" fn nearbyintf(a: f32) -> f32 { |
754 | 0 | a.round_ties_even() |
755 | 0 | } |
756 | 0 | Some(nearbyintf as *const u8) |
757 | | } |
758 | 0 | "fma" => { |
759 | | // The `fma` function for `x86_64-pc-windows-gnu` is incorrect. Use |
760 | | // `libm`'s instead. See: |
761 | | // https://github.com/bytecodealliance/wasmtime/issues/4512 |
762 | 0 | extern "C" fn fma(a: f64, b: f64, c: f64) -> f64 { |
763 | | #[cfg(all(target_os = "windows", target_env = "gnu"))] |
764 | | return libm::fma(a, b, c); |
765 | | #[cfg(not(all(target_os = "windows", target_env = "gnu")))] |
766 | 0 | return a.mul_add(b, c); |
767 | 0 | } |
768 | 0 | Some(fma as *const u8) |
769 | | } |
770 | 0 | "fmaf" => { |
771 | 0 | extern "C" fn fmaf(a: f32, b: f32, c: f32) -> f32 { |
772 | | #[cfg(all(target_os = "windows", target_env = "gnu"))] |
773 | | return libm::fmaf(a, b, c); |
774 | | #[cfg(not(all(target_os = "windows", target_env = "gnu")))] |
775 | 0 | return a.mul_add(b, c); |
776 | 0 | } |
777 | 0 | Some(fmaf as *const u8) |
778 | | } |
779 | | |
780 | | #[cfg(target_arch = "x86_64")] |
781 | 0 | "__cranelift_x86_pshufb" => Some(__cranelift_x86_pshufb as *const u8), |
782 | | |
783 | 0 | _ => panic!("unknown libcall {name}"), |
784 | | } |
785 | 8.13k | } |
786 | | |
787 | | #[cfg(target_arch = "x86_64")] |
788 | | use std::arch::x86_64::__m128i; |
789 | | #[cfg(target_arch = "x86_64")] |
790 | | #[expect( |
791 | | improper_ctypes_definitions, |
792 | | reason = "manually verified to work for now" |
793 | | )] |
794 | 0 | extern "C" fn __cranelift_x86_pshufb(a: __m128i, b: __m128i) -> __m128i { |
795 | | union U { |
796 | | reg: __m128i, |
797 | | mem: [u8; 16], |
798 | | } |
799 | | |
800 | | unsafe { |
801 | 0 | let a = U { reg: a }.mem; |
802 | 0 | let b = U { reg: b }.mem; |
803 | | |
804 | 0 | let select = |arr: &[u8; 16], byte: u8| { |
805 | 0 | if byte & 0x80 != 0 { |
806 | 0 | 0x00 |
807 | | } else { |
808 | 0 | arr[(byte & 0xf) as usize] |
809 | | } |
810 | 0 | }; |
811 | | |
812 | 0 | U { |
813 | 0 | mem: [ |
814 | 0 | select(&a, b[0]), |
815 | 0 | select(&a, b[1]), |
816 | 0 | select(&a, b[2]), |
817 | 0 | select(&a, b[3]), |
818 | 0 | select(&a, b[4]), |
819 | 0 | select(&a, b[5]), |
820 | 0 | select(&a, b[6]), |
821 | 0 | select(&a, b[7]), |
822 | 0 | select(&a, b[8]), |
823 | 0 | select(&a, b[9]), |
824 | 0 | select(&a, b[10]), |
825 | 0 | select(&a, b[11]), |
826 | 0 | select(&a, b[12]), |
827 | 0 | select(&a, b[13]), |
828 | 0 | select(&a, b[14]), |
829 | 0 | select(&a, b[15]), |
830 | 0 | ], |
831 | 0 | } |
832 | 0 | .reg |
833 | | } |
834 | 0 | } |
835 | | |
836 | | #[cfg(test)] |
837 | | mod test { |
838 | | use super::*; |
839 | | use cranelift_reader::{ParseOptions, parse_functions, parse_test}; |
840 | | |
841 | | fn parse(code: &str) -> Function { |
842 | | parse_functions(code).unwrap().into_iter().nth(0).unwrap() |
843 | | } |
844 | | |
845 | | #[test] |
846 | | fn nop() { |
847 | | // Skip this test when cranelift doesn't support the native platform. |
848 | | if cranelift_native::builder().is_err() { |
849 | | return; |
850 | | } |
851 | | let code = String::from( |
852 | | " |
853 | | test run |
854 | | function %test() -> i8 { |
855 | | block0: |
856 | | nop |
857 | | v1 = iconst.i8 -1 |
858 | | return v1 |
859 | | }", |
860 | | ); |
861 | | let ctrl_plane = &mut ControlPlane::default(); |
862 | | |
863 | | // extract function |
864 | | let test_file = parse_test(code.as_str(), ParseOptions::default()).unwrap(); |
865 | | assert_eq!(1, test_file.functions.len()); |
866 | | let function = test_file.functions[0].0.clone(); |
867 | | |
868 | | // execute function |
869 | | let mut compiler = TestFileCompiler::with_default_host_isa().unwrap(); |
870 | | compiler.declare_function(&function).unwrap(); |
871 | | compiler |
872 | | .define_function(function.clone(), ctrl_plane) |
873 | | .unwrap(); |
874 | | compiler |
875 | | .create_trampoline_for_function(&function, ctrl_plane) |
876 | | .unwrap(); |
877 | | let compiled = compiler.compile().unwrap(); |
878 | | let trampoline = compiled.get_trampoline(&function).unwrap(); |
879 | | let returned = trampoline.call(&compiled, &[]); |
880 | | assert_eq!(returned, vec![DataValue::I8(-1)]) |
881 | | } |
882 | | |
883 | | #[test] |
884 | | fn trampolines() { |
885 | | // Skip this test when cranelift doesn't support the native platform. |
886 | | if cranelift_native::builder().is_err() { |
887 | | return; |
888 | | } |
889 | | let function = parse( |
890 | | " |
891 | | function %test(f32, i8, i64x2, i8) -> f32x4, i64 { |
892 | | block0(v0: f32, v1: i8, v2: i64x2, v3: i8): |
893 | | v4 = vconst.f32x4 [0x0.1 0x0.2 0x0.3 0x0.4] |
894 | | v5 = iconst.i64 -1 |
895 | | return v4, v5 |
896 | | }", |
897 | | ); |
898 | | |
899 | | let compiler = TestFileCompiler::with_default_host_isa().unwrap(); |
900 | | let trampoline = make_trampoline( |
901 | | UserFuncName::user(0, 0), |
902 | | &function.signature, |
903 | | compiler.module.isa(), |
904 | | ); |
905 | | println!("{trampoline}"); |
906 | | assert!(format!("{trampoline}").ends_with( |
907 | | "sig0 = (f32, i8, i64x2, i8) -> f32x4, i64 fast |
908 | | |
909 | | block0(v0: i64, v1: i64): |
910 | | v2 = load.f32 notrap aligned v1 |
911 | | v3 = load.i8 notrap aligned v1+16 |
912 | | v4 = load.i64x2 notrap aligned little v1+32 |
913 | | v5 = load.i8 notrap aligned v1+48 |
914 | | v6, v7 = call_indirect sig0, v0(v2, v3, v4, v5) |
915 | | store notrap aligned little v6, v1 |
916 | | store notrap aligned v7, v1+16 |
917 | | return |
918 | | } |
919 | | " |
920 | | )); |
921 | | } |
922 | | } |