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