1 //! The JIT driver uses [`cranelift_jit`] to JIT execute programs without writing any object
4 use std::cell::RefCell;
6 use std::os::raw::{c_char, c_int};
7 use std::sync::{mpsc, Mutex};
9 use rustc_codegen_ssa::CrateInfo;
10 use rustc_middle::mir::mono::MonoItem;
11 use rustc_session::Session;
12 use rustc_span::Symbol;
14 use cranelift_jit::{JITBuilder, JITModule};
16 // FIXME use std::sync::OnceLock once it stabilizes
17 use once_cell::sync::OnceCell;
19 use crate::{prelude::*, BackendConfig};
20 use crate::{CodegenCx, CodegenMode};
23 backend_config: BackendConfig,
24 jit_module: JITModule,
28 static LAZY_JIT_STATE: RefCell<Option<JitState>> = const { RefCell::new(None) };
31 /// The Sender owned by the rustc thread
32 static GLOBAL_MESSAGE_SENDER: OnceCell<Mutex<mpsc::Sender<UnsafeMessage>>> = OnceCell::new();
34 /// A message that is sent from the jitted runtime to the rustc thread.
35 /// Senders are responsible for upholding `Send` semantics.
37 /// Request that the specified `Instance` be lazily jitted.
39 /// Nothing accessible through `instance_ptr` may be moved or mutated by the sender after
40 /// this message is sent.
42 instance_ptr: *const Instance<'static>,
43 trampoline_ptr: *const u8,
44 tx: mpsc::Sender<*const u8>,
47 unsafe impl Send for UnsafeMessage {}
51 fn send(self) -> Result<(), mpsc::SendError<UnsafeMessage>> {
53 /// The Sender owned by the local thread
54 static LOCAL_MESSAGE_SENDER: mpsc::Sender<UnsafeMessage> =
60 LOCAL_MESSAGE_SENDER.with(|sender| sender.send(self))
66 backend_config: &BackendConfig,
68 ) -> (JITModule, CodegenCx) {
69 let crate_info = CrateInfo::new(tcx, "dummy_target_cpu".to_string());
70 let imported_symbols = load_imported_symbols_for_jit(tcx.sess, crate_info);
72 let isa = crate::build_isa(tcx.sess, backend_config);
73 let mut jit_builder = JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());
74 jit_builder.hotswap(hotswap);
75 crate::compiler_builtins::register_functions_for_jit(&mut jit_builder);
76 jit_builder.symbols(imported_symbols);
77 jit_builder.symbol("__clif_jit_fn", clif_jit_fn as *const u8);
78 let mut jit_module = JITModule::new(jit_builder);
80 let mut cx = crate::CodegenCx::new(
82 backend_config.clone(),
85 Symbol::intern("dummy_cgu_name"),
88 crate::allocator::codegen(tcx, &mut jit_module, &mut cx.unwind_context);
89 crate::main_shim::maybe_create_entry_wrapper(
92 &mut cx.unwind_context,
100 pub(crate) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! {
101 if !tcx.sess.opts.output_types.should_codegen() {
102 tcx.sess.fatal("JIT mode doesn't work with `cargo check`");
105 if !tcx.sess.crate_types().contains(&rustc_session::config::CrateType::Executable) {
106 tcx.sess.fatal("can't jit non-executable crate");
109 let (mut jit_module, mut cx) = create_jit_module(
112 matches!(backend_config.codegen_mode, CodegenMode::JitLazy),
114 let mut cached_context = Context::new();
116 let (_, cgus) = tcx.collect_and_partition_mono_items(());
117 let mono_items = cgus
119 .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
121 .collect::<FxHashMap<_, (_, _)>>()
123 .collect::<Vec<(_, (_, _))>>();
125 super::time(tcx, backend_config.display_cg_time, "codegen mono items", || {
126 super::predefine_mono_items(tcx, &mut jit_module, &mono_items);
127 for (mono_item, _) in mono_items {
129 MonoItem::Fn(inst) => match backend_config.codegen_mode {
130 CodegenMode::Aot => unreachable!(),
131 CodegenMode::Jit => {
132 tcx.sess.time("codegen fn", || {
133 crate::base::codegen_and_compile_fn(
142 CodegenMode::JitLazy => {
143 codegen_shim(tcx, &mut cx, &mut cached_context, &mut jit_module, inst)
146 MonoItem::Static(def_id) => {
147 crate::constant::codegen_static(tcx, &mut jit_module, def_id);
149 MonoItem::GlobalAsm(item_id) => {
150 let item = tcx.hir().item(item_id);
151 tcx.sess.span_fatal(item.span, "Global asm is not supported in JIT mode");
157 if !cx.global_asm.is_empty() {
158 tcx.sess.fatal("Inline asm is not supported in JIT mode");
161 tcx.sess.abort_if_errors();
163 jit_module.finalize_definitions();
164 unsafe { cx.unwind_context.register_jit(&jit_module) };
167 "Rustc codegen cranelift will JIT run the executable, because -Cllvm-args=mode=jit was passed"
170 let args = std::iter::once(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string())
171 .chain(backend_config.jit_args.iter().map(|arg| &**arg))
172 .map(|arg| CString::new(arg).unwrap())
173 .collect::<Vec<_>>();
175 let start_sig = Signature {
177 AbiParam::new(jit_module.target_config().pointer_type()),
178 AbiParam::new(jit_module.target_config().pointer_type()),
180 returns: vec![AbiParam::new(jit_module.target_config().pointer_type() /*isize*/)],
181 call_conv: jit_module.target_config().default_call_conv,
183 let start_func_id = jit_module.declare_function("main", Linkage::Import, &start_sig).unwrap();
184 let finalized_start: *const u8 = jit_module.get_finalized_function(start_func_id);
186 LAZY_JIT_STATE.with(|lazy_jit_state| {
187 let mut lazy_jit_state = lazy_jit_state.borrow_mut();
188 assert!(lazy_jit_state.is_none());
189 *lazy_jit_state = Some(JitState { backend_config, jit_module });
192 let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
193 unsafe { ::std::mem::transmute(finalized_start) };
195 let (tx, rx) = mpsc::channel();
196 GLOBAL_MESSAGE_SENDER.set(Mutex::new(tx)).unwrap();
198 // Spawn the jitted runtime in a new thread so that this rustc thread can handle messages
199 // (eg to lazily JIT further functions as required)
200 std::thread::spawn(move || {
201 let mut argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
203 // Push a null pointer as a terminating argument. This is required by POSIX and
204 // useful as some dynamic linkers use it as a marker to jump over.
205 argv.push(std::ptr::null());
207 let ret = f(args.len() as c_int, argv.as_ptr());
208 std::process::exit(ret);
213 match rx.recv().unwrap() {
214 // lazy JIT compilation request - compile requested instance and return pointer to result
215 UnsafeMessage::JitFn { instance_ptr, trampoline_ptr, tx } => {
216 tx.send(jit_fn(instance_ptr, trampoline_ptr))
217 .expect("jitted runtime hung up before response to lazy JIT request was sent");
223 extern "C" fn clif_jit_fn(
224 instance_ptr: *const Instance<'static>,
225 trampoline_ptr: *const u8,
227 // send the JIT request to the rustc thread, with a channel for the response
228 let (tx, rx) = mpsc::channel();
229 UnsafeMessage::JitFn { instance_ptr, trampoline_ptr, tx }
231 .expect("rustc thread hung up before lazy JIT request was sent");
233 // block on JIT compilation result
234 rx.recv().expect("rustc thread hung up before responding to sent lazy JIT request")
237 fn jit_fn(instance_ptr: *const Instance<'static>, trampoline_ptr: *const u8) -> *const u8 {
238 rustc_middle::ty::tls::with(|tcx| {
239 // lift is used to ensure the correct lifetime for instance.
240 let instance = tcx.lift(unsafe { *instance_ptr }).unwrap();
242 LAZY_JIT_STATE.with(|lazy_jit_state| {
243 let mut lazy_jit_state = lazy_jit_state.borrow_mut();
244 let lazy_jit_state = lazy_jit_state.as_mut().unwrap();
245 let jit_module = &mut lazy_jit_state.jit_module;
246 let backend_config = lazy_jit_state.backend_config.clone();
248 let name = tcx.symbol_name(instance).name;
249 let sig = crate::abi::get_function_sig(tcx, jit_module.isa().triple(), instance);
250 let func_id = jit_module.declare_function(name, Linkage::Export, &sig).unwrap();
252 let current_ptr = jit_module.read_got_entry(func_id);
254 // If the function's GOT entry has already been updated to point at something other
255 // than the shim trampoline, don't re-jit but just return the new pointer instead.
256 // This does not need synchronization as this code is executed only by a sole rustc
258 if current_ptr != trampoline_ptr {
262 jit_module.prepare_for_function_redefine(func_id).unwrap();
264 let mut cx = crate::CodegenCx::new(
269 Symbol::intern("dummy_cgu_name"),
271 tcx.sess.time("codegen fn", || {
272 crate::base::codegen_and_compile_fn(
281 assert!(cx.global_asm.is_empty());
282 jit_module.finalize_definitions();
283 unsafe { cx.unwind_context.register_jit(&jit_module) };
284 jit_module.get_finalized_function(func_id)
289 fn load_imported_symbols_for_jit(
291 crate_info: CrateInfo,
292 ) -> Vec<(String, *const u8)> {
293 use rustc_middle::middle::dependency_format::Linkage;
295 let mut dylib_paths = Vec::new();
297 let data = &crate_info
300 .find(|(crate_type, _data)| *crate_type == rustc_session::config::CrateType::Executable)
303 for &cnum in &crate_info.used_crates {
304 let src = &crate_info.used_crate_source[&cnum];
305 match data[cnum.as_usize() - 1] {
306 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
308 let name = crate_info.crate_name[&cnum];
309 let mut err = sess.struct_err(&format!("Can't load static lib {}", name));
310 err.note("rustc_codegen_cranelift can only load dylibs in JIT mode.");
313 Linkage::Dynamic => {
314 dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
319 let mut imported_symbols = Vec::new();
320 for path in dylib_paths {
321 use object::{Object, ObjectSymbol};
322 let lib = libloading::Library::new(&path).unwrap();
323 let obj = std::fs::read(path).unwrap();
324 let obj = object::File::parse(&*obj).unwrap();
325 imported_symbols.extend(obj.dynamic_symbols().filter_map(|symbol| {
326 let name = symbol.name().unwrap().to_string();
327 if name.is_empty() || !symbol.is_global() || symbol.is_undefined() {
330 if name.starts_with("rust_metadata_") {
331 // The metadata is part of a section that is not loaded by the dynamic linker in
335 let dlsym_name = if cfg!(target_os = "macos") {
336 // On macOS `dlsym` expects the name without leading `_`.
337 assert!(name.starts_with('_'), "{:?}", name);
342 let symbol: libloading::Symbol<'_, *const u8> =
343 unsafe { lib.get(dlsym_name.as_bytes()) }.unwrap();
344 Some((name, *symbol))
346 std::mem::forget(lib)
349 sess.abort_if_errors();
354 fn codegen_shim<'tcx>(
357 cached_context: &mut Context,
358 module: &mut JITModule,
359 inst: Instance<'tcx>,
361 let pointer_type = module.target_config().pointer_type();
363 let name = tcx.symbol_name(inst).name;
364 let sig = crate::abi::get_function_sig(tcx, module.isa().triple(), inst);
365 let func_id = module.declare_function(name, Linkage::Export, &sig).unwrap();
367 let instance_ptr = Box::into_raw(Box::new(inst));
374 call_conv: module.target_config().default_call_conv,
375 params: vec![AbiParam::new(pointer_type), AbiParam::new(pointer_type)],
376 returns: vec![AbiParam::new(pointer_type)],
381 let context = cached_context;
383 let trampoline = &mut context.func;
384 trampoline.signature = sig.clone();
386 let mut builder_ctx = FunctionBuilderContext::new();
387 let mut trampoline_builder = FunctionBuilder::new(trampoline, &mut builder_ctx);
389 let trampoline_fn = module.declare_func_in_func(func_id, trampoline_builder.func);
390 let jit_fn = module.declare_func_in_func(jit_fn, trampoline_builder.func);
391 let sig_ref = trampoline_builder.func.import_signature(sig);
393 let entry_block = trampoline_builder.create_block();
394 trampoline_builder.append_block_params_for_function_params(entry_block);
395 let fn_args = trampoline_builder.func.dfg.block_params(entry_block).to_vec();
397 trampoline_builder.switch_to_block(entry_block);
398 let instance_ptr = trampoline_builder.ins().iconst(pointer_type, instance_ptr as u64 as i64);
399 let trampoline_ptr = trampoline_builder.ins().func_addr(pointer_type, trampoline_fn);
400 let jitted_fn = trampoline_builder.ins().call(jit_fn, &[instance_ptr, trampoline_ptr]);
401 let jitted_fn = trampoline_builder.func.dfg.inst_results(jitted_fn)[0];
402 let call_inst = trampoline_builder.ins().call_indirect(sig_ref, jitted_fn, &fn_args);
403 let ret_vals = trampoline_builder.func.dfg.inst_results(call_inst).to_vec();
404 trampoline_builder.ins().return_(&ret_vals);
406 module.define_function(func_id, context).unwrap();
407 cx.unwind_context.add_function(func_id, context, module.isa());