|
| 1 | +use std::any::Any; |
| 2 | +use std::ffi::CString; |
| 3 | +use std::fs::File; |
| 4 | +use std::os::raw::{c_char, c_int}; |
| 5 | + |
| 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; |
| 11 | +use rustc_mir::monomorphize::partitioning::CodegenUnitExt; |
| 12 | + |
| 13 | +use cranelift_faerie::*; |
| 14 | + |
| 15 | +use crate::prelude::*; |
| 16 | + |
| 17 | +pub fn codegen_crate<'a, 'tcx>( |
| 18 | + tcx: TyCtxt<'a, 'tcx, 'tcx>, |
| 19 | + metadata: EncodedMetadata, |
| 20 | + _need_metadata_module: bool, |
| 21 | +) -> Box<dyn Any> { |
| 22 | + env_logger::init(); |
| 23 | + if !tcx.sess.crate_types.get().contains(&CrateType::Executable) |
| 24 | + && std::env::var("SHOULD_RUN").is_ok() |
| 25 | + { |
| 26 | + tcx.sess |
| 27 | + .err("Can't JIT run non executable (SHOULD_RUN env var is set)"); |
| 28 | + } |
| 29 | + |
| 30 | + tcx.sess.abort_if_errors(); |
| 31 | + |
| 32 | + let mut log = if cfg!(debug_assertions) { |
| 33 | + Some(File::create(concat!(env!("CARGO_MANIFEST_DIR"), "/target/out/log.txt")).unwrap()) |
| 34 | + } else { |
| 35 | + None |
| 36 | + }; |
| 37 | + |
| 38 | + if std::env::var("SHOULD_RUN").is_ok() { |
| 39 | + let mut jit_module: Module<SimpleJITBackend> = |
| 40 | + Module::new(SimpleJITBuilder::new(cranelift_module::default_libcall_names())); |
| 41 | + assert_eq!(pointer_ty(tcx), jit_module.target_config().pointer_type()); |
| 42 | + |
| 43 | + let sig = Signature { |
| 44 | + params: vec![ |
| 45 | + AbiParam::new(jit_module.target_config().pointer_type()), |
| 46 | + AbiParam::new(jit_module.target_config().pointer_type()), |
| 47 | + ], |
| 48 | + returns: vec![AbiParam::new( |
| 49 | + jit_module.target_config().pointer_type(), /*isize*/ |
| 50 | + )], |
| 51 | + call_conv: CallConv::SystemV, |
| 52 | + }; |
| 53 | + let main_func_id = jit_module |
| 54 | + .declare_function("main", Linkage::Import, &sig) |
| 55 | + .unwrap(); |
| 56 | + |
| 57 | + codegen_cgus(tcx, &mut jit_module, &mut None, &mut log); |
| 58 | + crate::allocator::codegen(tcx.sess, &mut jit_module); |
| 59 | + jit_module.finalize_definitions(); |
| 60 | + |
| 61 | + tcx.sess.abort_if_errors(); |
| 62 | + |
| 63 | + let finalized_main: *const u8 = jit_module.get_finalized_function(main_func_id); |
| 64 | + |
| 65 | + println!("Rustc codegen cranelift will JIT run the executable, because the SHOULD_RUN env var is set"); |
| 66 | + |
| 67 | + let f: extern "C" fn(c_int, *const *const c_char) -> c_int = |
| 68 | + unsafe { ::std::mem::transmute(finalized_main) }; |
| 69 | + |
| 70 | + let args = ::std::env::var("JIT_ARGS").unwrap_or_else(|_| String::new()); |
| 71 | + let args = args |
| 72 | + .split(" ") |
| 73 | + .chain(Some(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string())) |
| 74 | + .map(|arg| CString::new(arg).unwrap()) |
| 75 | + .collect::<Vec<_>>(); |
| 76 | + let argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>(); |
| 77 | + // TODO: Rust doesn't care, but POSIX argv has a NULL sentinel at the end |
| 78 | + |
| 79 | + let ret = f(args.len() as c_int, argv.as_ptr()); |
| 80 | + |
| 81 | + jit_module.finish(); |
| 82 | + std::process::exit(ret); |
| 83 | + } else { |
| 84 | + let new_module = |name: String| { |
| 85 | + let module: Module<FaerieBackend> = Module::new( |
| 86 | + FaerieBuilder::new( |
| 87 | + crate::build_isa(tcx.sess), |
| 88 | + name + ".o", |
| 89 | + FaerieTrapCollection::Disabled, |
| 90 | + cranelift_module::default_libcall_names(), |
| 91 | + ) |
| 92 | + .unwrap(), |
| 93 | + ); |
| 94 | + assert_eq!(pointer_ty(tcx), module.target_config().pointer_type()); |
| 95 | + module |
| 96 | + }; |
| 97 | + |
| 98 | + let emit_module = |name: &str, |
| 99 | + kind: ModuleKind, |
| 100 | + mut module: Module<FaerieBackend>, |
| 101 | + debug: Option<DebugContext>| { |
| 102 | + module.finalize_definitions(); |
| 103 | + let mut artifact = module.finish().artifact; |
| 104 | + |
| 105 | + if let Some(mut debug) = debug { |
| 106 | + debug.emit(&mut artifact); |
| 107 | + } |
| 108 | + |
| 109 | + let tmp_file = tcx |
| 110 | + .output_filenames(LOCAL_CRATE) |
| 111 | + .temp_path(OutputType::Object, Some(name)); |
| 112 | + let obj = artifact.emit().unwrap(); |
| 113 | + std::fs::write(&tmp_file, obj).unwrap(); |
| 114 | + CompiledModule { |
| 115 | + name: name.to_string(), |
| 116 | + kind, |
| 117 | + object: Some(tmp_file), |
| 118 | + bytecode: None, |
| 119 | + bytecode_compressed: None, |
| 120 | + } |
| 121 | + }; |
| 122 | + |
| 123 | + let mut faerie_module = new_module("some_file".to_string()); |
| 124 | + |
| 125 | + let mut debug = if tcx.sess.opts.debuginfo != DebugInfo::None |
| 126 | + // macOS debuginfo doesn't work yet (see #303) |
| 127 | + && !tcx.sess.target.target.options.is_like_osx |
| 128 | + { |
| 129 | + let debug = DebugContext::new( |
| 130 | + tcx, |
| 131 | + faerie_module.target_config().pointer_type().bytes() as u8, |
| 132 | + ); |
| 133 | + Some(debug) |
| 134 | + } else { |
| 135 | + None |
| 136 | + }; |
| 137 | + |
| 138 | + codegen_cgus(tcx, &mut faerie_module, &mut debug, &mut log); |
| 139 | + |
| 140 | + tcx.sess.abort_if_errors(); |
| 141 | + |
| 142 | + let mut allocator_module = new_module("allocator_shim.o".to_string()); |
| 143 | + let created_alloc_shim = crate::allocator::codegen(tcx.sess, &mut allocator_module); |
| 144 | + |
| 145 | + rustc_incremental::assert_dep_graph(tcx); |
| 146 | + rustc_incremental::save_dep_graph(tcx); |
| 147 | + rustc_incremental::finalize_session_directory(tcx.sess, tcx.crate_hash(LOCAL_CRATE)); |
| 148 | + |
| 149 | + Box::new(CodegenResults { |
| 150 | + crate_name: tcx.crate_name(LOCAL_CRATE), |
| 151 | + modules: vec![emit_module( |
| 152 | + "dummy_name", |
| 153 | + ModuleKind::Regular, |
| 154 | + faerie_module, |
| 155 | + debug, |
| 156 | + )], |
| 157 | + allocator_module: if created_alloc_shim { |
| 158 | + Some(emit_module( |
| 159 | + "allocator_shim", |
| 160 | + ModuleKind::Allocator, |
| 161 | + allocator_module, |
| 162 | + None, |
| 163 | + )) |
| 164 | + } else { |
| 165 | + None |
| 166 | + }, |
| 167 | + metadata_module: Some(CompiledModule { |
| 168 | + name: "dummy_metadata".to_string(), |
| 169 | + kind: ModuleKind::Metadata, |
| 170 | + object: None, |
| 171 | + bytecode: None, |
| 172 | + bytecode_compressed: None, |
| 173 | + }), |
| 174 | + crate_hash: tcx.crate_hash(LOCAL_CRATE), |
| 175 | + metadata, |
| 176 | + windows_subsystem: None, // Windows is not yet supported |
| 177 | + linker_info: LinkerInfo::new(tcx), |
| 178 | + crate_info: CrateInfo::new(tcx), |
| 179 | + }) |
| 180 | + } |
| 181 | +} |
| 182 | + |
| 183 | +fn codegen_cgus<'a, 'tcx: 'a>( |
| 184 | + tcx: TyCtxt<'a, 'tcx, 'tcx>, |
| 185 | + module: &mut Module<impl Backend + 'static>, |
| 186 | + debug: &mut Option<DebugContext<'tcx>>, |
| 187 | + log: &mut Option<File>, |
| 188 | +) { |
| 189 | + let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE); |
| 190 | + let mono_items = cgus |
| 191 | + .iter() |
| 192 | + .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter()) |
| 193 | + .flatten() |
| 194 | + .collect::<FxHashMap<_, (_, _)>>(); |
| 195 | + |
| 196 | + codegen_mono_items(tcx, module, debug.as_mut(), log, mono_items); |
| 197 | + |
| 198 | + crate::main_shim::maybe_create_entry_wrapper(tcx, module); |
| 199 | +} |
| 200 | + |
| 201 | +fn codegen_mono_items<'a, 'tcx: 'a>( |
| 202 | + tcx: TyCtxt<'a, 'tcx, 'tcx>, |
| 203 | + module: &mut Module<impl Backend + 'static>, |
| 204 | + debug_context: Option<&mut DebugContext<'tcx>>, |
| 205 | + log: &mut Option<File>, |
| 206 | + mono_items: FxHashMap<MonoItem<'tcx>, (RLinkage, Visibility)>, |
| 207 | +) { |
| 208 | + let mut cx = CodegenCx::new(tcx, module, debug_context); |
| 209 | + time("codegen mono items", move || { |
| 210 | + for (mono_item, (linkage, visibility)) in mono_items { |
| 211 | + crate::unimpl::try_unimpl(tcx, log, || { |
| 212 | + let linkage = crate::linkage::get_clif_linkage(mono_item, linkage, visibility); |
| 213 | + trans_mono_item(&mut cx, mono_item, linkage); |
| 214 | + }); |
| 215 | + } |
| 216 | + |
| 217 | + cx.finalize(); |
| 218 | + }); |
| 219 | +} |
| 220 | + |
| 221 | +fn trans_mono_item<'a, 'clif, 'tcx: 'a, B: Backend + 'static>( |
| 222 | + cx: &mut crate::CodegenCx<'a, 'clif, 'tcx, B>, |
| 223 | + mono_item: MonoItem<'tcx>, |
| 224 | + linkage: Linkage, |
| 225 | +) { |
| 226 | + let tcx = cx.tcx; |
| 227 | + match mono_item { |
| 228 | + MonoItem::Fn(inst) => { |
| 229 | + let _inst_guard = |
| 230 | + PrintOnPanic(|| format!("{:?} {}", inst, tcx.symbol_name(inst).as_str())); |
| 231 | + debug_assert!(!inst.substs.needs_infer()); |
| 232 | + let _mir_guard = PrintOnPanic(|| { |
| 233 | + match inst.def { |
| 234 | + InstanceDef::Item(_) |
| 235 | + | InstanceDef::DropGlue(_, _) |
| 236 | + | InstanceDef::Virtual(_, _) |
| 237 | + if inst.def_id().krate == LOCAL_CRATE => |
| 238 | + { |
| 239 | + let mut mir = ::std::io::Cursor::new(Vec::new()); |
| 240 | + crate::rustc_mir::util::write_mir_pretty( |
| 241 | + tcx, |
| 242 | + Some(inst.def_id()), |
| 243 | + &mut mir, |
| 244 | + ) |
| 245 | + .unwrap(); |
| 246 | + String::from_utf8(mir.into_inner()).unwrap() |
| 247 | + } |
| 248 | + _ => { |
| 249 | + // FIXME fix write_mir_pretty for these instances |
| 250 | + format!("{:#?}", tcx.instance_mir(inst.def)) |
| 251 | + } |
| 252 | + } |
| 253 | + }); |
| 254 | + |
| 255 | + crate::base::trans_fn(cx, inst, linkage); |
| 256 | + } |
| 257 | + MonoItem::Static(def_id) => { |
| 258 | + crate::constant::codegen_static(&mut cx.ccx, def_id); |
| 259 | + } |
| 260 | + MonoItem::GlobalAsm(node_id) => tcx |
| 261 | + .sess |
| 262 | + .fatal(&format!("Unimplemented global asm mono item {:?}", node_id)), |
| 263 | + } |
| 264 | +} |
| 265 | + |
| 266 | +fn time<R>(name: &str, f: impl FnOnce() -> R) -> R { |
| 267 | + println!("[{}] start", name); |
| 268 | + let before = std::time::Instant::now(); |
| 269 | + let res = f(); |
| 270 | + let after = std::time::Instant::now(); |
| 271 | + println!("[{}] end time: {:?}", name, after - before); |
| 272 | + res |
| 273 | +} |
0 commit comments