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