]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/driver/aot.rs
Auto merge of #85178 - cjgillot:local-crate, r=oli-obk
[rust.git] / compiler / rustc_codegen_cranelift / src / driver / aot.rs
1 //! The AOT driver uses [`cranelift_object`] to write object files suitable for linking into a
2 //! standalone executable.
3
4 use std::path::PathBuf;
5
6 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
7 use rustc_codegen_ssa::back::linker::LinkerInfo;
8 use rustc_codegen_ssa::{CodegenResults, CompiledModule, CrateInfo, ModuleKind};
9 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
10 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
11 use rustc_middle::middle::cstore::EncodedMetadata;
12 use rustc_middle::mir::mono::{CodegenUnit, MonoItem};
13 use rustc_session::cgu_reuse_tracker::CguReuse;
14 use rustc_session::config::{DebugInfo, OutputType};
15
16 use cranelift_object::ObjectModule;
17
18 use crate::{prelude::*, BackendConfig};
19
20 struct ModuleCodegenResult(CompiledModule, Option<(WorkProductId, WorkProduct)>);
21
22 impl<HCX> HashStable<HCX> for ModuleCodegenResult {
23     fn hash_stable(&self, _: &mut HCX, _: &mut StableHasher) {
24         // do nothing
25     }
26 }
27
28 fn emit_module(
29     tcx: TyCtxt<'_>,
30     backend_config: &BackendConfig,
31     name: String,
32     kind: ModuleKind,
33     module: ObjectModule,
34     debug: Option<DebugContext<'_>>,
35     unwind_context: UnwindContext,
36 ) -> ModuleCodegenResult {
37     let mut product = module.finish();
38
39     if let Some(mut debug) = debug {
40         debug.emit(&mut product);
41     }
42
43     unwind_context.emit(&mut product);
44
45     let tmp_file = tcx.output_filenames(()).temp_path(OutputType::Object, Some(&name));
46     let obj = product.object.write().unwrap();
47     if let Err(err) = std::fs::write(&tmp_file, obj) {
48         tcx.sess.fatal(&format!("error writing object file: {}", err));
49     }
50
51     let work_product = if backend_config.disable_incr_cache {
52         None
53     } else {
54         rustc_incremental::copy_cgu_workproduct_to_incr_comp_cache_dir(
55             tcx.sess,
56             &name,
57             &Some(tmp_file.clone()),
58         )
59     };
60
61     ModuleCodegenResult(
62         CompiledModule { name, kind, object: Some(tmp_file), dwarf_object: None, bytecode: None },
63         work_product,
64     )
65 }
66
67 fn reuse_workproduct_for_cgu(
68     tcx: TyCtxt<'_>,
69     cgu: &CodegenUnit<'_>,
70     work_products: &mut FxHashMap<WorkProductId, WorkProduct>,
71 ) -> CompiledModule {
72     let incr_comp_session_dir = tcx.sess.incr_comp_session_dir();
73     let mut object = None;
74     let work_product = cgu.work_product(tcx);
75     if let Some(saved_file) = &work_product.saved_file {
76         let obj_out = tcx
77             .output_filenames(())
78             .temp_path(OutputType::Object, Some(&cgu.name().as_str()));
79         object = Some(obj_out.clone());
80         let source_file = rustc_incremental::in_incr_comp_dir(&incr_comp_session_dir, &saved_file);
81         if let Err(err) = rustc_fs_util::link_or_copy(&source_file, &obj_out) {
82             tcx.sess.err(&format!(
83                 "unable to copy {} to {}: {}",
84                 source_file.display(),
85                 obj_out.display(),
86                 err
87             ));
88         }
89     }
90
91     work_products.insert(cgu.work_product_id(), work_product);
92
93     CompiledModule {
94         name: cgu.name().to_string(),
95         kind: ModuleKind::Regular,
96         object,
97         dwarf_object: None,
98         bytecode: None,
99     }
100 }
101
102 fn module_codegen(
103     tcx: TyCtxt<'_>,
104     (backend_config, cgu_name): (BackendConfig, rustc_span::Symbol),
105 ) -> ModuleCodegenResult {
106     let cgu = tcx.codegen_unit(cgu_name);
107     let mono_items = cgu.items_in_deterministic_order(tcx);
108
109     let isa = crate::build_isa(tcx.sess, &backend_config);
110     let mut module = crate::backend::make_module(tcx.sess, isa, cgu_name.as_str().to_string());
111
112     let mut cx = crate::CodegenCx::new(
113         tcx,
114         backend_config.clone(),
115         module.isa(),
116         tcx.sess.opts.debuginfo != DebugInfo::None,
117     );
118     super::predefine_mono_items(tcx, &mut module, &mono_items);
119     for (mono_item, _) in mono_items {
120         match mono_item {
121             MonoItem::Fn(inst) => {
122                 cx.tcx
123                     .sess
124                     .time("codegen fn", || crate::base::codegen_fn(&mut cx, &mut module, inst));
125             }
126             MonoItem::Static(def_id) => crate::constant::codegen_static(tcx, &mut module, def_id),
127             MonoItem::GlobalAsm(item_id) => {
128                 let item = cx.tcx.hir().item(item_id);
129                 if let rustc_hir::ItemKind::GlobalAsm(asm) = item.kind {
130                     if !asm.options.contains(InlineAsmOptions::ATT_SYNTAX) {
131                         cx.global_asm.push_str("\n.intel_syntax noprefix\n");
132                     } else {
133                         cx.global_asm.push_str("\n.att_syntax\n");
134                     }
135                     for piece in asm.template {
136                         match *piece {
137                             InlineAsmTemplatePiece::String(ref s) => cx.global_asm.push_str(s),
138                             InlineAsmTemplatePiece::Placeholder { .. } => todo!(),
139                         }
140                     }
141                     cx.global_asm.push_str("\n.att_syntax\n\n");
142                 } else {
143                     bug!("Expected GlobalAsm found {:?}", item);
144                 }
145             }
146         }
147     }
148     crate::main_shim::maybe_create_entry_wrapper(tcx, &mut module, &mut cx.unwind_context, false);
149
150     let debug_context = cx.debug_context;
151     let unwind_context = cx.unwind_context;
152     let codegen_result = tcx.sess.time("write object file", || {
153         emit_module(
154             tcx,
155             &backend_config,
156             cgu.name().as_str().to_string(),
157             ModuleKind::Regular,
158             module,
159             debug_context,
160             unwind_context,
161         )
162     });
163
164     codegen_global_asm(tcx, &cgu.name().as_str(), &cx.global_asm);
165
166     codegen_result
167 }
168
169 pub(crate) fn run_aot(
170     tcx: TyCtxt<'_>,
171     backend_config: BackendConfig,
172     metadata: EncodedMetadata,
173     need_metadata_module: bool,
174 ) -> Box<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)> {
175     use rustc_span::symbol::sym;
176
177     let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID);
178     let subsystem = tcx.sess.first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
179     let windows_subsystem = subsystem.map(|subsystem| {
180         if subsystem != sym::windows && subsystem != sym::console {
181             tcx.sess.fatal(&format!(
182                 "invalid windows subsystem `{}`, only \
183                                     `windows` and `console` are allowed",
184                 subsystem
185             ));
186         }
187         subsystem.to_string()
188     });
189
190     let mut work_products = FxHashMap::default();
191
192     let cgus = if tcx.sess.opts.output_types.should_codegen() {
193         tcx.collect_and_partition_mono_items(()).1
194     } else {
195         // If only `--emit metadata` is used, we shouldn't perform any codegen.
196         // Also `tcx.collect_and_partition_mono_items` may panic in that case.
197         &[]
198     };
199
200     if tcx.dep_graph.is_fully_enabled() {
201         for cgu in &*cgus {
202             tcx.ensure().codegen_unit(cgu.name());
203         }
204     }
205
206     let modules = super::time(tcx, backend_config.display_cg_time, "codegen mono items", || {
207         cgus.iter()
208             .map(|cgu| {
209                 let cgu_reuse = determine_cgu_reuse(tcx, cgu);
210                 tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
211
212                 match cgu_reuse {
213                     _ if backend_config.disable_incr_cache => {}
214                     CguReuse::No => {}
215                     CguReuse::PreLto => {
216                         return reuse_workproduct_for_cgu(tcx, &*cgu, &mut work_products);
217                     }
218                     CguReuse::PostLto => unreachable!(),
219                 }
220
221                 let dep_node = cgu.codegen_dep_node(tcx);
222                 let (ModuleCodegenResult(module, work_product), _) = tcx.dep_graph.with_task(
223                     dep_node,
224                     tcx,
225                     (backend_config.clone(), cgu.name()),
226                     module_codegen,
227                     rustc_middle::dep_graph::hash_result,
228                 );
229
230                 if let Some((id, product)) = work_product {
231                     work_products.insert(id, product);
232                 }
233
234                 module
235             })
236             .collect::<Vec<_>>()
237     });
238
239     tcx.sess.abort_if_errors();
240
241     let isa = crate::build_isa(tcx.sess, &backend_config);
242     let mut allocator_module =
243         crate::backend::make_module(tcx.sess, isa, "allocator_shim".to_string());
244     assert_eq!(pointer_ty(tcx), allocator_module.target_config().pointer_type());
245     let mut allocator_unwind_context = UnwindContext::new(tcx, allocator_module.isa(), true);
246     let created_alloc_shim =
247         crate::allocator::codegen(tcx, &mut allocator_module, &mut allocator_unwind_context);
248
249     let allocator_module = if created_alloc_shim {
250         let ModuleCodegenResult(module, work_product) = emit_module(
251             tcx,
252             &backend_config,
253             "allocator_shim".to_string(),
254             ModuleKind::Allocator,
255             allocator_module,
256             None,
257             allocator_unwind_context,
258         );
259         if let Some((id, product)) = work_product {
260             work_products.insert(id, product);
261         }
262         Some(module)
263     } else {
264         None
265     };
266
267     let metadata_module = if need_metadata_module {
268         let _timer = tcx.prof.generic_activity("codegen crate metadata");
269         let (metadata_cgu_name, tmp_file) = tcx.sess.time("write compressed metadata", || {
270             use rustc_middle::mir::mono::CodegenUnitNameBuilder;
271
272             let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
273             let metadata_cgu_name = cgu_name_builder
274                 .build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata"))
275                 .as_str()
276                 .to_string();
277
278             let tmp_file = tcx
279                 .output_filenames(())
280                 .temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
281
282             let obj = crate::backend::with_object(tcx.sess, &metadata_cgu_name, |object| {
283                 crate::metadata::write_metadata(tcx, object);
284             });
285
286             if let Err(err) = std::fs::write(&tmp_file, obj) {
287                 tcx.sess.fatal(&format!("error writing metadata object file: {}", err));
288             }
289
290             (metadata_cgu_name, tmp_file)
291         });
292
293         Some(CompiledModule {
294             name: metadata_cgu_name,
295             kind: ModuleKind::Metadata,
296             object: Some(tmp_file),
297             dwarf_object: None,
298             bytecode: None,
299         })
300     } else {
301         None
302     };
303
304     Box::new((
305         CodegenResults {
306             crate_name: tcx.crate_name(LOCAL_CRATE),
307             modules,
308             allocator_module,
309             metadata_module,
310             metadata,
311             windows_subsystem,
312             linker_info: LinkerInfo::new(tcx, crate::target_triple(tcx.sess).to_string()),
313             crate_info: CrateInfo::new(tcx),
314         },
315         work_products,
316     ))
317 }
318
319 fn codegen_global_asm(tcx: TyCtxt<'_>, cgu_name: &str, global_asm: &str) {
320     use std::io::Write;
321     use std::process::{Command, Stdio};
322
323     if global_asm.is_empty() {
324         return;
325     }
326
327     if cfg!(not(feature = "inline_asm"))
328         || tcx.sess.target.is_like_osx
329         || tcx.sess.target.is_like_windows
330     {
331         if global_asm.contains("__rust_probestack") {
332             return;
333         }
334
335         // FIXME fix linker error on macOS
336         if cfg!(not(feature = "inline_asm")) {
337             tcx.sess.fatal(
338                 "asm! and global_asm! support is disabled while compiling rustc_codegen_cranelift",
339             );
340         } else {
341             tcx.sess.fatal("asm! and global_asm! are not yet supported on macOS and Windows");
342         }
343     }
344
345     let assembler = crate::toolchain::get_toolchain_binary(tcx.sess, "as");
346     let linker = crate::toolchain::get_toolchain_binary(tcx.sess, "ld");
347
348     // Remove all LLVM style comments
349     let global_asm = global_asm
350         .lines()
351         .map(|line| if let Some(index) = line.find("//") { &line[0..index] } else { line })
352         .collect::<Vec<_>>()
353         .join("\n");
354
355     let output_object_file =
356         tcx.output_filenames(()).temp_path(OutputType::Object, Some(cgu_name));
357
358     // Assemble `global_asm`
359     let global_asm_object_file = add_file_stem_postfix(output_object_file.clone(), ".asm");
360     let mut child = Command::new(assembler)
361         .arg("-o")
362         .arg(&global_asm_object_file)
363         .stdin(Stdio::piped())
364         .spawn()
365         .expect("Failed to spawn `as`.");
366     child.stdin.take().unwrap().write_all(global_asm.as_bytes()).unwrap();
367     let status = child.wait().expect("Failed to wait for `as`.");
368     if !status.success() {
369         tcx.sess.fatal(&format!("Failed to assemble `{}`", global_asm));
370     }
371
372     // Link the global asm and main object file together
373     let main_object_file = add_file_stem_postfix(output_object_file.clone(), ".main");
374     std::fs::rename(&output_object_file, &main_object_file).unwrap();
375     let status = Command::new(linker)
376         .arg("-r") // Create a new object file
377         .arg("-o")
378         .arg(output_object_file)
379         .arg(&main_object_file)
380         .arg(&global_asm_object_file)
381         .status()
382         .unwrap();
383     if !status.success() {
384         tcx.sess.fatal(&format!(
385             "Failed to link `{}` and `{}` together",
386             main_object_file.display(),
387             global_asm_object_file.display(),
388         ));
389     }
390
391     std::fs::remove_file(global_asm_object_file).unwrap();
392     std::fs::remove_file(main_object_file).unwrap();
393 }
394
395 fn add_file_stem_postfix(mut path: PathBuf, postfix: &str) -> PathBuf {
396     let mut new_filename = path.file_stem().unwrap().to_owned();
397     new_filename.push(postfix);
398     if let Some(extension) = path.extension() {
399         new_filename.push(".");
400         new_filename.push(extension);
401     }
402     path.set_file_name(new_filename);
403     path
404 }
405
406 // Adapted from https://github.com/rust-lang/rust/blob/303d8aff6092709edd4dbd35b1c88e9aa40bf6d8/src/librustc_codegen_ssa/base.rs#L922-L953
407 fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
408     if !tcx.dep_graph.is_fully_enabled() {
409         return CguReuse::No;
410     }
411
412     let work_product_id = &cgu.work_product_id();
413     if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
414         // We don't have anything cached for this CGU. This can happen
415         // if the CGU did not exist in the previous session.
416         return CguReuse::No;
417     }
418
419     // Try to mark the CGU as green. If it we can do so, it means that nothing
420     // affecting the LLVM module has changed and we can re-use a cached version.
421     // If we compile with any kind of LTO, this means we can re-use the bitcode
422     // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
423     // know that later). If we are not doing LTO, there is only one optimized
424     // version of each module, so we re-use that.
425     let dep_node = cgu.codegen_dep_node(tcx);
426     assert!(
427         !tcx.dep_graph.dep_node_exists(&dep_node),
428         "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
429         cgu.name()
430     );
431
432     if tcx.try_mark_green(&dep_node) { CguReuse::PreLto } else { CguReuse::No }
433 }