]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_interface/src/queries.rs
Auto merge of #104730 - petrochenkov:modchild5, r=cjgillot
[rust.git] / compiler / rustc_interface / src / queries.rs
1 use crate::errors::{FailedWritingFile, RustcErrorFatal, RustcErrorUnexpectedAnnotation};
2 use crate::interface::{Compiler, Result};
3 use crate::passes::{self, BoxedResolver, QueryContext};
4
5 use rustc_ast as ast;
6 use rustc_codegen_ssa::traits::CodegenBackend;
7 use rustc_codegen_ssa::CodegenResults;
8 use rustc_data_structures::svh::Svh;
9 use rustc_data_structures::sync::{Lrc, OnceCell, WorkerLocal};
10 use rustc_hir::def_id::LOCAL_CRATE;
11 use rustc_incremental::DepGraphFuture;
12 use rustc_lint::LintStore;
13 use rustc_middle::arena::Arena;
14 use rustc_middle::dep_graph::DepGraph;
15 use rustc_middle::ty::{GlobalCtxt, TyCtxt};
16 use rustc_query_impl::Queries as TcxQueries;
17 use rustc_session::config::{self, OutputFilenames, OutputType};
18 use rustc_session::{output::find_crate_name, Session};
19 use rustc_span::symbol::sym;
20 use std::any::Any;
21 use std::cell::{Ref, RefCell, RefMut};
22 use std::rc::Rc;
23
24 /// Represent the result of a query.
25 ///
26 /// This result can be stolen with the [`take`] method and generated with the [`compute`] method.
27 ///
28 /// [`take`]: Self::take
29 /// [`compute`]: Self::compute
30 pub struct Query<T> {
31     result: RefCell<Option<Result<T>>>,
32 }
33
34 impl<T> Query<T> {
35     fn compute<F: FnOnce() -> Result<T>>(&self, f: F) -> Result<&Query<T>> {
36         self.result.borrow_mut().get_or_insert_with(f).as_ref().map(|_| self).map_err(|&err| err)
37     }
38
39     /// Takes ownership of the query result. Further attempts to take or peek the query
40     /// result will panic unless it is generated by calling the `compute` method.
41     pub fn take(&self) -> T {
42         self.result.borrow_mut().take().expect("missing query result").unwrap()
43     }
44
45     /// Borrows the query result using the RefCell. Panics if the result is stolen.
46     pub fn peek(&self) -> Ref<'_, T> {
47         Ref::map(self.result.borrow(), |r| {
48             r.as_ref().unwrap().as_ref().expect("missing query result")
49         })
50     }
51
52     /// Mutably borrows the query result using the RefCell. Panics if the result is stolen.
53     pub fn peek_mut(&self) -> RefMut<'_, T> {
54         RefMut::map(self.result.borrow_mut(), |r| {
55             r.as_mut().unwrap().as_mut().expect("missing query result")
56         })
57     }
58 }
59
60 impl<T> Default for Query<T> {
61     fn default() -> Self {
62         Query { result: RefCell::new(None) }
63     }
64 }
65
66 pub struct Queries<'tcx> {
67     compiler: &'tcx Compiler,
68     gcx: OnceCell<GlobalCtxt<'tcx>>,
69     queries: OnceCell<TcxQueries<'tcx>>,
70
71     arena: WorkerLocal<Arena<'tcx>>,
72     hir_arena: WorkerLocal<rustc_hir::Arena<'tcx>>,
73
74     dep_graph_future: Query<Option<DepGraphFuture>>,
75     parse: Query<ast::Crate>,
76     crate_name: Query<String>,
77     register_plugins: Query<(ast::Crate, Lrc<LintStore>)>,
78     expansion: Query<(Lrc<ast::Crate>, Rc<RefCell<BoxedResolver>>, Lrc<LintStore>)>,
79     dep_graph: Query<DepGraph>,
80     prepare_outputs: Query<OutputFilenames>,
81     global_ctxt: Query<QueryContext<'tcx>>,
82     ongoing_codegen: Query<Box<dyn Any>>,
83 }
84
85 impl<'tcx> Queries<'tcx> {
86     pub fn new(compiler: &'tcx Compiler) -> Queries<'tcx> {
87         Queries {
88             compiler,
89             gcx: OnceCell::new(),
90             queries: OnceCell::new(),
91             arena: WorkerLocal::new(|_| Arena::default()),
92             hir_arena: WorkerLocal::new(|_| rustc_hir::Arena::default()),
93             dep_graph_future: Default::default(),
94             parse: Default::default(),
95             crate_name: Default::default(),
96             register_plugins: Default::default(),
97             expansion: Default::default(),
98             dep_graph: Default::default(),
99             prepare_outputs: Default::default(),
100             global_ctxt: Default::default(),
101             ongoing_codegen: Default::default(),
102         }
103     }
104
105     fn session(&self) -> &Lrc<Session> {
106         &self.compiler.sess
107     }
108     fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
109         self.compiler.codegen_backend()
110     }
111
112     fn dep_graph_future(&self) -> Result<&Query<Option<DepGraphFuture>>> {
113         self.dep_graph_future.compute(|| {
114             let sess = self.session();
115             Ok(sess.opts.build_dep_graph().then(|| rustc_incremental::load_dep_graph(sess)))
116         })
117     }
118
119     pub fn parse(&self) -> Result<&Query<ast::Crate>> {
120         self.parse.compute(|| {
121             passes::parse(self.session(), &self.compiler.input)
122                 .map_err(|mut parse_error| parse_error.emit())
123         })
124     }
125
126     pub fn register_plugins(&self) -> Result<&Query<(ast::Crate, Lrc<LintStore>)>> {
127         self.register_plugins.compute(|| {
128             let crate_name = self.crate_name()?.peek().clone();
129             let krate = self.parse()?.take();
130
131             let empty: &(dyn Fn(&Session, &mut LintStore) + Sync + Send) = &|_, _| {};
132             let (krate, lint_store) = passes::register_plugins(
133                 self.session(),
134                 &*self.codegen_backend().metadata_loader(),
135                 self.compiler.register_lints.as_deref().unwrap_or_else(|| empty),
136                 krate,
137                 &crate_name,
138             )?;
139
140             // Compute the dependency graph (in the background). We want to do
141             // this as early as possible, to give the DepGraph maximum time to
142             // load before dep_graph() is called, but it also can't happen
143             // until after rustc_incremental::prepare_session_directory() is
144             // called, which happens within passes::register_plugins().
145             self.dep_graph_future().ok();
146
147             Ok((krate, Lrc::new(lint_store)))
148         })
149     }
150
151     pub fn crate_name(&self) -> Result<&Query<String>> {
152         self.crate_name.compute(|| {
153             Ok({
154                 let parse_result = self.parse()?;
155                 let krate = parse_result.peek();
156                 // parse `#[crate_name]` even if `--crate-name` was passed, to make sure it matches.
157                 find_crate_name(self.session(), &krate.attrs, &self.compiler.input)
158             })
159         })
160     }
161
162     pub fn expansion(
163         &self,
164     ) -> Result<&Query<(Lrc<ast::Crate>, Rc<RefCell<BoxedResolver>>, Lrc<LintStore>)>> {
165         trace!("expansion");
166         self.expansion.compute(|| {
167             let crate_name = self.crate_name()?.peek().clone();
168             let (krate, lint_store) = self.register_plugins()?.take();
169             let _timer = self.session().timer("configure_and_expand");
170             let sess = self.session();
171             let mut resolver = passes::create_resolver(
172                 sess.clone(),
173                 self.codegen_backend().metadata_loader(),
174                 &krate,
175                 &crate_name,
176             );
177             let krate = resolver.access(|resolver| {
178                 passes::configure_and_expand(sess, &lint_store, krate, &crate_name, resolver)
179             })?;
180             Ok((Lrc::new(krate), Rc::new(RefCell::new(resolver)), lint_store))
181         })
182     }
183
184     fn dep_graph(&self) -> Result<&Query<DepGraph>> {
185         self.dep_graph.compute(|| {
186             let sess = self.session();
187             let future_opt = self.dep_graph_future()?.take();
188             let dep_graph = future_opt
189                 .and_then(|future| {
190                     let (prev_graph, prev_work_products) =
191                         sess.time("blocked_on_dep_graph_loading", || future.open().open(sess));
192
193                     rustc_incremental::build_dep_graph(sess, prev_graph, prev_work_products)
194                 })
195                 .unwrap_or_else(DepGraph::new_disabled);
196             Ok(dep_graph)
197         })
198     }
199
200     pub fn prepare_outputs(&self) -> Result<&Query<OutputFilenames>> {
201         self.prepare_outputs.compute(|| {
202             let (krate, boxed_resolver, _) = &*self.expansion()?.peek();
203             let crate_name = self.crate_name()?.peek();
204             passes::prepare_outputs(
205                 self.session(),
206                 self.compiler,
207                 krate,
208                 &*boxed_resolver,
209                 &crate_name,
210             )
211         })
212     }
213
214     pub fn global_ctxt(&'tcx self) -> Result<&Query<QueryContext<'tcx>>> {
215         self.global_ctxt.compute(|| {
216             let crate_name = self.crate_name()?.peek().clone();
217             let outputs = self.prepare_outputs()?.peek().clone();
218             let dep_graph = self.dep_graph()?.peek().clone();
219             let (krate, resolver, lint_store) = self.expansion()?.take();
220             Ok(passes::create_global_ctxt(
221                 self.compiler,
222                 lint_store,
223                 krate,
224                 dep_graph,
225                 resolver,
226                 outputs,
227                 &crate_name,
228                 &self.queries,
229                 &self.gcx,
230                 &self.arena,
231                 &self.hir_arena,
232             ))
233         })
234     }
235
236     pub fn ongoing_codegen(&'tcx self) -> Result<&Query<Box<dyn Any>>> {
237         self.ongoing_codegen.compute(|| {
238             let outputs = self.prepare_outputs()?;
239             self.global_ctxt()?.peek_mut().enter(|tcx| {
240                 tcx.analysis(()).ok();
241
242                 // Don't do code generation if there were any errors
243                 self.session().compile_status()?;
244
245                 // If we have any delayed bugs, for example because we created TyKind::Error earlier,
246                 // it's likely that codegen will only cause more ICEs, obscuring the original problem
247                 self.session().diagnostic().flush_delayed();
248
249                 // Hook for UI tests.
250                 Self::check_for_rustc_errors_attr(tcx);
251
252                 Ok(passes::start_codegen(&***self.codegen_backend(), tcx, &*outputs.peek()))
253             })
254         })
255     }
256
257     /// Check for the `#[rustc_error]` annotation, which forces an error in codegen. This is used
258     /// to write UI tests that actually test that compilation succeeds without reporting
259     /// an error.
260     fn check_for_rustc_errors_attr(tcx: TyCtxt<'_>) {
261         let Some((def_id, _)) = tcx.entry_fn(()) else { return };
262         for attr in tcx.get_attrs(def_id, sym::rustc_error) {
263             match attr.meta_item_list() {
264                 // Check if there is a `#[rustc_error(delay_span_bug_from_inside_query)]`.
265                 Some(list)
266                     if list.iter().any(|list_item| {
267                         matches!(
268                             list_item.ident().map(|i| i.name),
269                             Some(sym::delay_span_bug_from_inside_query)
270                         )
271                     }) =>
272                 {
273                     tcx.ensure().trigger_delay_span_bug(def_id);
274                 }
275
276                 // Bare `#[rustc_error]`.
277                 None => {
278                     tcx.sess.emit_fatal(RustcErrorFatal { span: tcx.def_span(def_id) });
279                 }
280
281                 // Some other attribute.
282                 Some(_) => {
283                     tcx.sess.emit_warning(RustcErrorUnexpectedAnnotation {
284                         span: tcx.def_span(def_id),
285                     });
286                 }
287             }
288         }
289     }
290
291     pub fn linker(&'tcx self) -> Result<Linker> {
292         let sess = self.session().clone();
293         let codegen_backend = self.codegen_backend().clone();
294
295         let dep_graph = self.dep_graph()?.peek().clone();
296         let prepare_outputs = self.prepare_outputs()?.take();
297         let crate_hash = self.global_ctxt()?.peek_mut().enter(|tcx| tcx.crate_hash(LOCAL_CRATE));
298         let ongoing_codegen = self.ongoing_codegen()?.take();
299
300         Ok(Linker {
301             sess,
302             codegen_backend,
303
304             dep_graph,
305             prepare_outputs,
306             crate_hash,
307             ongoing_codegen,
308         })
309     }
310 }
311
312 pub struct Linker {
313     // compilation inputs
314     sess: Lrc<Session>,
315     codegen_backend: Lrc<Box<dyn CodegenBackend>>,
316
317     // compilation outputs
318     dep_graph: DepGraph,
319     prepare_outputs: OutputFilenames,
320     crate_hash: Svh,
321     ongoing_codegen: Box<dyn Any>,
322 }
323
324 impl Linker {
325     pub fn link(self) -> Result<()> {
326         let (codegen_results, work_products) = self.codegen_backend.join_codegen(
327             self.ongoing_codegen,
328             &self.sess,
329             &self.prepare_outputs,
330         )?;
331
332         self.sess.compile_status()?;
333
334         let sess = &self.sess;
335         let dep_graph = self.dep_graph;
336         sess.time("serialize_work_products", || {
337             rustc_incremental::save_work_product_index(sess, &dep_graph, work_products)
338         });
339
340         let prof = self.sess.prof.clone();
341         prof.generic_activity("drop_dep_graph").run(move || drop(dep_graph));
342
343         // Now that we won't touch anything in the incremental compilation directory
344         // any more, we can finalize it (which involves renaming it)
345         rustc_incremental::finalize_session_directory(&self.sess, self.crate_hash);
346
347         if !self
348             .sess
349             .opts
350             .output_types
351             .keys()
352             .any(|&i| i == OutputType::Exe || i == OutputType::Metadata)
353         {
354             return Ok(());
355         }
356
357         if sess.opts.unstable_opts.no_link {
358             let encoded = CodegenResults::serialize_rlink(&codegen_results);
359             let rlink_file = self.prepare_outputs.with_extension(config::RLINK_EXT);
360             std::fs::write(&rlink_file, encoded)
361                 .map_err(|error| sess.emit_fatal(FailedWritingFile { path: &rlink_file, error }))?;
362             return Ok(());
363         }
364
365         let _timer = sess.prof.verbose_generic_activity("link_crate");
366         self.codegen_backend.link(&self.sess, codegen_results, &self.prepare_outputs)
367     }
368 }
369
370 impl Compiler {
371     pub fn enter<F, T>(&self, f: F) -> T
372     where
373         F: for<'tcx> FnOnce(&'tcx Queries<'tcx>) -> T,
374     {
375         let mut _timer = None;
376         let queries = Queries::new(self);
377         let ret = f(&queries);
378
379         // NOTE: intentionally does not compute the global context if it hasn't been built yet,
380         // since that likely means there was a parse error.
381         if let Some(Ok(gcx)) = &mut *queries.global_ctxt.result.borrow_mut() {
382             // We assume that no queries are run past here. If there are new queries
383             // after this point, they'll show up as "<unknown>" in self-profiling data.
384             {
385                 let _prof_timer =
386                     queries.session().prof.generic_activity("self_profile_alloc_query_strings");
387                 gcx.enter(rustc_query_impl::alloc_self_profile_query_strings);
388             }
389
390             self.session()
391                 .time("serialize_dep_graph", || gcx.enter(rustc_incremental::save_dep_graph));
392         }
393
394         _timer = Some(self.session().timer("free_global_ctxt"));
395
396         ret
397     }
398 }