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