1 use crate::errors::{FailedWritingFile, RustcErrorFatal, RustcErrorUnexpectedAnnotation};
2 use crate::interface::{Compiler, Result};
3 use crate::passes::{self, BoxedResolver, QueryContext};
6 use rustc_codegen_ssa::traits::CodegenBackend;
7 use rustc_codegen_ssa::CodegenResults;
8 use rustc_data_structures::steal::Steal;
9 use rustc_data_structures::svh::Svh;
10 use rustc_data_structures::sync::{Lrc, OnceCell, WorkerLocal};
11 use rustc_hir::def_id::LOCAL_CRATE;
12 use rustc_incremental::DepGraphFuture;
13 use rustc_lint::LintStore;
14 use rustc_middle::arena::Arena;
15 use rustc_middle::dep_graph::DepGraph;
16 use rustc_middle::ty::{GlobalCtxt, TyCtxt};
17 use rustc_query_impl::Queries as TcxQueries;
18 use rustc_session::config::{self, OutputFilenames, OutputType};
19 use rustc_session::{output::find_crate_name, Session};
20 use rustc_span::symbol::sym;
21 use rustc_span::Symbol;
23 use std::cell::{RefCell, RefMut};
27 /// Represent the result of a query.
29 /// This result can be stolen once with the [`steal`] method and generated with the [`compute`] method.
31 /// [`steal`]: Steal::steal
32 /// [`compute`]: Self::compute
34 /// `None` means no value has been computed yet.
35 result: RefCell<Option<Result<Steal<T>>>>,
39 fn compute<F: FnOnce() -> Result<T>>(&self, f: F) -> Result<QueryResult<'_, T>> {
41 self.result.borrow_mut(),
42 |r: &mut Option<Result<Steal<T>>>| -> Option<&mut Steal<T>> {
43 r.get_or_insert_with(|| f().map(Steal::new)).as_mut().ok()
46 .map_err(|r| *r.as_ref().unwrap().as_ref().map(|_| ()).unwrap_err())
51 pub struct QueryResult<'a, T>(RefMut<'a, Steal<T>>);
53 impl<'a, T> std::ops::Deref for QueryResult<'a, T> {
54 type Target = RefMut<'a, Steal<T>>;
56 fn deref(&self) -> &Self::Target {
61 impl<'a, T> std::ops::DerefMut for QueryResult<'a, T> {
62 fn deref_mut(&mut self) -> &mut Self::Target {
67 impl<'a, 'tcx> QueryResult<'a, QueryContext<'tcx>> {
68 pub fn enter<T>(mut self, f: impl FnOnce(TyCtxt<'tcx>) -> T) -> T {
69 (*self.0).get_mut().enter(f)
73 impl<T> Default for Query<T> {
74 fn default() -> Self {
75 Query { result: RefCell::new(None) }
79 pub struct Queries<'tcx> {
80 compiler: &'tcx Compiler,
81 gcx: OnceCell<GlobalCtxt<'tcx>>,
82 queries: OnceCell<TcxQueries<'tcx>>,
84 arena: WorkerLocal<Arena<'tcx>>,
85 hir_arena: WorkerLocal<rustc_hir::Arena<'tcx>>,
87 dep_graph_future: Query<Option<DepGraphFuture>>,
88 parse: Query<ast::Crate>,
89 crate_name: Query<Symbol>,
90 register_plugins: Query<(ast::Crate, Lrc<LintStore>)>,
91 expansion: Query<(Lrc<ast::Crate>, Rc<RefCell<BoxedResolver>>, Lrc<LintStore>)>,
92 dep_graph: Query<DepGraph>,
93 prepare_outputs: Query<OutputFilenames>,
94 global_ctxt: Query<QueryContext<'tcx>>,
95 ongoing_codegen: Query<Box<dyn Any>>,
98 impl<'tcx> Queries<'tcx> {
99 pub fn new(compiler: &'tcx Compiler) -> Queries<'tcx> {
102 gcx: OnceCell::new(),
103 queries: OnceCell::new(),
104 arena: WorkerLocal::new(|_| Arena::default()),
105 hir_arena: WorkerLocal::new(|_| rustc_hir::Arena::default()),
106 dep_graph_future: Default::default(),
107 parse: Default::default(),
108 crate_name: Default::default(),
109 register_plugins: Default::default(),
110 expansion: Default::default(),
111 dep_graph: Default::default(),
112 prepare_outputs: Default::default(),
113 global_ctxt: Default::default(),
114 ongoing_codegen: Default::default(),
118 fn session(&self) -> &Lrc<Session> {
121 fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
122 self.compiler.codegen_backend()
125 fn dep_graph_future(&self) -> Result<QueryResult<'_, Option<DepGraphFuture>>> {
126 self.dep_graph_future.compute(|| {
127 let sess = self.session();
128 Ok(sess.opts.build_dep_graph().then(|| rustc_incremental::load_dep_graph(sess)))
132 pub fn parse(&self) -> Result<QueryResult<'_, ast::Crate>> {
133 self.parse.compute(|| {
134 passes::parse(self.session(), &self.compiler.input)
135 .map_err(|mut parse_error| parse_error.emit())
139 pub fn register_plugins(&self) -> Result<QueryResult<'_, (ast::Crate, Lrc<LintStore>)>> {
140 self.register_plugins.compute(|| {
141 let crate_name = *self.crate_name()?.borrow();
142 let krate = self.parse()?.steal();
144 let empty: &(dyn Fn(&Session, &mut LintStore) + Sync + Send) = &|_, _| {};
145 let (krate, lint_store) = passes::register_plugins(
147 &*self.codegen_backend().metadata_loader(),
148 self.compiler.register_lints.as_deref().unwrap_or_else(|| empty),
153 // Compute the dependency graph (in the background). We want to do
154 // this as early as possible, to give the DepGraph maximum time to
155 // load before dep_graph() is called, but it also can't happen
156 // until after rustc_incremental::prepare_session_directory() is
157 // called, which happens within passes::register_plugins().
158 self.dep_graph_future().ok();
160 Ok((krate, Lrc::new(lint_store)))
164 pub fn crate_name(&self) -> Result<QueryResult<'_, Symbol>> {
165 self.crate_name.compute(|| {
167 let parse_result = self.parse()?;
168 let krate = parse_result.borrow();
169 // parse `#[crate_name]` even if `--crate-name` was passed, to make sure it matches.
170 find_crate_name(self.session(), &krate.attrs, &self.compiler.input)
177 ) -> Result<QueryResult<'_, (Lrc<ast::Crate>, Rc<RefCell<BoxedResolver>>, Lrc<LintStore>)>>
180 self.expansion.compute(|| {
181 let crate_name = *self.crate_name()?.borrow();
182 let (krate, lint_store) = self.register_plugins()?.steal();
183 let _timer = self.session().timer("configure_and_expand");
184 let sess = self.session();
185 let mut resolver = passes::create_resolver(
187 self.codegen_backend().metadata_loader(),
191 let krate = resolver.access(|resolver| {
192 passes::configure_and_expand(sess, &lint_store, krate, crate_name, resolver)
194 Ok((Lrc::new(krate), Rc::new(RefCell::new(resolver)), lint_store))
198 fn dep_graph(&self) -> Result<QueryResult<'_, DepGraph>> {
199 self.dep_graph.compute(|| {
200 let sess = self.session();
201 let future_opt = self.dep_graph_future()?.steal();
202 let dep_graph = future_opt
204 let (prev_graph, prev_work_products) =
205 sess.time("blocked_on_dep_graph_loading", || future.open().open(sess));
207 rustc_incremental::build_dep_graph(sess, prev_graph, prev_work_products)
209 .unwrap_or_else(DepGraph::new_disabled);
214 pub fn prepare_outputs(&self) -> Result<QueryResult<'_, OutputFilenames>> {
215 self.prepare_outputs.compute(|| {
216 let expansion = self.expansion()?;
217 let (krate, boxed_resolver, _) = &*expansion.borrow();
218 let crate_name = *self.crate_name()?.borrow();
219 passes::prepare_outputs(
229 pub fn global_ctxt(&'tcx self) -> Result<QueryResult<'_, QueryContext<'tcx>>> {
230 self.global_ctxt.compute(|| {
231 let crate_name = *self.crate_name()?.borrow();
232 let outputs = self.prepare_outputs()?.steal();
233 let dep_graph = self.dep_graph()?.borrow().clone();
234 let (krate, resolver, lint_store) = self.expansion()?.steal();
235 Ok(passes::create_global_ctxt(
251 pub fn ongoing_codegen(&'tcx self) -> Result<QueryResult<'_, Box<dyn Any>>> {
252 self.ongoing_codegen.compute(|| {
253 self.global_ctxt()?.enter(|tcx| {
254 tcx.analysis(()).ok();
256 // Don't do code generation if there were any errors
257 self.session().compile_status()?;
259 // If we have any delayed bugs, for example because we created TyKind::Error earlier,
260 // it's likely that codegen will only cause more ICEs, obscuring the original problem
261 self.session().diagnostic().flush_delayed();
263 // Hook for UI tests.
264 Self::check_for_rustc_errors_attr(tcx);
266 Ok(passes::start_codegen(&***self.codegen_backend(), tcx))
271 /// Check for the `#[rustc_error]` annotation, which forces an error in codegen. This is used
272 /// to write UI tests that actually test that compilation succeeds without reporting
274 fn check_for_rustc_errors_attr(tcx: TyCtxt<'_>) {
275 let Some((def_id, _)) = tcx.entry_fn(()) else { return };
276 for attr in tcx.get_attrs(def_id, sym::rustc_error) {
277 match attr.meta_item_list() {
278 // Check if there is a `#[rustc_error(delay_span_bug_from_inside_query)]`.
280 if list.iter().any(|list_item| {
282 list_item.ident().map(|i| i.name),
283 Some(sym::delay_span_bug_from_inside_query)
287 tcx.ensure().trigger_delay_span_bug(def_id);
290 // Bare `#[rustc_error]`.
292 tcx.sess.emit_fatal(RustcErrorFatal { span: tcx.def_span(def_id) });
295 // Some other attribute.
297 tcx.sess.emit_warning(RustcErrorUnexpectedAnnotation {
298 span: tcx.def_span(def_id),
305 pub fn linker(&'tcx self) -> Result<Linker> {
306 let sess = self.session().clone();
307 let codegen_backend = self.codegen_backend().clone();
309 let (crate_hash, prepare_outputs, dep_graph) = self.global_ctxt()?.enter(|tcx| {
310 (tcx.crate_hash(LOCAL_CRATE), tcx.output_filenames(()).clone(), tcx.dep_graph.clone())
312 let ongoing_codegen = self.ongoing_codegen()?.steal();
327 // compilation inputs
329 codegen_backend: Lrc<Box<dyn CodegenBackend>>,
331 // compilation outputs
333 prepare_outputs: Arc<OutputFilenames>,
335 ongoing_codegen: Box<dyn Any>,
339 pub fn link(self) -> Result<()> {
340 let (codegen_results, work_products) = self.codegen_backend.join_codegen(
341 self.ongoing_codegen,
343 &self.prepare_outputs,
346 self.sess.compile_status()?;
348 let sess = &self.sess;
349 let dep_graph = self.dep_graph;
350 sess.time("serialize_work_products", || {
351 rustc_incremental::save_work_product_index(sess, &dep_graph, work_products)
354 let prof = self.sess.prof.clone();
355 prof.generic_activity("drop_dep_graph").run(move || drop(dep_graph));
357 // Now that we won't touch anything in the incremental compilation directory
358 // any more, we can finalize it (which involves renaming it)
359 rustc_incremental::finalize_session_directory(&self.sess, self.crate_hash);
366 .any(|&i| i == OutputType::Exe || i == OutputType::Metadata)
371 if sess.opts.unstable_opts.no_link {
372 let encoded = CodegenResults::serialize_rlink(&codegen_results);
373 let rlink_file = self.prepare_outputs.with_extension(config::RLINK_EXT);
374 std::fs::write(&rlink_file, encoded)
375 .map_err(|error| sess.emit_fatal(FailedWritingFile { path: &rlink_file, error }))?;
379 let _timer = sess.prof.verbose_generic_activity("link_crate");
380 self.codegen_backend.link(&self.sess, codegen_results, &self.prepare_outputs)
385 pub fn enter<F, T>(&self, f: F) -> T
387 F: for<'tcx> FnOnce(&'tcx Queries<'tcx>) -> T,
389 let mut _timer = None;
390 let queries = Queries::new(self);
391 let ret = f(&queries);
393 // NOTE: intentionally does not compute the global context if it hasn't been built yet,
394 // since that likely means there was a parse error.
395 if let Some(Ok(gcx)) = &mut *queries.global_ctxt.result.borrow_mut() {
396 let gcx = gcx.get_mut();
397 // We assume that no queries are run past here. If there are new queries
398 // after this point, they'll show up as "<unknown>" in self-profiling data.
401 queries.session().prof.generic_activity("self_profile_alloc_query_strings");
402 gcx.enter(rustc_query_impl::alloc_self_profile_query_strings);
406 .time("serialize_dep_graph", || gcx.enter(rustc_incremental::save_dep_graph));
409 _timer = Some(self.session().timer("free_global_ctxt"));