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.
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,
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,
22 use rustc_query_system::Value;
23 use rustc_serialize::Decodable;
25 use std::num::NonZeroU64;
26 use thin_vec::ThinVec;
28 #[derive(Copy, Clone)]
29 pub struct QueryCtxt<'tcx> {
30 pub tcx: TyCtxt<'tcx>,
31 pub queries: &'tcx Queries<'tcx>,
34 impl<'tcx> std::ops::Deref for QueryCtxt<'tcx> {
35 type Target = TyCtxt<'tcx>;
38 fn deref(&self) -> &Self::Target {
43 impl<'tcx> HasDepContext for QueryCtxt<'tcx> {
44 type DepKind = rustc_middle::dep_graph::DepKind;
45 type DepContext = TyCtxt<'tcx>;
48 fn dep_context(&self) -> &Self::DepContext {
53 impl QueryContext for QueryCtxt<'_> {
54 fn next_job_id(&self) -> QueryJobId {
57 self.queries.jobs.fetch_add(1, rustc_data_structures::sync::Ordering::Relaxed),
63 fn current_query_job(&self) -> Option<QueryJobId> {
64 tls::with_related_context(**self, |icx| icx.query)
67 fn try_collect_active_jobs(&self) -> Option<QueryMap> {
68 self.queries.try_collect_active_jobs(**self)
71 // Interactions with on_disk_cache
72 fn load_side_effects(&self, prev_dep_node_index: SerializedDepNodeIndex) -> QuerySideEffects {
76 .map(|c| c.load_side_effects(**self, prev_dep_node_index))
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)
86 fn store_side_effects_for_anon_node(
88 dep_node_index: DepNodeIndex,
89 side_effects: QuerySideEffects,
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)
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.
104 diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
105 compute: impl FnOnce() -> 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();
115 // Update the `ImplicitCtxt` to point to our new query job.
116 let new_icx = ImplicitCtxt {
120 query_depth: current_icx.query_depth + depth_limit as usize,
121 task_deps: current_icx.task_deps,
124 // Use the `ImplicitCtxt` while we execute the query.
125 tls::enter_context(&new_icx, |_| {
126 rustc_data_structures::stack::ensure_sufficient_stack(compute)
132 impl<'tcx> QueryCtxt<'tcx> {
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);
142 QueryCtxt { tcx, queries }
145 pub(crate) fn on_disk_cache(self) -> Option<&'tcx on_disk_cache::OnDiskCache<'tcx>> {
146 self.queries.on_disk_cache.as_ref()
149 pub(super) fn encode_query_results(
151 encoder: &mut on_disk_cache::CacheEncoder<'_, 'tcx>,
152 query_result_index: &mut on_disk_cache::EncodedDepNodeIndex,
154 macro_rules! encode_queries {
155 ($($query:ident,)*) => {
157 on_disk_cache::encode_query_results::<_, super::queries::$query<'_>>(
166 rustc_cached_queries!(encode_queries!);
169 pub fn try_print_query_stack(
171 query: Option<QueryJobId>,
173 num_frames: Option<usize>,
175 rustc_query_system::query::print_query_stack(self, query, handler, num_frames)
179 macro_rules! handle_cycle_error {
181 rustc_query_system::HandleCycleError::Error
183 ([(fatal_cycle) $($rest:tt)*]) => {{
184 rustc_query_system::HandleCycleError::Fatal
186 ([(cycle_delay_bug) $($rest:tt)*]) => {{
187 rustc_query_system::HandleCycleError::DelayBug
189 ([$other:tt $($modifiers:tt)*]) => {
190 handle_cycle_error!([$($modifiers)*])
194 macro_rules! is_anon {
198 ([(anon) $($rest:tt)*]) => {{
201 ([$other:tt $($modifiers:tt)*]) => {
202 is_anon!([$($modifiers)*])
206 macro_rules! is_eval_always {
210 ([(eval_always) $($rest:tt)*]) => {{
213 ([$other:tt $($modifiers:tt)*]) => {
214 is_eval_always!([$($modifiers)*])
218 macro_rules! depth_limit {
222 ([(depth_limit) $($rest:tt)*]) => {{
225 ([$other:tt $($modifiers:tt)*]) => {
226 depth_limit!([$($modifiers)*])
230 macro_rules! hash_result {
232 Some(dep_graph::hash_result)
234 ([(no_hash) $($rest:tt)*]) => {{
237 ([$other:tt $($modifiers:tt)*]) => {
238 hash_result!([$($modifiers)*])
242 macro_rules! get_provider {
243 ([][$tcx:expr, $name:ident, $key:expr]) => {{
244 $tcx.queries.local_providers.$name
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
250 $tcx.queries.extern_providers.$name
253 ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
254 get_provider!([$($modifiers)*][$($args)*])
258 macro_rules! should_ever_cache_on_disk {
262 ([(cache) $($rest:tt)*]) => {{
263 Some($crate::plumbing::try_load_from_disk::<Self::Value>)
265 ([$other:tt $($modifiers:tt)*]) => {
266 should_ever_cache_on_disk!([$($modifiers)*])
270 pub(crate) fn create_query_frame<
272 K: Copy + Key + for<'a> HashStable<StableHashingContext<'a>>,
274 tcx: QueryCtxt<'tcx>,
275 do_describe: fn(QueryCtxt<'tcx>, K) -> String,
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))
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.
293 Some(key.default_span(*tcx))
295 let def_kind = if kind == dep_graph::DepKind::opt_def_kind {
296 // Try to avoid infinite recursion.
300 .and_then(|def_id| def_id.as_local())
301 .and_then(|def_id| tcx.opt_def_kind(def_id))
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>()
312 QueryStackFrame::new(name, description, span, def_kind, hash)
315 fn try_load_from_on_disk_cache<'tcx, Q>(tcx: TyCtxt<'tcx>, dep_node: DepNode)
317 Q: QueryDescription<QueryCtxt<'tcx>>,
318 Q::Key: DepNodeParams<TyCtxt<'tcx>>,
320 debug_assert!(tcx.dep_graph.is_green(&dep_node));
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)
325 if Q::cache_on_disk(tcx, &key) {
326 let _ = Q::execute_query(tcx, key);
330 pub(crate) fn try_load_from_disk<'tcx, V>(
331 tcx: QueryCtxt<'tcx>,
332 id: SerializedDepNodeIndex,
335 V: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
337 tcx.on_disk_cache().as_ref()?.try_load_query_result(*tcx, id)
340 fn force_from_dep_node<'tcx, Q>(tcx: TyCtxt<'tcx>, dep_node: DepNode) -> bool
342 Q: QueryDescription<QueryCtxt<'tcx>>,
343 Q::Key: DepNodeParams<TyCtxt<'tcx>>,
344 Q::Value: Value<TyCtxt<'tcx>>,
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);
357 pub(crate) fn query_callback<'tcx, Q: QueryConfig>(
359 is_eval_always: bool,
360 ) -> DepKindStruct<'tcx>
362 Q: QueryDescription<QueryCtxt<'tcx>>,
363 Q::Key: DepNodeParams<TyCtxt<'tcx>>,
365 let fingerprint_style = Q::Key::fingerprint_style();
367 if is_anon || !fingerprint_style.reconstructible() {
368 return DepKindStruct {
372 force_from_dep_node: None,
373 try_load_from_on_disk_cache: None,
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>),
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 {
391 [$($modifiers:tt)*] fn $name:ident($($K:tt)*) -> $V:ty,)*) => {
392 define_queries_struct! {
393 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
396 #[allow(nonstandard_style)]
398 use std::marker::PhantomData;
400 $(pub struct $name<'tcx> {
401 data: PhantomData<&'tcx ()>
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);
412 impl<'tcx> QueryDescription<QueryCtxt<'tcx>> for queries::$name<'tcx> {
413 rustc_query_description! { $name }
415 type Cache = query_storage::$name<'tcx>;
418 fn query_state<'a>(tcx: QueryCtxt<'tcx>) -> &'a QueryState<Self::Key>
419 where QueryCtxt<'tcx>: 'a
425 fn query_cache<'a>(tcx: QueryCtxt<'tcx>) -> &'a Self::Cache
428 &tcx.query_caches.$name
432 fn make_vtable(tcx: QueryCtxt<'tcx>, key: &Self::Key) ->
433 QueryVTable<QueryCtxt<'tcx>, Self::Key, Self::Value>
435 let compute = get_provider!([$($modifiers)*][tcx, $name, key]);
436 let cache_on_disk = Self::cache_on_disk(tcx.tcx, key);
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)*]),
445 try_load_from_disk: if cache_on_disk { should_ever_cache_on_disk!([$($modifiers)*]) } else { None },
449 fn execute_query(tcx: TyCtxt<'tcx>, k: Self::Key) -> Self::Stored {
454 #[allow(nonstandard_style)]
455 mod query_callbacks {
457 use rustc_query_system::dep_graph::FingerprintStyle;
459 // We use this for most things when incr. comp. is turned off.
460 pub fn Null<'tcx>() -> DepKindStruct<'tcx> {
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,
470 // We use this for the forever-red node.
471 pub fn Red<'tcx>() -> DepKindStruct<'tcx> {
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,
481 pub fn TraitSelect<'tcx>() -> DepKindStruct<'tcx> {
484 is_eval_always: false,
485 fingerprint_style: FingerprintStyle::Unit,
486 force_from_dep_node: None,
487 try_load_from_on_disk_cache: None,
491 pub fn CompileCodegenUnit<'tcx>() -> DepKindStruct<'tcx> {
494 is_eval_always: false,
495 fingerprint_style: FingerprintStyle::Opaque,
496 force_from_dep_node: None,
497 try_load_from_on_disk_cache: None,
501 pub fn CompileMonoItem<'tcx>() -> DepKindStruct<'tcx> {
504 is_eval_always: false,
505 fingerprint_style: FingerprintStyle::Opaque,
506 force_from_dep_node: None,
507 try_load_from_on_disk_cache: None,
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)*]),
519 pub fn query_callbacks<'tcx>(arena: &'tcx Arena<'tcx>) -> &'tcx [DepKindStruct<'tcx>] {
520 arena.alloc_from_iter(make_dep_kind_array!(query_callbacks))
525 use crate::{ExternProviders, OnDiskCache, Providers};
527 impl<'tcx> Queries<'tcx> {
529 local_providers: Providers,
530 extern_providers: ExternProviders,
531 on_disk_cache: Option<OnDiskCache<'tcx>>,
534 local_providers: Box::new(local_providers),
535 extern_providers: Box::new(extern_providers),
537 jobs: AtomicU64::new(1),
543 macro_rules! define_queries_struct {
545 input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
547 pub struct Queries<'tcx> {
548 local_providers: Box<Providers>,
549 extern_providers: Box<ExternProviders>,
551 pub on_disk_cache: Option<OnDiskCache<'tcx>>,
555 $($(#[$attr])* $name: QueryState<<queries::$name<'tcx> as QueryConfig>::Key>,)*
558 impl<'tcx> Queries<'tcx> {
559 pub(crate) fn try_collect_active_jobs(
562 ) -> Option<QueryMap> {
563 let tcx = QueryCtxt { tcx, queries: self };
564 let mut jobs = QueryMap::default();
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)
572 self.$name.try_collect_active_jobs(
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) };
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()
596 #[tracing::instrument(level = "trace", skip(self, tcx), ret)]
601 key: <queries::$name<'tcx> as QueryConfig>::Key,
603 ) -> Option<query_stored::$name<'tcx>> {
604 let qcx = QueryCtxt { tcx, queries: self };
605 get_query::<queries::$name<'tcx>, _>(qcx, span, key, mode)