1 //! Provides functionality for compiling and running CLIF IR for `run` tests.
2 use core::{mem, ptr};
3 use cranelift_codegen::binemit::{NullRelocSink, NullStackMapSink, NullTrapSink};
4 use cranelift_codegen::data_value::DataValue;
5 use cranelift_codegen::ir::immediates::{Ieee32, Ieee64};
6 use cranelift_codegen::ir::{condcodes::IntCC, Function, InstBuilder, Signature, Type};
7 use cranelift_codegen::isa::{BackendVariant, TargetIsa};
8 use cranelift_codegen::{ir, settings, CodegenError, Context};
9 use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};
10 use cranelift_native::builder_with_options;
11 use log::trace;
12 use memmap2::{Mmap, MmapMut};
13 use std::cmp::max;
14 use std::collections::HashMap;
15 use thiserror::Error;
16 
17 /// Compile a single function.
18 ///
19 /// Several Cranelift functions need the ability to run Cranelift IR (e.g. `test_run`); this
20 /// [SingleFunctionCompiler] provides a way for compiling Cranelift [Function]s to
21 /// `CompiledFunction`s and subsequently calling them through the use of a `Trampoline`. As its
22 /// name indicates, this compiler is limited: any functionality that requires knowledge of things
23 /// outside the [Function] will likely not work (e.g. global values, calls). For an example of this
24 /// "outside-of-function" functionality, see `cranelift_jit::backend::JITBackend`.
25 ///
26 /// ```
27 /// use cranelift_filetests::SingleFunctionCompiler;
28 /// use cranelift_reader::parse_functions;
29 ///
30 /// let code = "test run \n function %add(i32, i32) -> i32 {  block0(v0:i32, v1:i32):  v2 = iadd v0, v1  return v2 }".into();
31 /// let func = parse_functions(code).unwrap().into_iter().nth(0).unwrap();
32 /// let mut compiler = SingleFunctionCompiler::with_default_host_isa();
33 /// let compiled_func = compiler.compile(func).unwrap();
34 /// println!("Address of compiled function: {:p}", compiled_func.as_ptr());
35 /// ```
36 pub struct SingleFunctionCompiler {
37     isa: Box<dyn TargetIsa>,
38     trampolines: HashMap<Signature, Trampoline>,
39 }
40 
41 impl SingleFunctionCompiler {
42     /// Build a [SingleFunctionCompiler] from a [TargetIsa]. For functions to be runnable on the
43     /// host machine, this [TargetIsa] must match the host machine's ISA (see
44     /// [SingleFunctionCompiler::with_host_isa]).
45     pub fn new(isa: Box<dyn TargetIsa>) -> Self {
46         let trampolines = HashMap::new();
47         Self { isa, trampolines }
48     }
49 
50     /// Build a [SingleFunctionCompiler] using the host machine's ISA and the passed flags.
51     pub fn with_host_isa(flags: settings::Flags, variant: BackendVariant) -> Self {
52         let builder = builder_with_options(variant, true)
53             .expect("Unable to build a TargetIsa for the current host");
54         let isa = builder.finish(flags);
55         Self::new(isa)
56     }
57 
58     /// Build a [SingleFunctionCompiler] using the host machine's ISA and the default flags for this
59     /// ISA.
60     pub fn with_default_host_isa() -> Self {
61         let flags = settings::Flags::new(settings::builder());
62         Self::with_host_isa(flags, BackendVariant::Any)
63     }
64 
65     /// Compile the passed [Function] to a `CompiledFunction`. This function will:
66     ///  - check that the default ISA calling convention is used (to ensure it can be called)
67     ///  - compile the [Function]
68     ///  - compile a `Trampoline` for the [Function]'s signature (or used a cached `Trampoline`;
69     ///    this makes it possible to call functions when the signature is not known until runtime.
70     pub fn compile(&mut self, function: Function) -> Result<CompiledFunction, CompilationError> {
71         let signature = function.signature.clone();
72         if signature.call_conv != self.isa.default_call_conv() {
73             return Err(CompilationError::InvalidTargetIsa);
74         }
75 
76         // Compile the function itself.
77         let code_page = compile(function, self.isa.as_ref())?;
78 
79         // Compile the trampoline to call it, if necessary (it may be cached).
80         let isa = self.isa.as_ref();
81         let trampoline = self
82             .trampolines
83             .entry(signature.clone())
84             .or_insert_with(|| {
85                 let ir = make_trampoline(&signature, isa);
86                 let code = compile(ir, isa).expect("failed to compile trampoline");
87                 Trampoline::new(code)
88             });
89 
90         Ok(CompiledFunction::new(code_page, signature, trampoline))
91     }
92 }
93 
94 #[derive(Error, Debug)]
95 pub enum CompilationError {
96     #[error("Cross-compilation not currently supported; use the host's default calling convention \
97     or remove the specified calling convention in the function signature to use the host's default.")]
98     InvalidTargetIsa,
99     #[error("Cranelift codegen error")]
100     CodegenError(#[from] CodegenError),
101     #[error("Memory mapping error")]
102     IoError(#[from] std::io::Error),
103 }
104 
105 /// Contains the compiled code to move memory-allocated [DataValue]s to the correct location (e.g.
106 /// register, stack) dictated by the calling convention before calling a [CompiledFunction]. Without
107 /// this, it would be quite difficult to correctly place [DataValue]s since both the calling
108 /// convention and function signature are not known until runtime. See [make_trampoline] for the
109 /// Cranelift IR used to build this.
110 pub struct Trampoline {
111     page: Mmap,
112 }
113 
114 impl Trampoline {
115     /// Build a new [Trampoline].
116     pub fn new(page: Mmap) -> Self {
117         Self { page }
118     }
119 
120     /// Return a pointer to the compiled code.
121     fn as_ptr(&self) -> *const u8 {
122         self.page.as_ptr()
123     }
124 }
125 
126 /// Container for the compiled code of a [Function]. This wrapper allows users to call the compiled
127 /// function through the use of a [Trampoline].
128 ///
129 /// ```
130 /// use cranelift_filetests::SingleFunctionCompiler;
131 /// use cranelift_reader::parse_functions;
132 /// use cranelift_codegen::data_value::DataValue;
133 ///
134 /// let code = "test run \n function %add(i32, i32) -> i32 {  block0(v0:i32, v1:i32):  v2 = iadd v0, v1  return v2 }".into();
135 /// let func = parse_functions(code).unwrap().into_iter().nth(0).unwrap();
136 /// let mut compiler = SingleFunctionCompiler::with_default_host_isa();
137 /// let compiled_func = compiler.compile(func).unwrap();
138 ///
139 /// let returned = compiled_func.call(&vec![DataValue::I32(2), DataValue::I32(40)]);
140 /// assert_eq!(vec![DataValue::I32(42)], returned);
141 /// ```
142 pub struct CompiledFunction<'a> {
143     page: Mmap,
144     signature: Signature,
145     trampoline: &'a Trampoline,
146 }
147 
148 impl<'a> CompiledFunction<'a> {
149     /// Build a new [CompiledFunction].
150     pub fn new(page: Mmap, signature: Signature, trampoline: &'a Trampoline) -> Self {
151         Self {
152             page,
153             signature,
154             trampoline,
155         }
156     }
157 
158     /// Return a pointer to the compiled code.
159     pub fn as_ptr(&self) -> *const u8 {
160         self.page.as_ptr()
161     }
162 
163     /// Call the [CompiledFunction], passing in [DataValue]s using a compiled [Trampoline].
164     pub fn call(&self, arguments: &[DataValue]) -> Vec<DataValue> {
165         let mut values = UnboxedValues::make_arguments(arguments, &self.signature);
166         let arguments_address = values.as_mut_ptr();
167         let function_address = self.as_ptr();
168 
169         let callable_trampoline: fn(*const u8, *mut u128) -> () =
170             unsafe { mem::transmute(self.trampoline.as_ptr()) };
171         callable_trampoline(function_address, arguments_address);
172 
173         values.collect_returns(&self.signature)
174     }
175 }
176 
177 /// A container for laying out the [ValueData]s in memory in a way that the [Trampoline] can
178 /// understand.
179 struct UnboxedValues(Vec<u128>);
180 
181 impl UnboxedValues {
182     /// The size in bytes of each slot location in the allocated [DataValue]s. Though [DataValue]s
183     /// could be smaller than 16 bytes (e.g. `I16`), this simplifies the creation of the [DataValue]
184     /// array and could be used to align the slots to the largest used [DataValue] (i.e. 128-bit
185     /// vectors).
186     const SLOT_SIZE: usize = 16;
187 
188     /// Build the arguments vector for passing the [DataValue]s into the [Trampoline]. The size of
189     /// `u128` used here must match [Trampoline::SLOT_SIZE].
190     pub fn make_arguments(arguments: &[DataValue], signature: &ir::Signature) -> Self {
191         assert_eq!(arguments.len(), signature.params.len());
192         let mut values_vec = vec![0; max(signature.params.len(), signature.returns.len())];
193 
194         // Store the argument values into `values_vec`.
195         for ((arg, slot), param) in arguments.iter().zip(&mut values_vec).zip(&signature.params) {
196             assert!(
197                 arg.ty() == param.value_type || arg.is_vector(),
198                 "argument type mismatch: {} != {}",
199                 arg.ty(),
200                 param.value_type
201             );
202             unsafe {
203                 Self::write_value_to(arg, slot);
204             }
205         }
206 
207         Self(values_vec)
208     }
209 
210     /// Return a pointer to the underlying memory for passing to the trampoline.
211     pub fn as_mut_ptr(&mut self) -> *mut u128 {
212         self.0.as_mut_ptr()
213     }
214 
215     /// Collect the returned [DataValue]s into a [Vec]. The size of `u128` used here must match
216     /// [Trampoline::SLOT_SIZE].
217     pub fn collect_returns(&self, signature: &ir::Signature) -> Vec<DataValue> {
218         assert!(self.0.len() >= signature.returns.len());
219         let mut returns = Vec::with_capacity(signature.returns.len());
220 
221         // Extract the returned values from this vector.
222         for (slot, param) in self.0.iter().zip(&signature.returns) {
223             let value = unsafe { Self::read_value_from(slot, param.value_type) };
224             returns.push(value);
225         }
226 
227         returns
228     }
229 
230     /// Write a [DataValue] to a memory location.
231     unsafe fn write_value_to(v: &DataValue, p: *mut u128) {
232         match v {
233             DataValue::B(b) => ptr::write(p as *mut bool, *b),
234             DataValue::I8(i) => ptr::write(p as *mut i8, *i),
235             DataValue::I16(i) => ptr::write(p as *mut i16, *i),
236             DataValue::I32(i) => ptr::write(p as *mut i32, *i),
237             DataValue::I64(i) => ptr::write(p as *mut i64, *i),
238             DataValue::F32(f) => ptr::write(p as *mut Ieee32, *f),
239             DataValue::F64(f) => ptr::write(p as *mut Ieee64, *f),
240             DataValue::V128(b) => ptr::write(p as *mut [u8; 16], *b),
241             _ => unimplemented!(),
242         }
243     }
244 
245     /// Read a [DataValue] from a memory location using a given [Type].
246     unsafe fn read_value_from(p: *const u128, ty: Type) -> DataValue {
247         match ty {
248             ir::types::I8 => DataValue::I8(ptr::read(p as *const i8)),
249             ir::types::I16 => DataValue::I16(ptr::read(p as *const i16)),
250             ir::types::I32 => DataValue::I32(ptr::read(p as *const i32)),
251             ir::types::I64 => DataValue::I64(ptr::read(p as *const i64)),
252             ir::types::F32 => DataValue::F32(ptr::read(p as *const Ieee32)),
253             ir::types::F64 => DataValue::F64(ptr::read(p as *const Ieee64)),
254             _ if ty.is_bool() => DataValue::B(ptr::read(p as *const bool)),
255             _ if ty.is_vector() && ty.bytes() == 16 => {
256                 DataValue::V128(ptr::read(p as *const [u8; 16]))
257             }
258             _ => unimplemented!(),
259         }
260     }
261 }
262 
263 /// Compile a [Function] to its executable bytes in memory.
264 ///
265 /// This currently returns a [Mmap], a type from an external crate, so we wrap this up before
266 /// exposing it in public APIs.
267 fn compile(function: Function, isa: &dyn TargetIsa) -> Result<Mmap, CompilationError> {
268     // Set up the context.
269     let mut context = Context::new();
270     context.func = function;
271 
272     // Compile and encode the result to machine code.
273     let relocs = &mut NullRelocSink {};
274     let traps = &mut NullTrapSink {};
275     let stack_maps = &mut NullStackMapSink {};
276     let code_info = context.compile(isa)?;
277     let mut code_page = MmapMut::map_anon(code_info.total_size as usize)?;
278 
279     unsafe {
280         context.emit_to_memory(isa, code_page.as_mut_ptr(), relocs, traps, stack_maps);
281     };
282 
283     let code_page = code_page.make_exec()?;
284     trace!(
285         "Compiled function {} with signature {} at: {:p}",
286         context.func.name,
287         context.func.signature,
288         code_page.as_ptr()
289     );
290 
291     Ok(code_page)
292 }
293 
294 /// Build the Cranelift IR for moving the memory-allocated [DataValue]s to their correct location
295 /// (e.g. register, stack) prior to calling a [CompiledFunction]. The [Function] returned by
296 /// [make_trampoline] is compiled to a [Trampoline]. Note that this uses the [TargetIsa]'s default
297 /// calling convention so we must also check that the [CompiledFunction] has the same calling
298 /// convention (see [SingleFunctionCompiler::compile]).
299 fn make_trampoline(signature: &ir::Signature, isa: &dyn TargetIsa) -> Function {
300     // Create the trampoline signature: (callee_address: pointer, values_vec: pointer) -> ()
301     let pointer_type = isa.pointer_type();
302     let mut wrapper_sig = ir::Signature::new(isa.frontend_config().default_call_conv);
303     wrapper_sig.params.push(ir::AbiParam::new(pointer_type)); // Add the `callee_address` parameter.
304     wrapper_sig.params.push(ir::AbiParam::new(pointer_type)); // Add the `values_vec` parameter.
305 
306     let mut func = ir::Function::with_name_signature(ir::ExternalName::user(0, 0), wrapper_sig);
307 
308     // The trampoline has a single block filled with loads, one call to callee_address, and some loads.
309     let mut builder_context = FunctionBuilderContext::new();
310     let mut builder = FunctionBuilder::new(&mut func, &mut builder_context);
311     let block0 = builder.create_block();
312     builder.append_block_params_for_function_params(block0);
313     builder.switch_to_block(block0);
314     builder.seal_block(block0);
315 
316     // Extract the incoming SSA values.
317     let (callee_value, values_vec_ptr_val) = {
318         let params = builder.func.dfg.block_params(block0);
319         (params[0], params[1])
320     };
321 
322     // Load the argument values out of `values_vec`.
323     let callee_args = signature
324         .params
325         .iter()
326         .enumerate()
327         .map(|(i, param)| {
328             // Calculate the type to load from memory, using integers for booleans (no encodings).
329             let ty = if param.value_type.is_bool() {
330                 Type::int(max(param.value_type.bits(), 8)).expect(
331                     "to be able to convert any boolean type to its equal-width integer type",
332                 )
333             } else {
334                 param.value_type
335             };
336             // Load the value.
337             let loaded = builder.ins().load(
338                 ty,
339                 ir::MemFlags::trusted(),
340                 values_vec_ptr_val,
341                 (i * UnboxedValues::SLOT_SIZE) as i32,
342             );
343             // For booleans, we want to type-convert the loaded integer into a boolean and ensure
344             // that we are using the architecture's canonical boolean representation (presumably
345             // comparison will emit this).
346             if param.value_type.is_bool() {
347                 builder.ins().icmp_imm(IntCC::NotEqual, loaded, 0)
348             } else {
349                 loaded
350             }
351         })
352         .collect::<Vec<_>>();
353 
354     // Call the passed function.
355     let new_sig = builder.import_signature(signature.clone());
356     let call = builder
357         .ins()
358         .call_indirect(new_sig, callee_value, &callee_args);
359 
360     // Store the return values into `values_vec`.
361     let results = builder.func.dfg.inst_results(call).to_vec();
362     for ((i, value), param) in results.iter().enumerate().zip(&signature.returns) {
363         // Before storing return values, we convert booleans to their integer representation.
364         let value = if param.value_type.is_bool() {
365             let ty = Type::int(max(param.value_type.bits(), 8))
366                 .expect("to be able to convert any boolean type to its equal-width integer type");
367             builder.ins().bint(ty, *value)
368         } else {
369             *value
370         };
371         // Store the value.
372         builder.ins().store(
373             ir::MemFlags::trusted(),
374             value,
375             values_vec_ptr_val,
376             (i * UnboxedValues::SLOT_SIZE) as i32,
377         );
378     }
379 
380     builder.ins().return_(&[]);
381     builder.finalize();
382 
383     func
384 }
385 
386 #[cfg(test)]
387 mod test {
388     use super::*;
389     use cranelift_reader::{parse_functions, parse_test, ParseOptions};
390 
391     fn parse(code: &str) -> Function {
392         parse_functions(code).unwrap().into_iter().nth(0).unwrap()
393     }
394 
395     #[test]
396     fn nop() {
397         let code = String::from(
398             "
399             test run
400             function %test() -> b8 {
401             block0:
402                 nop
403                 v1 = bconst.b8 true
404                 return v1
405             }",
406         );
407 
408         // extract function
409         let test_file = parse_test(code.as_str(), ParseOptions::default()).unwrap();
410         assert_eq!(1, test_file.functions.len());
411         let function = test_file.functions[0].0.clone();
412 
413         // execute function
414         let mut compiler = SingleFunctionCompiler::with_default_host_isa();
415         let compiled_function = compiler.compile(function).unwrap();
416         let returned = compiled_function.call(&[]);
417         assert_eq!(returned, vec![DataValue::B(true)])
418     }
419 
420     #[test]
421     fn trampolines() {
422         let function = parse(
423             "
424             function %test(f32, i8, i64x2, b1) -> f32x4, b64 {
425             block0(v0: f32, v1: i8, v2: i64x2, v3: b1):
426                 v4 = vconst.f32x4 [0x0.1 0x0.2 0x0.3 0x0.4]
427                 v5 = bconst.b64 true
428                 return v4, v5
429             }",
430         );
431 
432         let compiler = SingleFunctionCompiler::with_default_host_isa();
433         let trampoline = make_trampoline(&function.signature, compiler.isa.as_ref());
434         assert!(format!("{}", trampoline).ends_with(
435             "sig0 = (f32, i8, i64x2, b1) -> f32x4, b64 fast
436 
437 block0(v0: i64, v1: i64):
438     v2 = load.f32 notrap aligned v1
439     v3 = load.i8 notrap aligned v1+16
440     v4 = load.i64x2 notrap aligned v1+32
441     v5 = load.i8 notrap aligned v1+48
442     v6 = icmp_imm ne v5, 0
443     v7, v8 = call_indirect sig0, v0(v2, v3, v4, v6)
444     store notrap aligned v7, v1
445     v9 = bint.i64 v8
446     store notrap aligned v9, v1+16
447     return
448 }
449 "
450         ));
451     }
452 }
453