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