]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/driver/jit.rs
Rollup merge of #102215 - alexcrichton:wasm-link-whole-archive, r=estebank
[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();
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(tcx, jit_module.isa().triple(), instance);
249             let func_id = jit_module.declare_function(name, Linkage::Export, &sig).unwrap();
250
251             let current_ptr = jit_module.read_got_entry(func_id);
252
253             // If the function's GOT entry has already been updated to point at something other
254             // than the shim trampoline, don't re-jit but just return the new pointer instead.
255             // This does not need synchronization as this code is executed only by a sole rustc
256             // thread.
257             if current_ptr != trampoline_ptr {
258                 return current_ptr;
259             }
260
261             jit_module.prepare_for_function_redefine(func_id).unwrap();
262
263             let mut cx = crate::CodegenCx::new(
264                 tcx,
265                 backend_config,
266                 jit_module.isa(),
267                 false,
268                 Symbol::intern("dummy_cgu_name"),
269             );
270             tcx.sess.time("codegen fn", || {
271                 crate::base::codegen_and_compile_fn(
272                     tcx,
273                     &mut cx,
274                     &mut Context::new(),
275                     jit_module,
276                     instance,
277                 )
278             });
279
280             assert!(cx.global_asm.is_empty());
281             jit_module.finalize_definitions();
282             unsafe { cx.unwind_context.register_jit(&jit_module) };
283             jit_module.get_finalized_function(func_id)
284         })
285     })
286 }
287
288 fn dep_symbol_lookup_fn(
289     sess: &Session,
290     crate_info: CrateInfo,
291 ) -> Box<dyn Fn(&str) -> Option<*const u8>> {
292     use rustc_middle::middle::dependency_format::Linkage;
293
294     let mut dylib_paths = Vec::new();
295
296     let data = &crate_info
297         .dependency_formats
298         .iter()
299         .find(|(crate_type, _data)| *crate_type == rustc_session::config::CrateType::Executable)
300         .unwrap()
301         .1;
302     for &cnum in &crate_info.used_crates {
303         let src = &crate_info.used_crate_source[&cnum];
304         match data[cnum.as_usize() - 1] {
305             Linkage::NotLinked | Linkage::IncludedFromDylib => {}
306             Linkage::Static => {
307                 let name = crate_info.crate_name[&cnum];
308                 let mut err = sess.struct_err(&format!("Can't load static lib {}", name));
309                 err.note("rustc_codegen_cranelift can only load dylibs in JIT mode.");
310                 err.emit();
311             }
312             Linkage::Dynamic => {
313                 dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
314             }
315         }
316     }
317
318     let imported_dylibs = Box::leak(
319         dylib_paths
320             .into_iter()
321             .map(|path| unsafe { libloading::Library::new(&path).unwrap() })
322             .collect::<Box<[_]>>(),
323     );
324
325     sess.abort_if_errors();
326
327     Box::new(move |sym_name| {
328         for dylib in &*imported_dylibs {
329             if let Ok(sym) = unsafe { dylib.get::<*const u8>(sym_name.as_bytes()) } {
330                 return Some(*sym);
331             }
332         }
333         None
334     })
335 }
336
337 fn codegen_shim<'tcx>(
338     tcx: TyCtxt<'tcx>,
339     cx: &mut CodegenCx,
340     cached_context: &mut Context,
341     module: &mut JITModule,
342     inst: Instance<'tcx>,
343 ) {
344     let pointer_type = module.target_config().pointer_type();
345
346     let name = tcx.symbol_name(inst).name;
347     let sig = crate::abi::get_function_sig(tcx, module.isa().triple(), inst);
348     let func_id = module.declare_function(name, Linkage::Export, &sig).unwrap();
349
350     let instance_ptr = Box::into_raw(Box::new(inst));
351
352     let jit_fn = module
353         .declare_function(
354             "__clif_jit_fn",
355             Linkage::Import,
356             &Signature {
357                 call_conv: module.target_config().default_call_conv,
358                 params: vec![AbiParam::new(pointer_type), AbiParam::new(pointer_type)],
359                 returns: vec![AbiParam::new(pointer_type)],
360             },
361         )
362         .unwrap();
363
364     let context = cached_context;
365     context.clear();
366     let trampoline = &mut context.func;
367     trampoline.signature = sig.clone();
368
369     let mut builder_ctx = FunctionBuilderContext::new();
370     let mut trampoline_builder = FunctionBuilder::new(trampoline, &mut builder_ctx);
371
372     let trampoline_fn = module.declare_func_in_func(func_id, trampoline_builder.func);
373     let jit_fn = module.declare_func_in_func(jit_fn, trampoline_builder.func);
374     let sig_ref = trampoline_builder.func.import_signature(sig);
375
376     let entry_block = trampoline_builder.create_block();
377     trampoline_builder.append_block_params_for_function_params(entry_block);
378     let fn_args = trampoline_builder.func.dfg.block_params(entry_block).to_vec();
379
380     trampoline_builder.switch_to_block(entry_block);
381     let instance_ptr = trampoline_builder.ins().iconst(pointer_type, instance_ptr as u64 as i64);
382     let trampoline_ptr = trampoline_builder.ins().func_addr(pointer_type, trampoline_fn);
383     let jitted_fn = trampoline_builder.ins().call(jit_fn, &[instance_ptr, trampoline_ptr]);
384     let jitted_fn = trampoline_builder.func.dfg.inst_results(jitted_fn)[0];
385     let call_inst = trampoline_builder.ins().call_indirect(sig_ref, jitted_fn, &fn_args);
386     let ret_vals = trampoline_builder.func.dfg.inst_results(call_inst).to_vec();
387     trampoline_builder.ins().return_(&ret_vals);
388
389     module.define_function(func_id, context).unwrap();
390     cx.unwind_context.add_function(func_id, context, module.isa());
391 }