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