1 use rustc::dep_graph::{WorkProduct, WorkProductFileKind, WorkProductId};
2 use rustc::middle::cstore::EncodedMetadata;
3 use rustc::mir::mono::CodegenUnit;
4 use rustc_session::config::{DebugInfo, OutputType};
5 use rustc_session::cgu_reuse_tracker::CguReuse;
6 use rustc_codegen_ssa::back::linker::LinkerInfo;
7 use rustc_codegen_ssa::CrateInfo;
8 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
10 use crate::prelude::*;
12 use crate::backend::{Emit, WriteDebugInfo};
14 fn new_module(tcx: TyCtxt<'_>, name: String) -> Module<crate::backend::Backend> {
15 let module = crate::backend::make_module(tcx.sess, name);
16 assert_eq!(pointer_ty(tcx), module.target_config().pointer_type());
20 struct ModuleCodegenResult(CompiledModule, Option<(WorkProductId, WorkProduct)>);
23 impl<HCX> HashStable<HCX> for ModuleCodegenResult {
24 fn hash_stable(&self, _: &mut HCX, _: &mut StableHasher) {
29 fn emit_module<B: Backend>(
33 mut module: Module<B>,
34 debug: Option<DebugContext>,
35 ) -> ModuleCodegenResult
36 where B::Product: Emit + WriteDebugInfo,
38 module.finalize_definitions();
39 let mut product = module.finish();
41 if let Some(mut debug) = debug {
42 debug.emit(&mut product);
46 .output_filenames(LOCAL_CRATE)
47 .temp_path(OutputType::Object, Some(&name));
48 let obj = product.emit();
49 std::fs::write(&tmp_file, obj).unwrap();
51 let work_product = if std::env::var("CG_CLIF_INCR_CACHE_DISABLED").is_ok() {
54 rustc_incremental::copy_cgu_workproducts_to_incr_comp_cache_dir(
57 &[(WorkProductFileKind::Object, tmp_file.clone())],
65 object: Some(tmp_file),
67 bytecode_compressed: None,
73 fn reuse_workproduct_for_cgu(
76 work_products: &mut FxHashMap<WorkProductId, WorkProduct>,
78 let incr_comp_session_dir = tcx.sess.incr_comp_session_dir();
79 let mut object = None;
80 let work_product = cgu.work_product(tcx);
81 for (kind, saved_file) in &work_product.saved_files {
82 let obj_out = match kind {
83 WorkProductFileKind::Object => {
84 let path = tcx.output_filenames(LOCAL_CRATE).temp_path(OutputType::Object, Some(&cgu.name().as_str()));
85 object = Some(path.clone());
88 WorkProductFileKind::Bytecode | WorkProductFileKind::BytecodeCompressed => {
89 panic!("cg_clif doesn't use bytecode");
92 let source_file = rustc_incremental::in_incr_comp_dir(&incr_comp_session_dir, &saved_file);
93 if let Err(err) = rustc_fs_util::link_or_copy(&source_file, &obj_out) {
94 tcx.sess.err(&format!(
95 "unable to copy {} to {}: {}",
96 source_file.display(),
103 work_products.insert(cgu.work_product_id(), work_product);
106 name: cgu.name().to_string(),
107 kind: ModuleKind::Regular,
110 bytecode_compressed: None,
114 fn module_codegen(tcx: TyCtxt<'_>, cgu_name: rustc_span::Symbol) -> ModuleCodegenResult {
115 let cgu = tcx.codegen_unit(cgu_name);
116 let mono_items = cgu.items_in_deterministic_order(tcx);
118 let mut module = new_module(tcx, cgu_name.as_str().to_string());
120 let mut debug = if tcx.sess.opts.debuginfo != DebugInfo::None {
121 let debug = DebugContext::new(
123 module.target_config().pointer_type().bytes() as u8,
130 super::codegen_mono_items(tcx, &mut module, debug.as_mut(), mono_items);
131 crate::main_shim::maybe_create_entry_wrapper(tcx, &mut module);
135 cgu.name().as_str().to_string(),
142 pub(super) fn run_aot(
144 metadata: EncodedMetadata,
145 need_metadata_module: bool,
146 ) -> Box<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)> {
147 let mut work_products = FxHashMap::default();
149 let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
151 if tcx.dep_graph.is_fully_enabled() {
153 tcx.codegen_unit(cgu.name());
157 let modules = super::time(tcx, "codegen mono items", || {
158 cgus.iter().map(|cgu| {
159 let cgu_reuse = determine_cgu_reuse(tcx, cgu);
160 tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
163 _ if std::env::var("CG_CLIF_INCR_CACHE_DISABLED").is_ok() => {}
165 CguReuse::PreLto => {
166 return reuse_workproduct_for_cgu(tcx, &*cgu, &mut work_products);
168 CguReuse::PostLto => unreachable!(),
171 let dep_node = cgu.codegen_dep_node(tcx);
172 let (ModuleCodegenResult(module, work_product), _) =
173 tcx.dep_graph.with_task(dep_node, tcx, cgu.name(), module_codegen, rustc::dep_graph::hash_result);
175 if let Some((id, product)) = work_product {
176 work_products.insert(id, product);
180 }).collect::<Vec<_>>()
183 tcx.sess.abort_if_errors();
185 let mut allocator_module = new_module(tcx, "allocator_shim".to_string());
186 let created_alloc_shim = crate::allocator::codegen(tcx, &mut allocator_module);
188 let allocator_module = if created_alloc_shim {
189 let ModuleCodegenResult(module, work_product) = emit_module(
191 "allocator_shim".to_string(),
192 ModuleKind::Allocator,
196 if let Some((id, product)) = work_product {
197 work_products.insert(id, product);
204 rustc_incremental::assert_dep_graph(tcx);
205 rustc_incremental::save_dep_graph(tcx);
207 let metadata_module = if need_metadata_module {
208 let _timer = tcx.prof.generic_activity("codegen crate metadata");
209 let (metadata_cgu_name, tmp_file) = tcx.sess.time("write compressed metadata", || {
210 use rustc::mir::mono::CodegenUnitNameBuilder;
212 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
213 let metadata_cgu_name = cgu_name_builder
214 .build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata"))
219 .output_filenames(LOCAL_CRATE)
220 .temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
222 let obj = crate::backend::with_object(tcx.sess, &metadata_cgu_name, |object| {
223 crate::metadata::write_metadata(tcx, object);
226 std::fs::write(&tmp_file, obj).unwrap();
228 (metadata_cgu_name, tmp_file)
231 Some(CompiledModule {
232 name: metadata_cgu_name,
233 kind: ModuleKind::Metadata,
234 object: Some(tmp_file),
236 bytecode_compressed: None,
242 Box::new((CodegenResults {
243 crate_name: tcx.crate_name(LOCAL_CRATE),
247 crate_hash: tcx.crate_hash(LOCAL_CRATE),
249 windows_subsystem: None, // Windows is not yet supported
250 linker_info: LinkerInfo::new(tcx),
251 crate_info: CrateInfo::new(tcx),
255 // Adapted from https://github.com/rust-lang/rust/blob/303d8aff6092709edd4dbd35b1c88e9aa40bf6d8/src/librustc_codegen_ssa/base.rs#L922-L953
256 fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
257 if !tcx.dep_graph.is_fully_enabled() {
261 let work_product_id = &cgu.work_product_id();
262 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
263 // We don't have anything cached for this CGU. This can happen
264 // if the CGU did not exist in the previous session.
268 // Try to mark the CGU as green. If it we can do so, it means that nothing
269 // affecting the LLVM module has changed and we can re-use a cached version.
270 // If we compile with any kind of LTO, this means we can re-use the bitcode
271 // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
272 // know that later). If we are not doing LTO, there is only one optimized
273 // version of each module, so we re-use that.
274 let dep_node = cgu.codegen_dep_node(tcx);
276 !tcx.dep_graph.dep_node_exists(&dep_node),
277 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
281 if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {