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