1 use crate::interface
::{Compiler, Result}
;
2 use crate::passes
::{self, BoxedResolver, QueryContext}
;
5 use rustc_codegen_ssa
::traits
::CodegenBackend
;
6 use rustc_data_structures
::sync
::{Lrc, OnceCell, WorkerLocal}
;
7 use rustc_errors
::ErrorReported
;
8 use rustc_hir
::def_id
::LOCAL_CRATE
;
10 use rustc_incremental
::DepGraphFuture
;
11 use rustc_lint
::LintStore
;
12 use rustc_middle
::arena
::Arena
;
13 use rustc_middle
::dep_graph
::DepGraph
;
14 use rustc_middle
::ty
::steal
::Steal
;
15 use rustc_middle
::ty
::{GlobalCtxt, ResolverOutputs, TyCtxt}
;
16 use rustc_session
::config
::{OutputFilenames, OutputType}
;
17 use rustc_session
::{output::find_crate_name, Session}
;
18 use rustc_span
::symbol
::sym
;
20 use std
::cell
::{Ref, RefCell, RefMut}
;
23 /// Represent the result of a query.
24 /// This result can be stolen with the `take` method and generated with the `compute` method.
26 result
: RefCell
<Option
<Result
<T
>>>,
30 fn compute
<F
: FnOnce() -> Result
<T
>>(&self, f
: F
) -> Result
<&Query
<T
>> {
31 let mut result
= self.result
.borrow_mut();
35 result
.as_ref().unwrap().as_ref().map(|_
| self).map_err(|err
| *err
)
38 /// Takes ownership of the query result. Further attempts to take or peek the query
39 /// result will panic unless it is generated by calling the `compute` method.
40 pub fn take(&self) -> T
{
41 self.result
.borrow_mut().take().expect("missing query result").unwrap()
44 /// Borrows the query result using the RefCell. Panics if the result is stolen.
45 pub fn peek(&self) -> Ref
<'_
, T
> {
46 Ref
::map(self.result
.borrow(), |r
| {
47 r
.as_ref().unwrap().as_ref().expect("missing query result")
51 /// Mutably borrows the query result using the RefCell. Panics if the result is stolen.
52 pub fn peek_mut(&self) -> RefMut
<'_
, T
> {
53 RefMut
::map(self.result
.borrow_mut(), |r
| {
54 r
.as_mut().unwrap().as_mut().expect("missing query result")
59 impl<T
> Default
for Query
<T
> {
60 fn default() -> Self {
61 Query { result: RefCell::new(None) }
65 pub struct Queries
<'tcx
> {
66 compiler
: &'tcx Compiler
,
67 gcx
: OnceCell
<GlobalCtxt
<'tcx
>>,
69 arena
: WorkerLocal
<Arena
<'tcx
>>,
70 hir_arena
: WorkerLocal
<rustc_ast_lowering
::Arena
<'tcx
>>,
72 dep_graph_future
: Query
<Option
<DepGraphFuture
>>,
73 parse
: Query
<ast
::Crate
>,
74 crate_name
: Query
<String
>,
75 register_plugins
: Query
<(ast
::Crate
, Lrc
<LintStore
>)>,
76 expansion
: Query
<(ast
::Crate
, Steal
<Rc
<RefCell
<BoxedResolver
>>>, Lrc
<LintStore
>)>,
77 dep_graph
: Query
<DepGraph
>,
78 lower_to_hir
: Query
<(&'tcx Crate
<'tcx
>, Steal
<ResolverOutputs
>)>,
79 prepare_outputs
: Query
<OutputFilenames
>,
80 global_ctxt
: Query
<QueryContext
<'tcx
>>,
81 ongoing_codegen
: Query
<Box
<dyn Any
>>,
84 impl<'tcx
> Queries
<'tcx
> {
85 pub fn new(compiler
: &'tcx Compiler
) -> Queries
<'tcx
> {
89 arena
: WorkerLocal
::new(|_
| Arena
::default()),
90 hir_arena
: WorkerLocal
::new(|_
| rustc_ast_lowering
::Arena
::default()),
91 dep_graph_future
: Default
::default(),
92 parse
: Default
::default(),
93 crate_name
: Default
::default(),
94 register_plugins
: Default
::default(),
95 expansion
: Default
::default(),
96 dep_graph
: Default
::default(),
97 lower_to_hir
: Default
::default(),
98 prepare_outputs
: Default
::default(),
99 global_ctxt
: Default
::default(),
100 ongoing_codegen
: Default
::default(),
104 fn session(&self) -> &Lrc
<Session
> {
107 fn codegen_backend(&self) -> &Lrc
<Box
<dyn CodegenBackend
>> {
108 &self.compiler
.codegen_backend()
111 pub fn dep_graph_future(&self) -> Result
<&Query
<Option
<DepGraphFuture
>>> {
112 self.dep_graph_future
.compute(|| {
117 .then(|| rustc_incremental
::load_dep_graph(self.session())))
121 pub fn parse(&self) -> Result
<&Query
<ast
::Crate
>> {
122 self.parse
.compute(|| {
123 passes
::parse(self.session(), &self.compiler
.input
).map_err(|mut parse_error
| {
130 pub fn register_plugins(&self) -> Result
<&Query
<(ast
::Crate
, Lrc
<LintStore
>)>> {
131 self.register_plugins
.compute(|| {
132 let crate_name
= self.crate_name()?
.peek().clone();
133 let krate
= self.parse()?
.take();
135 let empty
: &(dyn Fn(&Session
, &mut LintStore
) + Sync
+ Send
) = &|_
, _
| {}
;
136 let result
= passes
::register_plugins(
138 &*self.codegen_backend().metadata_loader(),
139 self.compiler
.register_lints
.as_deref().unwrap_or_else(|| empty
),
144 // Compute the dependency graph (in the background). We want to do
145 // this as early as possible, to give the DepGraph maximum time to
146 // load before dep_graph() is called, but it also can't happen
147 // until after rustc_incremental::prepare_session_directory() is
148 // called, which happens within passes::register_plugins().
149 self.dep_graph_future().ok();
155 pub fn crate_name(&self) -> Result
<&Query
<String
>> {
156 self.crate_name
.compute(|| {
157 Ok(match self.compiler
.crate_name
{
158 Some(ref crate_name
) => crate_name
.clone(),
160 let parse_result
= self.parse()?
;
161 let krate
= parse_result
.peek();
162 find_crate_name(self.session(), &krate
.attrs
, &self.compiler
.input
)
170 ) -> Result
<&Query
<(ast
::Crate
, Steal
<Rc
<RefCell
<BoxedResolver
>>>, Lrc
<LintStore
>)>> {
171 tracing
::trace
!("expansion");
172 self.expansion
.compute(|| {
173 let crate_name
= self.crate_name()?
.peek().clone();
174 let (krate
, lint_store
) = self.register_plugins()?
.take();
175 let _timer
= self.session().timer("configure_and_expand");
176 passes
::configure_and_expand(
177 self.session().clone(),
179 self.codegen_backend().metadata_loader(),
183 .map(|(krate
, resolver
)| {
184 (krate
, Steal
::new(Rc
::new(RefCell
::new(resolver
))), lint_store
)
189 pub fn dep_graph(&self) -> Result
<&Query
<DepGraph
>> {
190 self.dep_graph
.compute(|| {
191 Ok(match self.dep_graph_future()?
.take() {
192 None
=> DepGraph
::new_disabled(),
194 let (prev_graph
, prev_work_products
) =
195 self.session().time("blocked_on_dep_graph_loading", || {
198 .unwrap_or_else(|e
| rustc_incremental
::LoadResult
::Error
{
199 message
: format
!("could not decode incremental cache: {:?}", e
),
201 .open(self.session())
203 DepGraph
::new(prev_graph
, prev_work_products
)
209 pub fn lower_to_hir(&'tcx
self) -> Result
<&Query
<(&'tcx Crate
<'tcx
>, Steal
<ResolverOutputs
>)>> {
210 self.lower_to_hir
.compute(|| {
211 let expansion_result
= self.expansion()?
;
212 let peeked
= expansion_result
.peek();
213 let krate
= &peeked
.0;
214 let resolver
= peeked
.1.steal();
215 let lint_store
= &peeked
.2;
216 let hir
= resolver
.borrow_mut().access(|resolver
| {
217 Ok(passes
::lower_to_hir(
221 &*self.dep_graph()?
.peek(),
226 let hir
= self.hir_arena
.alloc(hir
);
227 Ok((hir
, Steal
::new(BoxedResolver
::to_resolver_outputs(resolver
))))
231 pub fn prepare_outputs(&self) -> Result
<&Query
<OutputFilenames
>> {
232 self.prepare_outputs
.compute(|| {
233 let expansion_result
= self.expansion()?
;
234 let (krate
, boxed_resolver
, _
) = &*expansion_result
.peek();
235 let crate_name
= self.crate_name()?
;
236 let crate_name
= crate_name
.peek();
237 passes
::prepare_outputs(
247 pub fn global_ctxt(&'tcx
self) -> Result
<&Query
<QueryContext
<'tcx
>>> {
248 self.global_ctxt
.compute(|| {
249 let crate_name
= self.crate_name()?
.peek().clone();
250 let outputs
= self.prepare_outputs()?
.peek().clone();
251 let lint_store
= self.expansion()?
.peek().2.clone();
252 let hir
= self.lower_to_hir()?
.peek();
253 let dep_graph
= self.dep_graph()?
.peek().clone();
254 let (ref krate
, ref resolver_outputs
) = &*hir
;
255 let _timer
= self.session().timer("create_global_ctxt");
256 Ok(passes
::create_global_ctxt(
261 resolver_outputs
.steal(),
270 pub fn ongoing_codegen(&'tcx
self) -> Result
<&Query
<Box
<dyn Any
>>> {
271 self.ongoing_codegen
.compute(|| {
272 let outputs
= self.prepare_outputs()?
;
273 self.global_ctxt()?
.peek_mut().enter(|tcx
| {
274 tcx
.analysis(LOCAL_CRATE
).ok();
276 // Don't do code generation if there were any errors
277 self.session().compile_status()?
;
279 // Hook for compile-fail tests.
280 Self::check_for_rustc_errors_attr(tcx
);
282 Ok(passes
::start_codegen(&***self.codegen_backend(), tcx
, &*outputs
.peek()))
287 /// Check for the `#[rustc_error]` annotation, which forces an error in codegen. This is used
288 /// to write compile-fail tests that actually test that compilation succeeds without reporting
290 fn check_for_rustc_errors_attr(tcx
: TyCtxt
<'_
>) {
291 let def_id
= match tcx
.entry_fn(LOCAL_CRATE
) {
292 Some((def_id
, _
)) => def_id
,
296 let attrs
= &*tcx
.get_attrs(def_id
.to_def_id());
297 let attrs
= attrs
.iter().filter(|attr
| tcx
.sess
.check_name(attr
, sym
::rustc_error
));
299 match attr
.meta_item_list() {
300 // Check if there is a `#[rustc_error(delay_span_bug_from_inside_query)]`.
302 if list
.iter().any(|list_item
| {
304 list_item
.ident().map(|i
| i
.name
),
305 Some(sym
::delay_span_bug_from_inside_query
)
309 tcx
.ensure().trigger_delay_span_bug(def_id
);
312 // Bare `#[rustc_error]`.
315 tcx
.def_span(def_id
),
316 "fatal error triggered by #[rustc_error]",
320 // Some other attribute.
323 tcx
.def_span(def_id
),
324 "unexpected annotation used with `#[rustc_error(...)]!",
331 pub fn linker(&'tcx
self) -> Result
<Linker
> {
332 let dep_graph
= self.dep_graph()?
;
333 let prepare_outputs
= self.prepare_outputs()?
;
334 let ongoing_codegen
= self.ongoing_codegen()?
;
336 let sess
= self.session().clone();
337 let codegen_backend
= self.codegen_backend().clone();
341 dep_graph
: dep_graph
.peek().clone(),
342 prepare_outputs
: prepare_outputs
.take(),
343 ongoing_codegen
: ongoing_codegen
.take(),
352 prepare_outputs
: OutputFilenames
,
353 ongoing_codegen
: Box
<dyn Any
>,
354 codegen_backend
: Lrc
<Box
<dyn CodegenBackend
>>,
358 pub fn link(self) -> Result
<()> {
359 let codegen_results
=
360 self.codegen_backend
.join_codegen(self.ongoing_codegen
, &self.sess
, &self.dep_graph
)?
;
361 let prof
= self.sess
.prof
.clone();
362 let dep_graph
= self.dep_graph
;
363 prof
.generic_activity("drop_dep_graph").run(move || drop(dep_graph
));
370 .any(|&i
| i
== OutputType
::Exe
|| i
== OutputType
::Metadata
)
374 self.codegen_backend
.link(&self.sess
, codegen_results
, &self.prepare_outputs
)
379 pub fn enter
<F
, T
>(&self, f
: F
) -> T
381 F
: for<'tcx
> FnOnce(&'tcx Queries
<'tcx
>) -> T
,
383 let mut _timer
= None
;
384 let queries
= Queries
::new(&self);
385 let ret
= f(&queries
);
387 if self.session().opts
.debugging_opts
.query_stats
{
388 if let Ok(gcx
) = queries
.global_ctxt() {
389 gcx
.peek_mut().print_stats();
393 _timer
= Some(self.session().timer("free_global_ctxt"));