]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/driver/jit.rs
Rollup merge of #100653 - cuviper:fptoint_sat, r=michaelwoerister,antoyo
[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     let imported_symbols = load_imported_symbols_for_jit(tcx.sess, crate_info);
71
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);
79
80     let mut cx = crate::CodegenCx::new(
81         tcx,
82         backend_config.clone(),
83         jit_module.isa(),
84         false,
85         Symbol::intern("dummy_cgu_name"),
86     );
87
88     crate::allocator::codegen(tcx, &mut jit_module, &mut cx.unwind_context);
89     crate::main_shim::maybe_create_entry_wrapper(
90         tcx,
91         &mut jit_module,
92         &mut cx.unwind_context,
93         true,
94         true,
95     );
96
97     (jit_module, cx)
98 }
99
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`");
103     }
104
105     if !tcx.sess.crate_types().contains(&rustc_session::config::CrateType::Executable) {
106         tcx.sess.fatal("can't jit non-executable crate");
107     }
108
109     let (mut jit_module, mut cx) = create_jit_module(
110         tcx,
111         &backend_config,
112         matches!(backend_config.codegen_mode, CodegenMode::JitLazy),
113     );
114     let mut cached_context = Context::new();
115
116     let (_, cgus) = tcx.collect_and_partition_mono_items(());
117     let mono_items = cgus
118         .iter()
119         .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
120         .flatten()
121         .collect::<FxHashMap<_, (_, _)>>()
122         .into_iter()
123         .collect::<Vec<(_, (_, _))>>();
124
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 {
128             match mono_item {
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(
134                                 tcx,
135                                 &mut cx,
136                                 &mut cached_context,
137                                 &mut jit_module,
138                                 inst,
139                             )
140                         });
141                     }
142                     CodegenMode::JitLazy => {
143                         codegen_shim(tcx, &mut cx, &mut cached_context, &mut jit_module, inst)
144                     }
145                 },
146                 MonoItem::Static(def_id) => {
147                     crate::constant::codegen_static(tcx, &mut jit_module, def_id);
148                 }
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");
152                 }
153             }
154         }
155     });
156
157     if !cx.global_asm.is_empty() {
158         tcx.sess.fatal("Inline asm is not supported in JIT mode");
159     }
160
161     tcx.sess.abort_if_errors();
162
163     jit_module.finalize_definitions();
164     unsafe { cx.unwind_context.register_jit(&jit_module) };
165
166     println!(
167         "Rustc codegen cranelift will JIT run the executable, because -Cllvm-args=mode=jit was passed"
168     );
169
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<_>>();
174
175     let start_sig = Signature {
176         params: vec![
177             AbiParam::new(jit_module.target_config().pointer_type()),
178             AbiParam::new(jit_module.target_config().pointer_type()),
179         ],
180         returns: vec![AbiParam::new(jit_module.target_config().pointer_type() /*isize*/)],
181         call_conv: jit_module.target_config().default_call_conv,
182     };
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);
185
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 });
190     });
191
192     let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
193         unsafe { ::std::mem::transmute(finalized_start) };
194
195     let (tx, rx) = mpsc::channel();
196     GLOBAL_MESSAGE_SENDER.set(Mutex::new(tx)).unwrap();
197
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<_>>();
202
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());
206
207         let ret = f(args.len() as c_int, argv.as_ptr());
208         std::process::exit(ret);
209     });
210
211     // Handle messages
212     loop {
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");
218             }
219         }
220     }
221 }
222
223 extern "C" fn clif_jit_fn(
224     instance_ptr: *const Instance<'static>,
225     trampoline_ptr: *const u8,
226 ) -> *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 }
230         .send()
231         .expect("rustc thread hung up before lazy JIT request was sent");
232
233     // block on JIT compilation result
234     rx.recv().expect("rustc thread hung up before responding to sent lazy JIT request")
235 }
236
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();
241
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();
247
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();
251
252             let current_ptr = jit_module.read_got_entry(func_id);
253
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
257             // thread.
258             if current_ptr != trampoline_ptr {
259                 return current_ptr;
260             }
261
262             jit_module.prepare_for_function_redefine(func_id).unwrap();
263
264             let mut cx = crate::CodegenCx::new(
265                 tcx,
266                 backend_config,
267                 jit_module.isa(),
268                 false,
269                 Symbol::intern("dummy_cgu_name"),
270             );
271             tcx.sess.time("codegen fn", || {
272                 crate::base::codegen_and_compile_fn(
273                     tcx,
274                     &mut cx,
275                     &mut Context::new(),
276                     jit_module,
277                     instance,
278                 )
279             });
280
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)
285         })
286     })
287 }
288
289 fn load_imported_symbols_for_jit(
290     sess: &Session,
291     crate_info: CrateInfo,
292 ) -> Vec<(String, *const u8)> {
293     use rustc_middle::middle::dependency_format::Linkage;
294
295     let mut dylib_paths = Vec::new();
296
297     let data = &crate_info
298         .dependency_formats
299         .iter()
300         .find(|(crate_type, _data)| *crate_type == rustc_session::config::CrateType::Executable)
301         .unwrap()
302         .1;
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 => {}
307             Linkage::Static => {
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.");
311                 err.emit();
312             }
313             Linkage::Dynamic => {
314                 dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
315             }
316         }
317     }
318
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() {
328                 return None;
329             }
330             if name.starts_with("rust_metadata_") {
331                 // The metadata is part of a section that is not loaded by the dynamic linker in
332                 // case of cg_llvm.
333                 return None;
334             }
335             let dlsym_name = if cfg!(target_os = "macos") {
336                 // On macOS `dlsym` expects the name without leading `_`.
337                 assert!(name.starts_with('_'), "{:?}", name);
338                 &name[1..]
339             } else {
340                 &name
341             };
342             let symbol: libloading::Symbol<'_, *const u8> =
343                 unsafe { lib.get(dlsym_name.as_bytes()) }.unwrap();
344             Some((name, *symbol))
345         }));
346         std::mem::forget(lib)
347     }
348
349     sess.abort_if_errors();
350
351     imported_symbols
352 }
353
354 fn codegen_shim<'tcx>(
355     tcx: TyCtxt<'tcx>,
356     cx: &mut CodegenCx,
357     cached_context: &mut Context,
358     module: &mut JITModule,
359     inst: Instance<'tcx>,
360 ) {
361     let pointer_type = module.target_config().pointer_type();
362
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();
366
367     let instance_ptr = Box::into_raw(Box::new(inst));
368
369     let jit_fn = module
370         .declare_function(
371             "__clif_jit_fn",
372             Linkage::Import,
373             &Signature {
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)],
377             },
378         )
379         .unwrap();
380
381     let context = cached_context;
382     context.clear();
383     let trampoline = &mut context.func;
384     trampoline.signature = sig.clone();
385
386     let mut builder_ctx = FunctionBuilderContext::new();
387     let mut trampoline_builder = FunctionBuilder::new(trampoline, &mut builder_ctx);
388
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);
392
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();
396
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);
405
406     module.define_function(func_id, context).unwrap();
407     cx.unwind_context.add_function(func_id, context, module.isa());
408 }