Skip to main content

rustc_interface/
queries.rs

1use std::any::Any;
2use std::sync::Arc;
3
4use rustc_codegen_ssa::traits::CodegenBackend;
5use rustc_codegen_ssa::{CompiledModules, CrateInfo};
6use rustc_data_structures::svh::Svh;
7use rustc_errors::timings::TimingSection;
8use rustc_hir::def_id::LOCAL_CRATE;
9use rustc_metadata::EncodedMetadata;
10use rustc_middle::dep_graph::{DepGraph, IncrCompSession, WorkProduct};
11use rustc_middle::ty::TyCtxt;
12use rustc_session::Session;
13use rustc_session::config::{self, OutputFilenames};
14use rustc_session::output::OutputType;
15
16use crate::diagnostics::FailedWritingFile;
17use crate::passes;
18
19pub struct Linker {
20    dep_graph: DepGraph,
21    output_filenames: Arc<OutputFilenames>,
22    // Only present when incr. comp. is enabled.
23    crate_hash: Option<Svh>,
24    crate_info: CrateInfo,
25    metadata: EncodedMetadata,
26    ongoing_codegen: Box<dyn Any>,
27}
28
29impl Linker {
30    pub fn codegen_and_build_linker(
31        tcx: TyCtxt<'_>,
32        codegen_backend: &dyn CodegenBackend,
33        metadata: EncodedMetadata,
34    ) -> Linker {
35        let (ongoing_codegen, crate_info) = passes::start_codegen(codegen_backend, tcx);
36
37        Linker {
38            dep_graph: tcx.dep_graph.clone(),
39            output_filenames: Arc::clone(tcx.output_filenames(())),
40            crate_hash: if tcx.sess.opts.incremental.is_some() {
41                Some(tcx.crate_hash(LOCAL_CRATE))
42            } else {
43                None
44            },
45            crate_info,
46            metadata,
47            ongoing_codegen,
48        }
49    }
50
51    pub fn link(
52        self,
53        sess: &Session,
54        mut incr_comp_session: Option<IncrCompSession>,
55        codegen_backend: &dyn CodegenBackend,
56    ) {
57        let compiled_modules = sess.time("finish_ongoing_codegen", || {
58            match self.ongoing_codegen.downcast::<CompiledModules>() {
59                // This was a check only build
60                Ok(compiled_modules) => *compiled_modules,
61
62                Err(ongoing_codegen) => codegen_backend.join_codegen(
63                    ongoing_codegen,
64                    sess,
65                    incr_comp_session.as_mut(),
66                    &self.output_filenames,
67                    &self.crate_info,
68                ),
69            }
70        });
71
72        // Backends could raise an error, do not continue if that's the case.
73        if let Some(guar) = sess.dcx().has_errors_or_delayed_bugs() {
74            guar.raise_fatal();
75        }
76
77        sess.timings.end_section(sess.dcx(), TimingSection::Codegen);
78
79        if sess.opts.incremental.is_some()
80            && let Some(path) = self.metadata.path()
81        {
82            rustc_incremental::copy_cgu_workproduct_to_incr_comp_cache_dir(
83                sess,
84                incr_comp_session.as_mut().unwrap(),
85                WorkProduct::METADATA_WORKPRODUCT_CGU_NAME,
86                &[(OutputType::Metadata.extension(), path)],
87            );
88        }
89
90        let _timer = sess.timer("link");
91
92        let prof = sess.prof.clone();
93        prof.generic_activity("drop_dep_graph").run(move || drop(self.dep_graph));
94
95        // Now that we won't touch anything in the incremental compilation directory
96        // any more, we can finalize it (which involves renaming it)
97        if let Some(incr_comp_session) = incr_comp_session {
98            rustc_incremental::finalize_session_directory(
99                sess,
100                incr_comp_session,
101                // The svh is always produced when incr. comp. is enabled.
102                self.crate_hash.unwrap(),
103            );
104        }
105
106        // The `HostMetadata` offload pass only writes the kernel manifest.
107        // Codegen was already skipped so there are no files to link.
108        if sess
109            .opts
110            .unstable_opts
111            .offload
112            .iter()
113            .any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    config::Offload::HostMetadata(_) => true,
    _ => false,
}matches!(o, config::Offload::HostMetadata(_)))
114        {
115            return;
116        }
117
118        if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe) {
119            return;
120        }
121
122        if sess.opts.unstable_opts.no_link {
123            let rlink_file = self.output_filenames.with_extension(config::RLINK_EXT);
124            CompiledModules::serialize_rlink(
125                sess,
126                &rlink_file,
127                &compiled_modules,
128                &self.crate_info,
129                &self.metadata,
130                &self.output_filenames,
131            )
132            .unwrap_or_else(|error| {
133                sess.dcx().emit_fatal(FailedWritingFile { path: &rlink_file, error })
134            });
135            return;
136        }
137
138        let _timer = sess.prof.verbose_generic_activity("link_crate");
139        let _timing = sess.timings.section_guard(sess.dcx(), TimingSection::Linking);
140        codegen_backend.link(
141            sess,
142            compiled_modules,
143            self.crate_info,
144            self.metadata,
145            &self.output_filenames,
146        )
147    }
148}