4 use std::os::raw::{c_char, c_int};
6 use rustc::middle::cstore::EncodedMetadata;
7 use rustc::mir::mono::{Linkage as RLinkage, Visibility};
8 use rustc::session::config::{DebugInfo, OutputType};
9 use rustc_codegen_ssa::back::linker::LinkerInfo;
10 use rustc_codegen_ssa::CrateInfo;
12 use cranelift_faerie::*;
14 use crate::prelude::*;
18 metadata: EncodedMetadata,
19 need_metadata_module: bool,
21 tcx.sess.abort_if_errors();
23 let mut log = if cfg!(debug_assertions) {
24 Some(File::create(concat!(env!("CARGO_MANIFEST_DIR"), "/target/out/log.txt")).unwrap())
29 if std::env::var("SHOULD_RUN").is_ok()
30 && tcx.sess.crate_types.get().contains(&CrateType::Executable)
32 #[cfg(not(target_arch = "wasm32"))]
33 let _: ! = run_jit(tcx, &mut log);
35 #[cfg(target_arch = "wasm32")]
36 panic!("jit not supported on wasm");
39 run_aot(tcx, metadata, need_metadata_module, &mut log)
42 #[cfg(not(target_arch = "wasm32"))]
43 fn run_jit(tcx: TyCtxt<'_>, log: &mut Option<File>) -> ! {
44 use cranelift_simplejit::{SimpleJITBackend, SimpleJITBuilder};
46 let imported_symbols = load_imported_symbols_for_jit(tcx);
48 let mut jit_builder = SimpleJITBuilder::with_isa(
49 crate::build_isa(tcx.sess, false),
50 cranelift_module::default_libcall_names(),
52 jit_builder.symbols(imported_symbols);
53 let mut jit_module: Module<SimpleJITBackend> = Module::new(jit_builder);
54 assert_eq!(pointer_ty(tcx), jit_module.target_config().pointer_type());
58 AbiParam::new(jit_module.target_config().pointer_type()),
59 AbiParam::new(jit_module.target_config().pointer_type()),
61 returns: vec![AbiParam::new(
62 jit_module.target_config().pointer_type(), /*isize*/
64 call_conv: CallConv::SystemV,
66 let main_func_id = jit_module
67 .declare_function("main", Linkage::Import, &sig)
70 codegen_cgus(tcx, &mut jit_module, &mut None, log);
71 crate::allocator::codegen(tcx.sess, &mut jit_module);
72 jit_module.finalize_definitions();
74 tcx.sess.abort_if_errors();
76 let finalized_main: *const u8 = jit_module.get_finalized_function(main_func_id);
78 println!("Rustc codegen cranelift will JIT run the executable, because the SHOULD_RUN env var is set");
80 let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
81 unsafe { ::std::mem::transmute(finalized_main) };
83 let args = ::std::env::var("JIT_ARGS").unwrap_or_else(|_| String::new());
86 .chain(Some(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string()))
87 .map(|arg| CString::new(arg).unwrap())
89 let argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
90 // TODO: Rust doesn't care, but POSIX argv has a NULL sentinel at the end
92 let ret = f(args.len() as c_int, argv.as_ptr());
95 std::process::exit(ret);
98 fn load_imported_symbols_for_jit(tcx: TyCtxt<'_>) -> Vec<(String, *const u8)> {
99 use rustc::middle::dependency_format::Linkage;
101 let mut dylib_paths = Vec::new();
103 let crate_info = CrateInfo::new(tcx);
104 let formats = tcx.sess.dependency_formats.borrow();
105 let data = formats.get(&CrateType::Executable).unwrap();
106 for &(cnum, _) in &crate_info.used_crates_dynamic {
107 let src = &crate_info.used_crate_source[&cnum];
108 match data[cnum.as_usize() - 1] {
109 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
111 let name = tcx.crate_name(cnum);
112 let mut err = tcx.sess.struct_err(&format!("Can't load static lib {}", name.as_str()));
113 err.note("rustc_codegen_cranelift can only load dylibs in JIT mode.");
116 Linkage::Dynamic => {
117 dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
122 let mut imported_symbols = Vec::new();
123 for path in dylib_paths {
125 let lib = libloading::Library::new(&path).unwrap();
126 let obj = std::fs::read(path).unwrap();
127 let obj = object::File::parse(&obj).unwrap();
128 imported_symbols.extend(obj.dynamic_symbols().filter_map(|(_idx, symbol)| {
129 let name = symbol.name().unwrap().to_string();
130 if name.is_empty() || !symbol.is_global() || symbol.is_undefined() {
133 let symbol: libloading::Symbol<*const u8> =
134 unsafe { lib.get(name.as_bytes()) }.unwrap();
135 Some((name, *symbol))
137 std::mem::forget(lib)
140 tcx.sess.abort_if_errors();
147 metadata: EncodedMetadata,
148 need_metadata_module: bool,
149 log: &mut Option<File>,
150 ) -> Box<CodegenResults> {
151 let new_module = |name: String| {
152 let module: Module<FaerieBackend> = Module::new(
154 crate::build_isa(tcx.sess, true),
156 FaerieTrapCollection::Disabled,
157 cranelift_module::default_libcall_names(),
161 assert_eq!(pointer_ty(tcx), module.target_config().pointer_type());
165 let emit_module = |name: &str,
167 mut module: Module<FaerieBackend>,
168 debug: Option<DebugContext>| {
169 module.finalize_definitions();
170 let mut artifact = module.finish().artifact;
172 if let Some(mut debug) = debug {
173 debug.emit(&mut artifact);
177 .output_filenames(LOCAL_CRATE)
178 .temp_path(OutputType::Object, Some(name));
179 let obj = artifact.emit().unwrap();
180 std::fs::write(&tmp_file, obj).unwrap();
182 name: name.to_string(),
184 object: Some(tmp_file),
186 bytecode_compressed: None,
190 let mut faerie_module = new_module("some_file".to_string());
192 let mut debug = if tcx.sess.opts.debuginfo != DebugInfo::None
193 // macOS debuginfo doesn't work yet (see #303)
194 && !tcx.sess.target.target.options.is_like_osx
196 let debug = DebugContext::new(
198 faerie_module.target_config().pointer_type().bytes() as u8,
205 codegen_cgus(tcx, &mut faerie_module, &mut debug, log);
207 tcx.sess.abort_if_errors();
209 let mut allocator_module = new_module("allocator_shim.o".to_string());
210 let created_alloc_shim = crate::allocator::codegen(tcx.sess, &mut allocator_module);
212 rustc_incremental::assert_dep_graph(tcx);
213 rustc_incremental::save_dep_graph(tcx);
214 rustc_incremental::finalize_session_directory(tcx.sess, tcx.crate_hash(LOCAL_CRATE));
216 let metadata_module = if need_metadata_module {
217 use rustc::mir::mono::CodegenUnitNameBuilder;
219 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
220 let metadata_cgu_name = cgu_name_builder
221 .build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata"))
225 let mut metadata_artifact =
226 faerie::Artifact::new(crate::build_isa(tcx.sess, true).triple().clone(), metadata_cgu_name.clone());
227 crate::metadata::write_metadata(tcx, &mut metadata_artifact);
230 .output_filenames(LOCAL_CRATE)
231 .temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
233 let obj = metadata_artifact.emit().unwrap();
234 std::fs::write(&tmp_file, obj).unwrap();
236 Some(CompiledModule {
237 name: metadata_cgu_name,
238 kind: ModuleKind::Metadata,
239 object: Some(tmp_file),
241 bytecode_compressed: None,
247 Box::new(CodegenResults {
248 crate_name: tcx.crate_name(LOCAL_CRATE),
249 modules: vec![emit_module(
255 allocator_module: if created_alloc_shim {
258 ModuleKind::Allocator,
266 crate_hash: tcx.crate_hash(LOCAL_CRATE),
268 windows_subsystem: None, // Windows is not yet supported
269 linker_info: LinkerInfo::new(tcx),
270 crate_info: CrateInfo::new(tcx),
274 fn codegen_cgus<'tcx>(
276 module: &mut Module<impl Backend + 'static>,
277 debug: &mut Option<DebugContext<'tcx>>,
278 log: &mut Option<File>,
280 let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
281 let mono_items = cgus
283 .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
285 .collect::<FxHashMap<_, (_, _)>>();
287 codegen_mono_items(tcx, module, debug.as_mut(), log, mono_items);
289 crate::main_shim::maybe_create_entry_wrapper(tcx, module);
292 fn codegen_mono_items<'tcx>(
294 module: &mut Module<impl Backend + 'static>,
295 debug_context: Option<&mut DebugContext<'tcx>>,
296 log: &mut Option<File>,
297 mono_items: FxHashMap<MonoItem<'tcx>, (RLinkage, Visibility)>,
299 let mut cx = CodegenCx::new(tcx, module, debug_context);
300 time("codegen mono items", move || {
301 for (mono_item, (linkage, visibility)) in mono_items {
302 crate::unimpl::try_unimpl(tcx, log, || {
303 let linkage = crate::linkage::get_clif_linkage(mono_item, linkage, visibility);
304 trans_mono_item(&mut cx, mono_item, linkage);
312 fn trans_mono_item<'clif, 'tcx, B: Backend + 'static>(
313 cx: &mut crate::CodegenCx<'clif, 'tcx, B>,
314 mono_item: MonoItem<'tcx>,
319 MonoItem::Fn(inst) => {
321 PrintOnPanic(|| format!("{:?} {}", inst, tcx.symbol_name(inst).as_str()));
322 debug_assert!(!inst.substs.needs_infer());
323 let _mir_guard = PrintOnPanic(|| {
326 | InstanceDef::DropGlue(_, _)
327 | InstanceDef::Virtual(_, _) => {
328 let mut mir = ::std::io::Cursor::new(Vec::new());
329 crate::rustc_mir::util::write_mir_pretty(
335 String::from_utf8(mir.into_inner()).unwrap()
338 // FIXME fix write_mir_pretty for these instances
339 format!("{:#?}", tcx.instance_mir(inst.def))
344 crate::base::trans_fn(cx, inst, linkage);
346 MonoItem::Static(def_id) => {
347 crate::constant::codegen_static(&mut cx.constants_cx, def_id);
349 MonoItem::GlobalAsm(node_id) => tcx
351 .fatal(&format!("Unimplemented global asm mono item {:?}", node_id)),
355 fn time<R>(name: &str, f: impl FnOnce() -> R) -> R {
356 println!("[{}] start", name);
357 let before = std::time::Instant::now();
359 let after = std::time::Instant::now();
360 println!("[{}] end time: {:?}", name, after - before);