]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_query_impl/src/plumbing.rs
Rollup merge of #97511 - jyn514:faster-cargo-build, r=Mark-Simulacrum
[rust.git] / compiler / rustc_query_impl / src / plumbing.rs
1 //! The implementation of the query system itself. This defines the macros that
2 //! generate the actual methods on tcx which find and execute the provider,
3 //! manage the caches, and so forth.
4
5 use crate::{on_disk_cache, Queries};
6 use rustc_middle::dep_graph::{DepNodeIndex, SerializedDepNodeIndex};
7 use rustc_middle::ty::tls::{self, ImplicitCtxt};
8 use rustc_middle::ty::TyCtxt;
9 use rustc_query_system::dep_graph::HasDepContext;
10 use rustc_query_system::query::{QueryContext, QueryJobId, QueryMap, QuerySideEffects};
11
12 use rustc_data_structures::sync::Lock;
13 use rustc_data_structures::thin_vec::ThinVec;
14 use rustc_errors::{Diagnostic, Handler};
15
16 use std::any::Any;
17 use std::num::NonZeroU64;
18
19 #[derive(Copy, Clone)]
20 pub struct QueryCtxt<'tcx> {
21     pub tcx: TyCtxt<'tcx>,
22     pub queries: &'tcx Queries<'tcx>,
23 }
24
25 impl<'tcx> std::ops::Deref for QueryCtxt<'tcx> {
26     type Target = TyCtxt<'tcx>;
27
28     #[inline]
29     fn deref(&self) -> &Self::Target {
30         &self.tcx
31     }
32 }
33
34 impl<'tcx> HasDepContext for QueryCtxt<'tcx> {
35     type DepKind = rustc_middle::dep_graph::DepKind;
36     type DepContext = TyCtxt<'tcx>;
37
38     #[inline]
39     fn dep_context(&self) -> &Self::DepContext {
40         &self.tcx
41     }
42 }
43
44 impl QueryContext for QueryCtxt<'_> {
45     fn next_job_id(&self) -> QueryJobId {
46         QueryJobId(
47             NonZeroU64::new(
48                 self.queries.jobs.fetch_add(1, rustc_data_structures::sync::Ordering::Relaxed),
49             )
50             .unwrap(),
51         )
52     }
53
54     fn current_query_job(&self) -> Option<QueryJobId> {
55         tls::with_related_context(**self, |icx| icx.query)
56     }
57
58     fn try_collect_active_jobs(&self) -> Option<QueryMap> {
59         self.queries.try_collect_active_jobs(**self)
60     }
61
62     // Interactions with on_disk_cache
63     fn load_side_effects(&self, prev_dep_node_index: SerializedDepNodeIndex) -> QuerySideEffects {
64         self.queries
65             .on_disk_cache
66             .as_ref()
67             .map(|c| c.load_side_effects(**self, prev_dep_node_index))
68             .unwrap_or_default()
69     }
70
71     fn store_side_effects(&self, dep_node_index: DepNodeIndex, side_effects: QuerySideEffects) {
72         if let Some(c) = self.queries.on_disk_cache.as_ref() {
73             c.store_side_effects(dep_node_index, side_effects)
74         }
75     }
76
77     fn store_side_effects_for_anon_node(
78         &self,
79         dep_node_index: DepNodeIndex,
80         side_effects: QuerySideEffects,
81     ) {
82         if let Some(c) = self.queries.on_disk_cache.as_ref() {
83             c.store_side_effects_for_anon_node(dep_node_index, side_effects)
84         }
85     }
86
87     /// Executes a job by changing the `ImplicitCtxt` to point to the
88     /// new query job while it executes. It returns the diagnostics
89     /// captured during execution and the actual result.
90     #[inline(always)]
91     fn start_query<R>(
92         &self,
93         token: QueryJobId,
94         diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
95         compute: impl FnOnce() -> R,
96     ) -> R {
97         // The `TyCtxt` stored in TLS has the same global interner lifetime
98         // as `self`, so we use `with_related_context` to relate the 'tcx lifetimes
99         // when accessing the `ImplicitCtxt`.
100         tls::with_related_context(**self, move |current_icx| {
101             // Update the `ImplicitCtxt` to point to our new query job.
102             let new_icx = ImplicitCtxt {
103                 tcx: **self,
104                 query: Some(token),
105                 diagnostics,
106                 layout_depth: current_icx.layout_depth,
107                 task_deps: current_icx.task_deps,
108             };
109
110             // Use the `ImplicitCtxt` while we execute the query.
111             tls::enter_context(&new_icx, |_| {
112                 rustc_data_structures::stack::ensure_sufficient_stack(compute)
113             })
114         })
115     }
116 }
117
118 impl<'tcx> QueryCtxt<'tcx> {
119     #[inline]
120     pub fn from_tcx(tcx: TyCtxt<'tcx>) -> Self {
121         let queries = tcx.queries.as_any();
122         let queries = unsafe {
123             let queries = std::mem::transmute::<&dyn Any, &dyn Any>(queries);
124             let queries = queries.downcast_ref().unwrap();
125             let queries = std::mem::transmute::<&Queries<'_>, &Queries<'_>>(queries);
126             queries
127         };
128         QueryCtxt { tcx, queries }
129     }
130
131     pub(crate) fn on_disk_cache(self) -> Option<&'tcx on_disk_cache::OnDiskCache<'tcx>> {
132         self.queries.on_disk_cache.as_ref()
133     }
134
135     #[cfg(parallel_compiler)]
136     pub unsafe fn deadlock(self, registry: &rustc_rayon_core::Registry) {
137         rustc_query_system::query::deadlock(self, registry)
138     }
139
140     pub(super) fn encode_query_results(
141         self,
142         encoder: &mut on_disk_cache::CacheEncoder<'_, 'tcx>,
143         query_result_index: &mut on_disk_cache::EncodedDepNodeIndex,
144     ) {
145         macro_rules! encode_queries {
146             ($($query:ident,)*) => {
147                 $(
148                     on_disk_cache::encode_query_results::<_, super::queries::$query<'_>>(
149                         self,
150                         encoder,
151                         query_result_index
152                     );
153                 )*
154             }
155         }
156
157         rustc_cached_queries!(encode_queries!);
158     }
159
160     pub fn try_print_query_stack(
161         self,
162         query: Option<QueryJobId>,
163         handler: &Handler,
164         num_frames: Option<usize>,
165     ) -> usize {
166         rustc_query_system::query::print_query_stack(self, query, handler, num_frames)
167     }
168 }
169
170 macro_rules! handle_cycle_error {
171     ([][$tcx: expr, $error:expr]) => {{
172         $error.emit();
173         Value::from_cycle_error($tcx)
174     }};
175     ([(fatal_cycle) $($rest:tt)*][$tcx:expr, $error:expr]) => {{
176         $error.emit();
177         $tcx.sess.abort_if_errors();
178         unreachable!()
179     }};
180     ([(cycle_delay_bug) $($rest:tt)*][$tcx:expr, $error:expr]) => {{
181         $error.delay_as_bug();
182         Value::from_cycle_error($tcx)
183     }};
184     ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
185         handle_cycle_error!([$($modifiers)*][$($args)*])
186     };
187 }
188
189 macro_rules! is_anon {
190     ([]) => {{
191         false
192     }};
193     ([(anon) $($rest:tt)*]) => {{
194         true
195     }};
196     ([$other:tt $($modifiers:tt)*]) => {
197         is_anon!([$($modifiers)*])
198     };
199 }
200
201 macro_rules! is_eval_always {
202     ([]) => {{
203         false
204     }};
205     ([(eval_always) $($rest:tt)*]) => {{
206         true
207     }};
208     ([$other:tt $($modifiers:tt)*]) => {
209         is_eval_always!([$($modifiers)*])
210     };
211 }
212
213 macro_rules! hash_result {
214     ([]) => {{
215         Some(dep_graph::hash_result)
216     }};
217     ([(no_hash) $($rest:tt)*]) => {{
218         None
219     }};
220     ([$other:tt $($modifiers:tt)*]) => {
221         hash_result!([$($modifiers)*])
222     };
223 }
224
225 macro_rules! get_provider {
226     ([][$tcx:expr, $name:ident, $key:expr]) => {{
227         $tcx.queries.local_providers.$name
228     }};
229     ([(separate_provide_extern) $($rest:tt)*][$tcx:expr, $name:ident, $key:expr]) => {{
230         if $key.query_crate_is_local() {
231             $tcx.queries.local_providers.$name
232         } else {
233             $tcx.queries.extern_providers.$name
234         }
235     }};
236     ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
237         get_provider!([$($modifiers)*][$($args)*])
238     };
239 }
240
241 macro_rules! opt_remap_env_constness {
242     ([][$name:ident]) => {};
243     ([(remap_env_constness) $($rest:tt)*][$name:ident]) => {
244         let $name = $name.without_const();
245     };
246     ([$other:tt $($modifiers:tt)*][$name:ident]) => {
247         opt_remap_env_constness!([$($modifiers)*][$name])
248     };
249 }
250
251 macro_rules! define_queries {
252     (<$tcx:tt>
253      $($(#[$attr:meta])*
254         [$($modifiers:tt)*] fn $name:ident($($K:tt)*) -> $V:ty,)*) => {
255
256         define_queries_struct! {
257             tcx: $tcx,
258             input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
259         }
260
261         mod make_query {
262             use super::*;
263
264             // Create an eponymous constructor for each query.
265             $(#[allow(nonstandard_style)] $(#[$attr])*
266             pub fn $name<$tcx>(tcx: QueryCtxt<$tcx>, key: query_keys::$name<$tcx>) -> QueryStackFrame {
267                 opt_remap_env_constness!([$($modifiers)*][key]);
268                 let kind = dep_graph::DepKind::$name;
269                 let name = stringify!($name);
270                 // Disable visible paths printing for performance reasons.
271                 // Showing visible path instead of any path is not that important in production.
272                 let description = ty::print::with_no_visible_paths!(
273                     // Force filename-line mode to avoid invoking `type_of` query.
274                     ty::print::with_forced_impl_filename_line!(
275                         queries::$name::describe(tcx, key)
276                     )
277                 );
278                 let description = if tcx.sess.verbose() {
279                     format!("{} [{}]", description, name)
280                 } else {
281                     description
282                 };
283                 let span = if kind == dep_graph::DepKind::def_span {
284                     // The `def_span` query is used to calculate `default_span`,
285                     // so exit to avoid infinite recursion.
286                     None
287                 } else {
288                     Some(key.default_span(*tcx))
289                 };
290                 // Use `tcx.hir().opt_def_kind()` to reduce the chance of
291                 // accidentally triggering an infinite query loop.
292                 let def_kind = key.key_as_def_id()
293                     .and_then(|def_id| def_id.as_local())
294                     .and_then(|def_id| tcx.hir().opt_def_kind(def_id));
295                 let hash = || {
296                     let mut hcx = tcx.create_stable_hashing_context();
297                     let mut hasher = StableHasher::new();
298                     std::mem::discriminant(&kind).hash_stable(&mut hcx, &mut hasher);
299                     key.hash_stable(&mut hcx, &mut hasher);
300                     hasher.finish::<u64>()
301                 };
302
303                 QueryStackFrame::new(name, description, span, def_kind, hash)
304             })*
305         }
306
307         #[allow(nonstandard_style)]
308         mod queries {
309             use std::marker::PhantomData;
310
311             $(pub struct $name<$tcx> {
312                 data: PhantomData<&$tcx ()>
313             })*
314         }
315
316         $(impl<$tcx> QueryConfig for queries::$name<$tcx> {
317             type Key = query_keys::$name<$tcx>;
318             type Value = query_values::$name<$tcx>;
319             type Stored = query_stored::$name<$tcx>;
320             const NAME: &'static str = stringify!($name);
321         }
322
323         impl<$tcx> QueryDescription<QueryCtxt<$tcx>> for queries::$name<$tcx> {
324             rustc_query_description! { $name<$tcx> }
325
326             type Cache = query_storage::$name<$tcx>;
327
328             #[inline(always)]
329             fn query_state<'a>(tcx: QueryCtxt<$tcx>) -> &'a QueryState<Self::Key>
330                 where QueryCtxt<$tcx>: 'a
331             {
332                 &tcx.queries.$name
333             }
334
335             #[inline(always)]
336             fn query_cache<'a>(tcx: QueryCtxt<$tcx>) -> &'a Self::Cache
337                 where 'tcx:'a
338             {
339                 &tcx.query_caches.$name
340             }
341
342             #[inline]
343             fn make_vtable(tcx: QueryCtxt<'tcx>, key: &Self::Key) ->
344                 QueryVtable<QueryCtxt<$tcx>, Self::Key, Self::Value>
345             {
346                 let compute = get_provider!([$($modifiers)*][tcx, $name, key]);
347                 let cache_on_disk = Self::cache_on_disk(tcx.tcx, key);
348                 QueryVtable {
349                     anon: is_anon!([$($modifiers)*]),
350                     eval_always: is_eval_always!([$($modifiers)*]),
351                     dep_kind: dep_graph::DepKind::$name,
352                     hash_result: hash_result!([$($modifiers)*]),
353                     handle_cycle_error: |tcx, mut error| handle_cycle_error!([$($modifiers)*][tcx, error]),
354                     compute,
355                     cache_on_disk,
356                     try_load_from_disk: Self::TRY_LOAD_FROM_DISK,
357                 }
358             }
359         })*
360
361         #[allow(nonstandard_style)]
362         mod query_callbacks {
363             use super::*;
364             use rustc_middle::dep_graph::DepNode;
365             use rustc_middle::ty::query::query_keys;
366             use rustc_query_system::dep_graph::DepNodeParams;
367             use rustc_query_system::query::{force_query, QueryDescription};
368             use rustc_query_system::dep_graph::FingerprintStyle;
369
370             // We use this for most things when incr. comp. is turned off.
371             pub fn Null() -> DepKindStruct {
372                 DepKindStruct {
373                     is_anon: false,
374                     is_eval_always: false,
375                     fingerprint_style: FingerprintStyle::Unit,
376                     force_from_dep_node: Some(|_, dep_node| bug!("force_from_dep_node: encountered {:?}", dep_node)),
377                     try_load_from_on_disk_cache: None,
378                 }
379             }
380
381             pub fn TraitSelect() -> DepKindStruct {
382                 DepKindStruct {
383                     is_anon: true,
384                     is_eval_always: false,
385                     fingerprint_style: FingerprintStyle::Unit,
386                     force_from_dep_node: None,
387                     try_load_from_on_disk_cache: None,
388                 }
389             }
390
391             pub fn CompileCodegenUnit() -> DepKindStruct {
392                 DepKindStruct {
393                     is_anon: false,
394                     is_eval_always: false,
395                     fingerprint_style: FingerprintStyle::Opaque,
396                     force_from_dep_node: None,
397                     try_load_from_on_disk_cache: None,
398                 }
399             }
400
401             pub fn CompileMonoItem() -> DepKindStruct {
402                 DepKindStruct {
403                     is_anon: false,
404                     is_eval_always: false,
405                     fingerprint_style: FingerprintStyle::Opaque,
406                     force_from_dep_node: None,
407                     try_load_from_on_disk_cache: None,
408                 }
409             }
410
411             $(pub(crate) fn $name()-> DepKindStruct {
412                 let is_anon = is_anon!([$($modifiers)*]);
413                 let is_eval_always = is_eval_always!([$($modifiers)*]);
414
415                 let fingerprint_style =
416                     <query_keys::$name<'_> as DepNodeParams<TyCtxt<'_>>>::fingerprint_style();
417
418                 if is_anon || !fingerprint_style.reconstructible() {
419                     return DepKindStruct {
420                         is_anon,
421                         is_eval_always,
422                         fingerprint_style,
423                         force_from_dep_node: None,
424                         try_load_from_on_disk_cache: None,
425                     }
426                 }
427
428                 #[inline(always)]
429                 fn recover<'tcx>(tcx: TyCtxt<'tcx>, dep_node: DepNode) -> Option<query_keys::$name<'tcx>> {
430                     <query_keys::$name<'_> as DepNodeParams<TyCtxt<'_>>>::recover(tcx, &dep_node)
431                 }
432
433                 fn force_from_dep_node(tcx: TyCtxt<'_>, dep_node: DepNode) -> bool {
434                     if let Some(key) = recover(tcx, dep_node) {
435                         #[cfg(debug_assertions)]
436                         let _guard = tracing::span!(tracing::Level::TRACE, stringify!($name), ?key).entered();
437                         let tcx = QueryCtxt::from_tcx(tcx);
438                         force_query::<queries::$name<'_>, _>(tcx, key, dep_node);
439                         true
440                     } else {
441                         false
442                     }
443                 }
444
445                 fn try_load_from_on_disk_cache(tcx: TyCtxt<'_>, dep_node: DepNode) {
446                     debug_assert!(tcx.dep_graph.is_green(&dep_node));
447
448                     let key = recover(tcx, dep_node).unwrap_or_else(|| panic!("Failed to recover key for {:?} with hash {}", dep_node, dep_node.hash));
449                     if queries::$name::cache_on_disk(tcx, &key) {
450                         let _ = tcx.$name(key);
451                     }
452                 }
453
454                 DepKindStruct {
455                     is_anon,
456                     is_eval_always,
457                     fingerprint_style,
458                     force_from_dep_node: Some(force_from_dep_node),
459                     try_load_from_on_disk_cache: Some(try_load_from_on_disk_cache),
460                 }
461             })*
462         }
463
464         pub fn query_callbacks<'tcx>(arena: &'tcx Arena<'tcx>) -> &'tcx [DepKindStruct] {
465             arena.alloc_from_iter(make_dep_kind_array!(query_callbacks))
466         }
467     }
468 }
469
470 // FIXME(eddyb) this macro (and others?) use `$tcx` and `'tcx` interchangeably.
471 // We should either not take `$tcx` at all and use `'tcx` everywhere, or use
472 // `$tcx` everywhere (even if that isn't necessary due to lack of hygiene).
473 macro_rules! define_queries_struct {
474     (tcx: $tcx:tt,
475      input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
476         pub struct Queries<$tcx> {
477             local_providers: Box<Providers>,
478             extern_providers: Box<ExternProviders>,
479
480             pub on_disk_cache: Option<OnDiskCache<$tcx>>,
481
482             jobs: AtomicU64,
483
484             $($(#[$attr])*  $name: QueryState<query_keys::$name<$tcx>>,)*
485         }
486
487         impl<$tcx> Queries<$tcx> {
488             pub fn new(
489                 local_providers: Providers,
490                 extern_providers: ExternProviders,
491                 on_disk_cache: Option<OnDiskCache<$tcx>>,
492             ) -> Self {
493                 Queries {
494                     local_providers: Box::new(local_providers),
495                     extern_providers: Box::new(extern_providers),
496                     on_disk_cache,
497                     jobs: AtomicU64::new(1),
498                     $($name: Default::default()),*
499                 }
500             }
501
502             pub(crate) fn try_collect_active_jobs(
503                 &$tcx self,
504                 tcx: TyCtxt<$tcx>,
505             ) -> Option<QueryMap> {
506                 let tcx = QueryCtxt { tcx, queries: self };
507                 let mut jobs = QueryMap::default();
508
509                 $(
510                     self.$name.try_collect_active_jobs(
511                         tcx,
512                         make_query::$name,
513                         &mut jobs,
514                     )?;
515                 )*
516
517                 Some(jobs)
518             }
519         }
520
521         impl<'tcx> QueryEngine<'tcx> for Queries<'tcx> {
522             fn as_any(&'tcx self) -> &'tcx dyn std::any::Any {
523                 let this = unsafe { std::mem::transmute::<&Queries<'_>, &Queries<'_>>(self) };
524                 this as _
525             }
526
527             fn try_mark_green(&'tcx self, tcx: TyCtxt<'tcx>, dep_node: &dep_graph::DepNode) -> bool {
528                 let qcx = QueryCtxt { tcx, queries: self };
529                 tcx.dep_graph.try_mark_green(qcx, dep_node).is_some()
530             }
531
532             $($(#[$attr])*
533             #[inline(always)]
534             #[tracing::instrument(level = "trace", skip(self, tcx))]
535             fn $name(
536                 &'tcx self,
537                 tcx: TyCtxt<$tcx>,
538                 span: Span,
539                 key: query_keys::$name<$tcx>,
540                 mode: QueryMode,
541             ) -> Option<query_stored::$name<$tcx>> {
542                 opt_remap_env_constness!([$($modifiers)*][key]);
543                 let qcx = QueryCtxt { tcx, queries: self };
544                 get_query::<queries::$name<$tcx>, _>(qcx, span, key, mode)
545             })*
546         }
547     };
548 }