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