]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/driver/jit.rs
Rollup merge of #105458 - Ayush1325:blocking_spawn, r=Mark-Simulacrum
[rust.git] / compiler / rustc_codegen_cranelift / src / driver / jit.rs
1 //! The JIT driver uses [`cranelift_jit`] to JIT execute programs without writing any object
2 //! files.
3
4 use std::cell::RefCell;
5 use std::ffi::CString;
6 use std::os::raw::{c_char, c_int};
7 use std::sync::{mpsc, Mutex};
8
9 use rustc_codegen_ssa::CrateInfo;
10 use rustc_middle::mir::mono::MonoItem;
11 use rustc_session::Session;
12 use rustc_span::Symbol;
13
14 use cranelift_jit::{JITBuilder, JITModule};
15
16 // FIXME use std::sync::OnceLock once it stabilizes
17 use once_cell::sync::OnceCell;
18
19 use crate::{prelude::*, BackendConfig};
20 use crate::{CodegenCx, CodegenMode};
21
22 struct JitState {
23     backend_config: BackendConfig,
24     jit_module: JITModule,
25 }
26
27 thread_local! {
28     static LAZY_JIT_STATE: RefCell<Option<JitState>> = const { RefCell::new(None) };
29 }
30
31 /// The Sender owned by the rustc thread
32 static GLOBAL_MESSAGE_SENDER: OnceCell<Mutex<mpsc::Sender<UnsafeMessage>>> = OnceCell::new();
33
34 /// A message that is sent from the jitted runtime to the rustc thread.
35 /// Senders are responsible for upholding `Send` semantics.
36 enum UnsafeMessage {
37     /// Request that the specified `Instance` be lazily jitted.
38     ///
39     /// Nothing accessible through `instance_ptr` may be moved or mutated by the sender after
40     /// this message is sent.
41     JitFn {
42         instance_ptr: *const Instance<'static>,
43         trampoline_ptr: *const u8,
44         tx: mpsc::Sender<*const u8>,
45     },
46 }
47 unsafe impl Send for UnsafeMessage {}
48
49 impl UnsafeMessage {
50     /// Send the message.
51     fn send(self) -> Result<(), mpsc::SendError<UnsafeMessage>> {
52         thread_local! {
53             /// The Sender owned by the local thread
54             static LOCAL_MESSAGE_SENDER: mpsc::Sender<UnsafeMessage> =
55                 GLOBAL_MESSAGE_SENDER
56                     .get().unwrap()
57                     .lock().unwrap()
58                     .clone();
59         }
60         LOCAL_MESSAGE_SENDER.with(|sender| sender.send(self))
61     }
62 }
63
64 fn create_jit_module(
65     tcx: TyCtxt<'_>,
66     backend_config: &BackendConfig,
67     hotswap: bool,
68 ) -> (JITModule, CodegenCx) {
69     let crate_info = CrateInfo::new(tcx, "dummy_target_cpu".to_string());
70
71     let isa = crate::build_isa(tcx.sess, backend_config);
72     let mut jit_builder = JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());
73     jit_builder.hotswap(hotswap);
74     crate::compiler_builtins::register_functions_for_jit(&mut jit_builder);
75     jit_builder.symbol_lookup_fn(dep_symbol_lookup_fn(tcx.sess, crate_info));
76     jit_builder.symbol("__clif_jit_fn", clif_jit_fn as *const u8);
77     let mut jit_module = JITModule::new(jit_builder);
78
79     let mut cx = crate::CodegenCx::new(
80         tcx,
81         backend_config.clone(),
82         jit_module.isa(),
83         false,
84         Symbol::intern("dummy_cgu_name"),
85     );
86
87     crate::allocator::codegen(tcx, &mut jit_module, &mut cx.unwind_context);
88     crate::main_shim::maybe_create_entry_wrapper(
89         tcx,
90         &mut jit_module,
91         &mut cx.unwind_context,
92         true,
93         true,
94     );
95
96     (jit_module, cx)
97 }
98
99 pub(crate) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! {
100     if !tcx.sess.opts.output_types.should_codegen() {
101         tcx.sess.fatal("JIT mode doesn't work with `cargo check`");
102     }
103
104     if !tcx.sess.crate_types().contains(&rustc_session::config::CrateType::Executable) {
105         tcx.sess.fatal("can't jit non-executable crate");
106     }
107
108     let (mut jit_module, mut cx) = create_jit_module(
109         tcx,
110         &backend_config,
111         matches!(backend_config.codegen_mode, CodegenMode::JitLazy),
112     );
113     let mut cached_context = Context::new();
114
115     let (_, cgus) = tcx.collect_and_partition_mono_items(());
116     let mono_items = cgus
117         .iter()
118         .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
119         .flatten()
120         .collect::<FxHashMap<_, (_, _)>>()
121         .into_iter()
122         .collect::<Vec<(_, (_, _))>>();
123
124     super::time(tcx, backend_config.display_cg_time, "codegen mono items", || {
125         super::predefine_mono_items(tcx, &mut jit_module, &mono_items);
126         for (mono_item, _) in mono_items {
127             match mono_item {
128                 MonoItem::Fn(inst) => match backend_config.codegen_mode {
129                     CodegenMode::Aot => unreachable!(),
130                     CodegenMode::Jit => {
131                         tcx.sess.time("codegen fn", || {
132                             crate::base::codegen_and_compile_fn(
133                                 tcx,
134                                 &mut cx,
135                                 &mut cached_context,
136                                 &mut jit_module,
137                                 inst,
138                             )
139                         });
140                     }
141                     CodegenMode::JitLazy => {
142                         codegen_shim(tcx, &mut cx, &mut cached_context, &mut jit_module, inst)
143                     }
144                 },
145                 MonoItem::Static(def_id) => {
146                     crate::constant::codegen_static(tcx, &mut jit_module, def_id);
147                 }
148                 MonoItem::GlobalAsm(item_id) => {
149                     let item = tcx.hir().item(item_id);
150                     tcx.sess.span_fatal(item.span, "Global asm is not supported in JIT mode");
151                 }
152             }
153         }
154     });
155
156     if !cx.global_asm.is_empty() {
157         tcx.sess.fatal("Inline asm is not supported in JIT mode");
158     }
159
160     tcx.sess.abort_if_errors();
161
162     jit_module.finalize_definitions().unwrap();
163     unsafe { cx.unwind_context.register_jit(&jit_module) };
164
165     println!(
166         "Rustc codegen cranelift will JIT run the executable, because -Cllvm-args=mode=jit was passed"
167     );
168
169     let args = std::iter::once(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string())
170         .chain(backend_config.jit_args.iter().map(|arg| &**arg))
171         .map(|arg| CString::new(arg).unwrap())
172         .collect::<Vec<_>>();
173
174     let start_sig = Signature {
175         params: vec![
176             AbiParam::new(jit_module.target_config().pointer_type()),
177             AbiParam::new(jit_module.target_config().pointer_type()),
178         ],
179         returns: vec![AbiParam::new(jit_module.target_config().pointer_type() /*isize*/)],
180         call_conv: jit_module.target_config().default_call_conv,
181     };
182     let start_func_id = jit_module.declare_function("main", Linkage::Import, &start_sig).unwrap();
183     let finalized_start: *const u8 = jit_module.get_finalized_function(start_func_id);
184
185     LAZY_JIT_STATE.with(|lazy_jit_state| {
186         let mut lazy_jit_state = lazy_jit_state.borrow_mut();
187         assert!(lazy_jit_state.is_none());
188         *lazy_jit_state = Some(JitState { backend_config, jit_module });
189     });
190
191     let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
192         unsafe { ::std::mem::transmute(finalized_start) };
193
194     let (tx, rx) = mpsc::channel();
195     GLOBAL_MESSAGE_SENDER.set(Mutex::new(tx)).unwrap();
196
197     // Spawn the jitted runtime in a new thread so that this rustc thread can handle messages
198     // (eg to lazily JIT further functions as required)
199     std::thread::spawn(move || {
200         let mut argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
201
202         // Push a null pointer as a terminating argument. This is required by POSIX and
203         // useful as some dynamic linkers use it as a marker to jump over.
204         argv.push(std::ptr::null());
205
206         let ret = f(args.len() as c_int, argv.as_ptr());
207         std::process::exit(ret);
208     });
209
210     // Handle messages
211     loop {
212         match rx.recv().unwrap() {
213             // lazy JIT compilation request - compile requested instance and return pointer to result
214             UnsafeMessage::JitFn { instance_ptr, trampoline_ptr, tx } => {
215                 tx.send(jit_fn(instance_ptr, trampoline_ptr))
216                     .expect("jitted runtime hung up before response to lazy JIT request was sent");
217             }
218         }
219     }
220 }
221
222 extern "C" fn clif_jit_fn(
223     instance_ptr: *const Instance<'static>,
224     trampoline_ptr: *const u8,
225 ) -> *const u8 {
226     // send the JIT request to the rustc thread, with a channel for the response
227     let (tx, rx) = mpsc::channel();
228     UnsafeMessage::JitFn { instance_ptr, trampoline_ptr, tx }
229         .send()
230         .expect("rustc thread hung up before lazy JIT request was sent");
231
232     // block on JIT compilation result
233     rx.recv().expect("rustc thread hung up before responding to sent lazy JIT request")
234 }
235
236 fn jit_fn(instance_ptr: *const Instance<'static>, trampoline_ptr: *const u8) -> *const u8 {
237     rustc_middle::ty::tls::with(|tcx| {
238         // lift is used to ensure the correct lifetime for instance.
239         let instance = tcx.lift(unsafe { *instance_ptr }).unwrap();
240
241         LAZY_JIT_STATE.with(|lazy_jit_state| {
242             let mut lazy_jit_state = lazy_jit_state.borrow_mut();
243             let lazy_jit_state = lazy_jit_state.as_mut().unwrap();
244             let jit_module = &mut lazy_jit_state.jit_module;
245             let backend_config = lazy_jit_state.backend_config.clone();
246
247             let name = tcx.symbol_name(instance).name;
248             let sig = crate::abi::get_function_sig(
249                 tcx,
250                 jit_module.target_config().default_call_conv,
251                 instance,
252             );
253             let func_id = jit_module.declare_function(name, Linkage::Export, &sig).unwrap();
254
255             let current_ptr = jit_module.read_got_entry(func_id);
256
257             // If the function's GOT entry has already been updated to point at something other
258             // than the shim trampoline, don't re-jit but just return the new pointer instead.
259             // This does not need synchronization as this code is executed only by a sole rustc
260             // thread.
261             if current_ptr != trampoline_ptr {
262                 return current_ptr;
263             }
264
265             jit_module.prepare_for_function_redefine(func_id).unwrap();
266
267             let mut cx = crate::CodegenCx::new(
268                 tcx,
269                 backend_config,
270                 jit_module.isa(),
271                 false,
272                 Symbol::intern("dummy_cgu_name"),
273             );
274             tcx.sess.time("codegen fn", || {
275                 crate::base::codegen_and_compile_fn(
276                     tcx,
277                     &mut cx,
278                     &mut Context::new(),
279                     jit_module,
280                     instance,
281                 )
282             });
283
284             assert!(cx.global_asm.is_empty());
285             jit_module.finalize_definitions().unwrap();
286             unsafe { cx.unwind_context.register_jit(&jit_module) };
287             jit_module.get_finalized_function(func_id)
288         })
289     })
290 }
291
292 fn dep_symbol_lookup_fn(
293     sess: &Session,
294     crate_info: CrateInfo,
295 ) -> Box<dyn Fn(&str) -> Option<*const u8>> {
296     use rustc_middle::middle::dependency_format::Linkage;
297
298     let mut dylib_paths = Vec::new();
299
300     let data = &crate_info
301         .dependency_formats
302         .iter()
303         .find(|(crate_type, _data)| *crate_type == rustc_session::config::CrateType::Executable)
304         .unwrap()
305         .1;
306     for &cnum in &crate_info.used_crates {
307         let src = &crate_info.used_crate_source[&cnum];
308         match data[cnum.as_usize() - 1] {
309             Linkage::NotLinked | Linkage::IncludedFromDylib => {}
310             Linkage::Static => {
311                 let name = crate_info.crate_name[&cnum];
312                 let mut err = sess.struct_err(&format!("Can't load static lib {}", name));
313                 err.note("rustc_codegen_cranelift can only load dylibs in JIT mode.");
314                 err.emit();
315             }
316             Linkage::Dynamic => {
317                 dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
318             }
319         }
320     }
321
322     let imported_dylibs = Box::leak(
323         dylib_paths
324             .into_iter()
325             .map(|path| unsafe { libloading::Library::new(&path).unwrap() })
326             .collect::<Box<[_]>>(),
327     );
328
329     sess.abort_if_errors();
330
331     Box::new(move |sym_name| {
332         for dylib in &*imported_dylibs {
333             if let Ok(sym) = unsafe { dylib.get::<*const u8>(sym_name.as_bytes()) } {
334                 return Some(*sym);
335             }
336         }
337         None
338     })
339 }
340
341 fn codegen_shim<'tcx>(
342     tcx: TyCtxt<'tcx>,
343     cx: &mut CodegenCx,
344     cached_context: &mut Context,
345     module: &mut JITModule,
346     inst: Instance<'tcx>,
347 ) {
348     let pointer_type = module.target_config().pointer_type();
349
350     let name = tcx.symbol_name(inst).name;
351     let sig = crate::abi::get_function_sig(tcx, module.target_config().default_call_conv, inst);
352     let func_id = module.declare_function(name, Linkage::Export, &sig).unwrap();
353
354     let instance_ptr = Box::into_raw(Box::new(inst));
355
356     let jit_fn = module
357         .declare_function(
358             "__clif_jit_fn",
359             Linkage::Import,
360             &Signature {
361                 call_conv: module.target_config().default_call_conv,
362                 params: vec![AbiParam::new(pointer_type), AbiParam::new(pointer_type)],
363                 returns: vec![AbiParam::new(pointer_type)],
364             },
365         )
366         .unwrap();
367
368     let context = cached_context;
369     context.clear();
370     let trampoline = &mut context.func;
371     trampoline.signature = sig.clone();
372
373     let mut builder_ctx = FunctionBuilderContext::new();
374     let mut trampoline_builder = FunctionBuilder::new(trampoline, &mut builder_ctx);
375
376     let trampoline_fn = module.declare_func_in_func(func_id, trampoline_builder.func);
377     let jit_fn = module.declare_func_in_func(jit_fn, trampoline_builder.func);
378     let sig_ref = trampoline_builder.func.import_signature(sig);
379
380     let entry_block = trampoline_builder.create_block();
381     trampoline_builder.append_block_params_for_function_params(entry_block);
382     let fn_args = trampoline_builder.func.dfg.block_params(entry_block).to_vec();
383
384     trampoline_builder.switch_to_block(entry_block);
385     let instance_ptr = trampoline_builder.ins().iconst(pointer_type, instance_ptr as u64 as i64);
386     let trampoline_ptr = trampoline_builder.ins().func_addr(pointer_type, trampoline_fn);
387     let jitted_fn = trampoline_builder.ins().call(jit_fn, &[instance_ptr, trampoline_ptr]);
388     let jitted_fn = trampoline_builder.func.dfg.inst_results(jitted_fn)[0];
389     let call_inst = trampoline_builder.ins().call_indirect(sig_ref, jitted_fn, &fn_args);
390     let ret_vals = trampoline_builder.func.dfg.inst_results(call_inst).to_vec();
391     trampoline_builder.ins().return_(&ret_vals);
392
393     module.define_function(func_id, context).unwrap();
394     cx.unwind_context.add_function(func_id, context, module.isa());
395 }