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::{LayoutOfDepth, QueryOverflow, Value};
23 use rustc_serialize::Decodable;
24 use rustc_session::Limit;
25 use rustc_span::def_id::LOCAL_CRATE;
27 use std::num::NonZeroU64;
28 use thin_vec::ThinVec;
30 #[derive(Copy, Clone)]
31 pub struct QueryCtxt<'tcx> {
32 pub tcx: TyCtxt<'tcx>,
33 pub queries: &'tcx Queries<'tcx>,
36 impl<'tcx> std::ops::Deref for QueryCtxt<'tcx> {
37 type Target = TyCtxt<'tcx>;
40 fn deref(&self) -> &Self::Target {
45 impl<'tcx> HasDepContext for QueryCtxt<'tcx> {
46 type DepKind = rustc_middle::dep_graph::DepKind;
47 type DepContext = TyCtxt<'tcx>;
50 fn dep_context(&self) -> &Self::DepContext {
55 impl QueryContext for QueryCtxt<'_> {
56 fn next_job_id(&self) -> QueryJobId {
59 self.queries.jobs.fetch_add(1, rustc_data_structures::sync::Ordering::Relaxed),
65 fn current_query_job(&self) -> Option<QueryJobId> {
66 tls::with_related_context(**self, |icx| icx.query)
69 fn try_collect_active_jobs(&self) -> Option<QueryMap> {
70 self.queries.try_collect_active_jobs(**self)
73 // Interactions with on_disk_cache
74 fn load_side_effects(&self, prev_dep_node_index: SerializedDepNodeIndex) -> QuerySideEffects {
78 .map(|c| c.load_side_effects(**self, prev_dep_node_index))
82 fn store_side_effects(&self, dep_node_index: DepNodeIndex, side_effects: QuerySideEffects) {
83 if let Some(c) = self.queries.on_disk_cache.as_ref() {
84 c.store_side_effects(dep_node_index, side_effects)
88 fn store_side_effects_for_anon_node(
90 dep_node_index: DepNodeIndex,
91 side_effects: QuerySideEffects,
93 if let Some(c) = self.queries.on_disk_cache.as_ref() {
94 c.store_side_effects_for_anon_node(dep_node_index, side_effects)
98 /// Executes a job by changing the `ImplicitCtxt` to point to the
99 /// new query job while it executes. It returns the diagnostics
100 /// captured during execution and the actual result.
106 diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
107 compute: impl FnOnce() -> R,
109 // The `TyCtxt` stored in TLS has the same global interner lifetime
110 // as `self`, so we use `with_related_context` to relate the 'tcx lifetimes
111 // when accessing the `ImplicitCtxt`.
112 tls::with_related_context(**self, move |current_icx| {
113 if depth_limit && !self.recursion_limit().value_within_limit(current_icx.query_depth) {
114 self.depth_limit_error(token);
117 // Update the `ImplicitCtxt` to point to our new query job.
118 let new_icx = ImplicitCtxt {
122 query_depth: current_icx.query_depth + depth_limit as usize,
123 task_deps: current_icx.task_deps,
126 // Use the `ImplicitCtxt` while we execute the query.
127 tls::enter_context(&new_icx, |_| {
128 rustc_data_structures::stack::ensure_sufficient_stack(compute)
133 fn depth_limit_error(&self, job: QueryJobId) {
135 let mut layout_of_depth = None;
136 if let Some(map) = self.try_collect_active_jobs() {
137 if let Some((info, depth)) = job.try_find_layout_root(map) {
138 span = Some(info.job.span);
139 layout_of_depth = Some(LayoutOfDepth { desc: info.query.description, depth });
143 let suggested_limit = match self.recursion_limit() {
144 Limit(0) => Limit(2),
148 self.sess.emit_fatal(QueryOverflow {
152 crate_name: self.crate_name(LOCAL_CRATE),
157 impl<'tcx> QueryCtxt<'tcx> {
159 pub fn from_tcx(tcx: TyCtxt<'tcx>) -> Self {
160 let queries = tcx.queries.as_any();
161 let queries = unsafe {
162 let queries = std::mem::transmute::<&dyn Any, &dyn Any>(queries);
163 let queries = queries.downcast_ref().unwrap();
164 let queries = std::mem::transmute::<&Queries<'_>, &Queries<'_>>(queries);
167 QueryCtxt { tcx, queries }
170 pub(crate) fn on_disk_cache(self) -> Option<&'tcx on_disk_cache::OnDiskCache<'tcx>> {
171 self.queries.on_disk_cache.as_ref()
174 pub(super) fn encode_query_results(
176 encoder: &mut on_disk_cache::CacheEncoder<'_, 'tcx>,
177 query_result_index: &mut on_disk_cache::EncodedDepNodeIndex,
179 macro_rules! expand_if_cached {
180 ([] $encode:expr) => {};
181 ([(cache) $($rest:tt)*] $encode:expr) => {
184 ([$other:tt $($modifiers:tt)*] $encode:expr) => {
185 expand_if_cached!([$($modifiers)*] $encode)
189 macro_rules! encode_queries {
192 [$($modifiers:tt)*] fn $query:ident($($K:tt)*) -> $V:ty,)*) => {
194 expand_if_cached!([$($modifiers)*] on_disk_cache::encode_query_results::<_, super::queries::$query<'_>>(
203 rustc_query_append!(encode_queries!);
206 pub fn try_print_query_stack(
208 query: Option<QueryJobId>,
210 num_frames: Option<usize>,
212 rustc_query_system::query::print_query_stack(self, query, handler, num_frames)
216 macro_rules! handle_cycle_error {
218 rustc_query_system::HandleCycleError::Error
220 ([(fatal_cycle) $($rest:tt)*]) => {{
221 rustc_query_system::HandleCycleError::Fatal
223 ([(cycle_delay_bug) $($rest:tt)*]) => {{
224 rustc_query_system::HandleCycleError::DelayBug
226 ([$other:tt $($modifiers:tt)*]) => {
227 handle_cycle_error!([$($modifiers)*])
231 macro_rules! is_anon {
235 ([(anon) $($rest:tt)*]) => {{
238 ([$other:tt $($modifiers:tt)*]) => {
239 is_anon!([$($modifiers)*])
243 macro_rules! is_eval_always {
247 ([(eval_always) $($rest:tt)*]) => {{
250 ([$other:tt $($modifiers:tt)*]) => {
251 is_eval_always!([$($modifiers)*])
255 macro_rules! depth_limit {
259 ([(depth_limit) $($rest:tt)*]) => {{
262 ([$other:tt $($modifiers:tt)*]) => {
263 depth_limit!([$($modifiers)*])
267 macro_rules! hash_result {
269 Some(dep_graph::hash_result)
271 ([(no_hash) $($rest:tt)*]) => {{
274 ([$other:tt $($modifiers:tt)*]) => {
275 hash_result!([$($modifiers)*])
279 macro_rules! get_provider {
280 ([][$tcx:expr, $name:ident, $key:expr]) => {{
281 $tcx.queries.local_providers.$name
283 ([(separate_provide_extern) $($rest:tt)*][$tcx:expr, $name:ident, $key:expr]) => {{
284 if $key.query_crate_is_local() {
285 $tcx.queries.local_providers.$name
287 $tcx.queries.extern_providers.$name
290 ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
291 get_provider!([$($modifiers)*][$($args)*])
295 macro_rules! should_ever_cache_on_disk {
299 ([(cache) $($rest:tt)*]) => {{
300 Some($crate::plumbing::try_load_from_disk::<Self::Value>)
302 ([$other:tt $($modifiers:tt)*]) => {
303 should_ever_cache_on_disk!([$($modifiers)*])
307 pub(crate) fn create_query_frame<
309 K: Copy + Key + for<'a> HashStable<StableHashingContext<'a>>,
311 tcx: QueryCtxt<'tcx>,
312 do_describe: fn(QueryCtxt<'tcx>, K) -> String,
316 ) -> QueryStackFrame {
317 // Disable visible paths printing for performance reasons.
318 // Showing visible path instead of any path is not that important in production.
319 let description = ty::print::with_no_visible_paths!(
320 // Force filename-line mode to avoid invoking `type_of` query.
321 ty::print::with_forced_impl_filename_line!(do_describe(tcx, key))
324 if tcx.sess.verbose() { format!("{} [{}]", description, name) } else { description };
325 let span = if kind == dep_graph::DepKind::def_span {
326 // The `def_span` query is used to calculate `default_span`,
327 // so exit to avoid infinite recursion.
330 Some(key.default_span(*tcx))
332 let def_kind = if kind == dep_graph::DepKind::opt_def_kind {
333 // Try to avoid infinite recursion.
337 .and_then(|def_id| def_id.as_local())
338 .and_then(|def_id| tcx.opt_def_kind(def_id))
341 tcx.with_stable_hashing_context(|mut hcx| {
342 let mut hasher = StableHasher::new();
343 std::mem::discriminant(&kind).hash_stable(&mut hcx, &mut hasher);
344 key.hash_stable(&mut hcx, &mut hasher);
345 hasher.finish::<u64>()
349 QueryStackFrame::new(name, description, span, def_kind, hash)
352 fn try_load_from_on_disk_cache<'tcx, Q>(tcx: TyCtxt<'tcx>, dep_node: DepNode)
354 Q: QueryDescription<QueryCtxt<'tcx>>,
355 Q::Key: DepNodeParams<TyCtxt<'tcx>>,
357 debug_assert!(tcx.dep_graph.is_green(&dep_node));
359 let key = Q::Key::recover(tcx, &dep_node).unwrap_or_else(|| {
360 panic!("Failed to recover key for {:?} with hash {}", dep_node, dep_node.hash)
362 if Q::cache_on_disk(tcx, &key) {
363 let _ = Q::execute_query(tcx, key);
367 pub(crate) fn try_load_from_disk<'tcx, V>(
368 tcx: QueryCtxt<'tcx>,
369 id: SerializedDepNodeIndex,
372 V: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
374 tcx.on_disk_cache().as_ref()?.try_load_query_result(*tcx, id)
377 fn force_from_dep_node<'tcx, Q>(tcx: TyCtxt<'tcx>, dep_node: DepNode) -> bool
379 Q: QueryDescription<QueryCtxt<'tcx>>,
380 Q::Key: DepNodeParams<TyCtxt<'tcx>>,
381 Q::Value: Value<TyCtxt<'tcx>>,
383 if let Some(key) = Q::Key::recover(tcx, &dep_node) {
384 #[cfg(debug_assertions)]
385 let _guard = tracing::span!(tracing::Level::TRACE, stringify!($name), ?key).entered();
386 let tcx = QueryCtxt::from_tcx(tcx);
387 force_query::<Q, _>(tcx, key, dep_node);
394 pub(crate) fn query_callback<'tcx, Q: QueryConfig>(
396 is_eval_always: bool,
397 ) -> DepKindStruct<'tcx>
399 Q: QueryDescription<QueryCtxt<'tcx>>,
400 Q::Key: DepNodeParams<TyCtxt<'tcx>>,
402 let fingerprint_style = Q::Key::fingerprint_style();
404 if is_anon || !fingerprint_style.reconstructible() {
405 return DepKindStruct {
409 force_from_dep_node: None,
410 try_load_from_on_disk_cache: None,
418 force_from_dep_node: Some(force_from_dep_node::<Q>),
419 try_load_from_on_disk_cache: Some(try_load_from_on_disk_cache::<Q>),
423 // NOTE: `$V` isn't used here, but we still need to match on it so it can be passed to other macros
424 // invoked by `rustc_query_append`.
425 macro_rules! define_queries {
428 [$($modifiers:tt)*] fn $name:ident($($K:tt)*) -> $V:ty,)*) => {
429 define_queries_struct! {
430 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
433 #[allow(nonstandard_style)]
435 use std::marker::PhantomData;
437 $(pub struct $name<'tcx> {
438 data: PhantomData<&'tcx ()>
442 $(impl<'tcx> QueryConfig for queries::$name<'tcx> {
443 type Key = query_keys::$name<'tcx>;
444 type Value = query_values::$name<'tcx>;
445 type Stored = query_stored::$name<'tcx>;
446 const NAME: &'static str = stringify!($name);
449 impl<'tcx> QueryDescription<QueryCtxt<'tcx>> for queries::$name<'tcx> {
450 rustc_query_description! { $name }
452 type Cache = query_storage::$name<'tcx>;
455 fn query_state<'a>(tcx: QueryCtxt<'tcx>) -> &'a QueryState<Self::Key>
456 where QueryCtxt<'tcx>: 'a
462 fn query_cache<'a>(tcx: QueryCtxt<'tcx>) -> &'a Self::Cache
465 &tcx.query_caches.$name
469 fn make_vtable(tcx: QueryCtxt<'tcx>, key: &Self::Key) ->
470 QueryVTable<QueryCtxt<'tcx>, Self::Key, Self::Value>
472 let compute = get_provider!([$($modifiers)*][tcx, $name, key]);
473 let cache_on_disk = Self::cache_on_disk(tcx.tcx, key);
475 anon: is_anon!([$($modifiers)*]),
476 eval_always: is_eval_always!([$($modifiers)*]),
477 depth_limit: depth_limit!([$($modifiers)*]),
478 dep_kind: dep_graph::DepKind::$name,
479 hash_result: hash_result!([$($modifiers)*]),
480 handle_cycle_error: handle_cycle_error!([$($modifiers)*]),
482 try_load_from_disk: if cache_on_disk { should_ever_cache_on_disk!([$($modifiers)*]) } else { None },
486 fn execute_query(tcx: TyCtxt<'tcx>, k: Self::Key) -> Self::Stored {
491 #[allow(nonstandard_style)]
492 mod query_callbacks {
494 use rustc_query_system::dep_graph::FingerprintStyle;
496 // We use this for most things when incr. comp. is turned off.
497 pub fn Null<'tcx>() -> DepKindStruct<'tcx> {
500 is_eval_always: false,
501 fingerprint_style: FingerprintStyle::Unit,
502 force_from_dep_node: Some(|_, dep_node| bug!("force_from_dep_node: encountered {:?}", dep_node)),
503 try_load_from_on_disk_cache: None,
507 // We use this for the forever-red node.
508 pub fn Red<'tcx>() -> DepKindStruct<'tcx> {
511 is_eval_always: false,
512 fingerprint_style: FingerprintStyle::Unit,
513 force_from_dep_node: Some(|_, dep_node| bug!("force_from_dep_node: encountered {:?}", dep_node)),
514 try_load_from_on_disk_cache: None,
518 pub fn TraitSelect<'tcx>() -> DepKindStruct<'tcx> {
521 is_eval_always: false,
522 fingerprint_style: FingerprintStyle::Unit,
523 force_from_dep_node: None,
524 try_load_from_on_disk_cache: None,
528 pub fn CompileCodegenUnit<'tcx>() -> DepKindStruct<'tcx> {
531 is_eval_always: false,
532 fingerprint_style: FingerprintStyle::Opaque,
533 force_from_dep_node: None,
534 try_load_from_on_disk_cache: None,
538 pub fn CompileMonoItem<'tcx>() -> DepKindStruct<'tcx> {
541 is_eval_always: false,
542 fingerprint_style: FingerprintStyle::Opaque,
543 force_from_dep_node: None,
544 try_load_from_on_disk_cache: None,
548 $(pub(crate) fn $name<'tcx>()-> DepKindStruct<'tcx> {
549 $crate::plumbing::query_callback::<queries::$name<'tcx>>(
550 is_anon!([$($modifiers)*]),
551 is_eval_always!([$($modifiers)*]),
556 pub fn query_callbacks<'tcx>(arena: &'tcx Arena<'tcx>) -> &'tcx [DepKindStruct<'tcx>] {
557 arena.alloc_from_iter(make_dep_kind_array!(query_callbacks))
562 use crate::{ExternProviders, OnDiskCache, Providers};
564 impl<'tcx> Queries<'tcx> {
566 local_providers: Providers,
567 extern_providers: ExternProviders,
568 on_disk_cache: Option<OnDiskCache<'tcx>>,
571 local_providers: Box::new(local_providers),
572 extern_providers: Box::new(extern_providers),
574 jobs: AtomicU64::new(1),
580 macro_rules! define_queries_struct {
582 input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
584 pub struct Queries<'tcx> {
585 local_providers: Box<Providers>,
586 extern_providers: Box<ExternProviders>,
588 pub on_disk_cache: Option<OnDiskCache<'tcx>>,
592 $($(#[$attr])* $name: QueryState<<queries::$name<'tcx> as QueryConfig>::Key>,)*
595 impl<'tcx> Queries<'tcx> {
596 pub(crate) fn try_collect_active_jobs(
599 ) -> Option<QueryMap> {
600 let tcx = QueryCtxt { tcx, queries: self };
601 let mut jobs = QueryMap::default();
604 let make_query = |tcx, key| {
605 let kind = dep_graph::DepKind::$name;
606 let name = stringify!($name);
607 $crate::plumbing::create_query_frame(tcx, queries::$name::describe, key, kind, name)
609 self.$name.try_collect_active_jobs(
620 impl<'tcx> QueryEngine<'tcx> for Queries<'tcx> {
621 fn as_any(&'tcx self) -> &'tcx dyn std::any::Any {
622 let this = unsafe { std::mem::transmute::<&Queries<'_>, &Queries<'_>>(self) };
626 fn try_mark_green(&'tcx self, tcx: TyCtxt<'tcx>, dep_node: &dep_graph::DepNode) -> bool {
627 let qcx = QueryCtxt { tcx, queries: self };
628 tcx.dep_graph.try_mark_green(qcx, dep_node).is_some()
633 #[tracing::instrument(level = "trace", skip(self, tcx), ret)]
638 key: <queries::$name<'tcx> as QueryConfig>::Key,
640 ) -> Option<query_stored::$name<'tcx>> {
641 let qcx = QueryCtxt { tcx, queries: self };
642 get_query::<queries::$name<'tcx>, _>(qcx, span, key, mode)