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