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