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.
5 use crate::dep_graph::{DepKind, DepNode, DepNodeIndex, SerializedDepNodeIndex};
6 use crate::ty::query::config::{QueryConfig, QueryDescription};
7 use crate::ty::query::job::{QueryInfo, QueryJob};
8 use crate::ty::query::Query;
10 use crate::ty::{self, TyCtxt};
12 use errors::{struct_span_err, Diagnostic, DiagnosticBuilder, FatalError, Handler, Level};
13 #[cfg(not(parallel_compiler))]
14 use rustc_data_structures::cold_path;
15 use rustc_data_structures::fx::{FxHashMap, FxHasher};
16 use rustc_data_structures::sharded::Sharded;
17 use rustc_data_structures::sync::{Lock, Lrc};
18 use rustc_data_structures::thin_vec::ThinVec;
19 use rustc_span::source_map::DUMMY_SP;
21 use std::collections::hash_map::Entry;
22 use std::hash::{Hash, Hasher};
26 use rustc_error_codes::*;
28 pub struct QueryCache<'tcx, D: QueryConfig<'tcx> + ?Sized> {
29 pub(super) results: FxHashMap<D::Key, QueryValue<D::Value>>,
30 pub(super) active: FxHashMap<D::Key, QueryResult<'tcx>>,
31 #[cfg(debug_assertions)]
32 pub(super) cache_hits: usize,
35 pub(super) struct QueryValue<T> {
37 pub(super) index: DepNodeIndex,
40 impl<T> QueryValue<T> {
41 pub(super) fn new(value: T, dep_node_index: DepNodeIndex) -> QueryValue<T> {
42 QueryValue { value, index: dep_node_index }
46 /// Indicates the state of a query for a given key in a query map.
47 pub(super) enum QueryResult<'tcx> {
48 /// An already executing query. The query job can be used to await for its completion.
49 Started(Lrc<QueryJob<'tcx>>),
51 /// The query panicked. Queries trying to wait on this will raise a fatal error or
56 impl<'tcx, M: QueryConfig<'tcx>> Default for QueryCache<'tcx, M> {
57 fn default() -> QueryCache<'tcx, M> {
59 results: FxHashMap::default(),
60 active: FxHashMap::default(),
61 #[cfg(debug_assertions)]
67 /// A type representing the responsibility to execute the job in the `job` field.
68 /// This will poison the relevant query if dropped.
69 pub(super) struct JobOwner<'a, 'tcx, Q: QueryDescription<'tcx>> {
70 cache: &'a Sharded<QueryCache<'tcx, Q>>,
72 job: Lrc<QueryJob<'tcx>>,
75 impl<'a, 'tcx, Q: QueryDescription<'tcx>> JobOwner<'a, 'tcx, Q> {
76 /// Either gets a `JobOwner` corresponding the query, allowing us to
77 /// start executing the query, or returns with the result of the query.
78 /// If the query is executing elsewhere, this will wait for it.
79 /// If the query panicked, this will silently panic.
81 /// This function is inlined because that results in a noticeable speed-up
82 /// for some compile-time benchmarks.
84 pub(super) fn try_get(tcx: TyCtxt<'tcx>, span: Span, key: &Q::Key) -> TryGetJob<'a, 'tcx, Q> {
85 let cache = Q::query_cache(tcx);
87 // We compute the key's hash once and then use it for both the
88 // shard lookup and the hashmap lookup. This relies on the fact
89 // that both of them use `FxHasher`.
90 let mut state = FxHasher::default();
92 let key_hash = state.finish();
94 let mut lock = cache.get_shard_by_hash(key_hash).lock();
95 if let Some((_, value)) =
96 lock.results.raw_entry().from_key_hashed_nocheck(key_hash, key)
98 tcx.prof.query_cache_hit(Q::NAME);
99 let result = (value.value.clone(), value.index);
100 #[cfg(debug_assertions)]
102 lock.cache_hits += 1;
104 return TryGetJob::JobCompleted(result);
107 #[cfg(parallel_compiler)]
108 let query_blocked_prof_timer;
110 let job = match lock.active.entry((*key).clone()) {
111 Entry::Occupied(entry) => {
113 QueryResult::Started(ref job) => {
114 // For parallel queries, we'll block and wait until the query running
115 // in another thread has completed. Record how long we wait in the
117 #[cfg(parallel_compiler)]
119 query_blocked_prof_timer = tcx.prof.query_blocked(Q::NAME);
124 QueryResult::Poisoned => FatalError.raise(),
127 Entry::Vacant(entry) => {
128 // No job entry for this query. Return a new one to be started later.
129 return tls::with_related_context(tcx, |icx| {
130 // Create the `parent` variable before `info`. This allows LLVM
131 // to elide the move of `info`
132 let parent = icx.query.clone();
133 let info = QueryInfo { span, query: Q::query(key.clone()) };
134 let job = Lrc::new(QueryJob::new(info, parent));
135 let owner = JobOwner { cache, job: job.clone(), key: (*key).clone() };
136 entry.insert(QueryResult::Started(job));
137 TryGetJob::NotYetStarted(owner)
143 // If we are single-threaded we know that we have cycle error,
144 // so we just return the error.
145 #[cfg(not(parallel_compiler))]
146 return TryGetJob::Cycle(cold_path(|| {
147 Q::handle_cycle_error(tcx, job.find_cycle_in_stack(tcx, span))
150 // With parallel queries we might just have to wait on some other
152 #[cfg(parallel_compiler)]
154 let result = job.r#await(tcx, span);
156 // This `drop()` is not strictly necessary as the binding
157 // would go out of scope anyway. But it's good to have an
158 // explicit marker of how far the measurement goes.
159 drop(query_blocked_prof_timer);
161 if let Err(cycle) = result {
162 return TryGetJob::Cycle(Q::handle_cycle_error(tcx, cycle));
168 /// Completes the query by updating the query cache with the `result`,
169 /// signals the waiter and forgets the JobOwner, so it won't poison the query
171 pub(super) fn complete(self, result: &Q::Value, dep_node_index: DepNodeIndex) {
172 // We can move out of `self` here because we `mem::forget` it below
173 let key = unsafe { ptr::read(&self.key) };
174 let job = unsafe { ptr::read(&self.job) };
175 let cache = self.cache;
177 // Forget ourself so our destructor won't poison the query
180 let value = QueryValue::new(result.clone(), dep_node_index);
182 let mut lock = cache.get_shard_by_value(&key).lock();
183 lock.active.remove(&key);
184 lock.results.insert(key, value);
187 job.signal_complete();
192 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
194 F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R,
196 let diagnostics = Lock::new(ThinVec::new());
197 let result = f(Some(&diagnostics));
198 (result, diagnostics.into_inner())
201 impl<'a, 'tcx, Q: QueryDescription<'tcx>> Drop for JobOwner<'a, 'tcx, Q> {
205 // Poison the query so jobs waiting on it panic.
206 let shard = self.cache.get_shard_by_value(&self.key);
207 shard.lock().active.insert(self.key.clone(), QueryResult::Poisoned);
208 // Also signal the completion of the job, so waiters
209 // will continue execution.
210 self.job.signal_complete();
215 pub struct CycleError<'tcx> {
216 /// The query and related span that uses the cycle.
217 pub(super) usage: Option<(Span, Query<'tcx>)>,
218 pub(super) cycle: Vec<QueryInfo<'tcx>>,
221 /// The result of `try_get_lock`.
222 pub(super) enum TryGetJob<'a, 'tcx, D: QueryDescription<'tcx>> {
223 /// The query is not yet started. Contains a guard to the cache eventually used to start it.
224 NotYetStarted(JobOwner<'a, 'tcx, D>),
226 /// The query was already completed.
227 /// Returns the result of the query and its dep-node index
228 /// if it succeeded or a cycle error if it failed.
229 JobCompleted((D::Value, DepNodeIndex)),
231 /// Trying to execute the query resulted in a cycle.
235 impl<'tcx> TyCtxt<'tcx> {
236 /// Executes a job by changing the `ImplicitCtxt` to point to the
237 /// new query job while it executes. It returns the diagnostics
238 /// captured during execution and the actual result.
240 pub(super) fn start_query<F, R>(
242 job: Lrc<QueryJob<'tcx>>,
243 diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
247 F: FnOnce(TyCtxt<'tcx>) -> R,
249 // The `TyCtxt` stored in TLS has the same global interner lifetime
250 // as `self`, so we use `with_related_context` to relate the 'tcx lifetimes
251 // when accessing the `ImplicitCtxt`.
252 tls::with_related_context(self, move |current_icx| {
253 // Update the `ImplicitCtxt` to point to our new query job.
254 let new_icx = tls::ImplicitCtxt {
258 layout_depth: current_icx.layout_depth,
259 task_deps: current_icx.task_deps,
262 // Use the `ImplicitCtxt` while we execute the query.
263 tls::enter_context(&new_icx, |_| compute(self))
269 pub(super) fn report_cycle(
271 CycleError { usage, cycle: stack }: CycleError<'tcx>,
272 ) -> DiagnosticBuilder<'tcx> {
273 assert!(!stack.is_empty());
275 let fix_span = |span: Span, query: &Query<'tcx>| {
276 self.sess.source_map().def_span(query.default_span(self, span))
279 // Disable naming impls with types in this path, since that
280 // sometimes cycles itself, leading to extra cycle errors.
281 // (And cycle errors around impls tend to occur during the
282 // collect/coherence phases anyhow.)
283 ty::print::with_forced_impl_filename_line(|| {
284 let span = fix_span(stack[1 % stack.len()].span, &stack[0].query);
285 let mut err = struct_span_err!(
289 "cycle detected when {}",
290 stack[0].query.describe(self)
293 for i in 1..stack.len() {
294 let query = &stack[i].query;
295 let span = fix_span(stack[(i + 1) % stack.len()].span, query);
296 err.span_note(span, &format!("...which requires {}...", query.describe(self)));
300 "...which again requires {}, completing the cycle",
301 stack[0].query.describe(self)
304 if let Some((span, query)) = usage {
306 fix_span(span, &query),
307 &format!("cycle used when {}", query.describe(self)),
315 pub fn try_print_query_stack(handler: &Handler) {
316 eprintln!("query stack during panic:");
318 // Be careful reyling on global state here: this code is called from
319 // a panic hook, which means that the global `Handler` may be in a weird
320 // state if it was responsible for triggering the panic.
321 tls::with_context_opt(|icx| {
322 if let Some(icx) = icx {
323 let mut current_query = icx.query.clone();
326 while let Some(query) = current_query {
327 let mut diag = Diagnostic::new(
332 query.info.query.name(),
333 query.info.query.describe(icx.tcx)
336 diag.span = icx.tcx.sess.source_map().def_span(query.info.span).into();
337 handler.force_print_diagnostic(diag);
339 current_query = query.parent.clone();
345 eprintln!("end of query stack");
349 pub(super) fn get_query<Q: QueryDescription<'tcx>>(self, span: Span, key: Q::Key) -> Q::Value {
350 debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME.as_str(), key, span);
352 let job = match JobOwner::try_get(self, span, &key) {
353 TryGetJob::NotYetStarted(job) => job,
354 TryGetJob::Cycle(result) => return result,
355 TryGetJob::JobCompleted((v, index)) => {
356 self.dep_graph.read_index(index);
361 // Fast path for when incr. comp. is off. `to_dep_node` is
362 // expensive for some `DepKind`s.
363 if !self.dep_graph.is_fully_enabled() {
364 let null_dep_node = DepNode::new_no_params(crate::dep_graph::DepKind::Null);
365 return self.force_query_with_job::<Q>(key, job, null_dep_node).0;
369 let prof_timer = self.prof.query_provider(Q::NAME);
371 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
372 self.start_query(job.job.clone(), diagnostics, |tcx| {
373 tcx.dep_graph.with_anon_task(Q::dep_kind(), || Q::compute(tcx, key))
379 self.dep_graph.read_index(dep_node_index);
381 if unlikely!(!diagnostics.is_empty()) {
384 .store_diagnostics_for_anon_node(dep_node_index, diagnostics);
387 job.complete(&result, dep_node_index);
392 let dep_node = Q::to_dep_node(self, &key);
395 // The diagnostics for this query will be
396 // promoted to the current session during
397 // `try_mark_green()`, so we can ignore them here.
398 let loaded = self.start_query(job.job.clone(), None, |tcx| {
399 let marked = tcx.dep_graph.try_mark_green_and_read(tcx, &dep_node);
400 marked.map(|(prev_dep_node_index, dep_node_index)| {
402 tcx.load_from_disk_and_cache_in_memory::<Q>(
412 if let Some((result, dep_node_index)) = loaded {
413 job.complete(&result, dep_node_index);
418 let (result, dep_node_index) = self.force_query_with_job::<Q>(key, job, dep_node);
419 self.dep_graph.read_index(dep_node_index);
423 fn load_from_disk_and_cache_in_memory<Q: QueryDescription<'tcx>>(
426 prev_dep_node_index: SerializedDepNodeIndex,
427 dep_node_index: DepNodeIndex,
430 // Note this function can be called concurrently from the same query
431 // We must ensure that this is handled correctly.
433 debug_assert!(self.dep_graph.is_green(dep_node));
435 // First we try to load the result from the on-disk cache.
436 let result = if Q::cache_on_disk(self, key.clone(), None)
437 && self.sess.opts.debugging_opts.incremental_queries
439 let _prof_timer = self.prof.incr_cache_loading(Q::NAME);
440 let result = Q::try_load_from_disk(self, prev_dep_node_index);
442 // We always expect to find a cached result for things that
443 // can be forced from `DepNode`.
445 !dep_node.kind.can_reconstruct_query_key() || result.is_some(),
446 "missing on-disk cache entry for {:?}",
451 // Some things are never cached on disk.
455 let result = if let Some(result) = result {
458 // We could not load a result from the on-disk cache, so
460 let _prof_timer = self.prof.query_provider(Q::NAME);
462 // The dep-graph for this computation is already in-place.
463 let result = self.dep_graph.with_ignore(|| Q::compute(self, key));
468 // If `-Zincremental-verify-ich` is specified, re-hash results from
469 // the cache and make sure that they have the expected fingerprint.
470 if unlikely!(self.sess.opts.debugging_opts.incremental_verify_ich) {
471 self.incremental_verify_ich::<Q>(&result, dep_node, dep_node_index);
479 fn incremental_verify_ich<Q: QueryDescription<'tcx>>(
483 dep_node_index: DepNodeIndex,
485 use crate::ich::Fingerprint;
488 Some(self.dep_graph.fingerprint_of(dep_node_index))
489 == self.dep_graph.prev_fingerprint_of(dep_node),
490 "fingerprint for green query instance not loaded from cache: {:?}",
494 debug!("BEGIN verify_ich({:?})", dep_node);
495 let mut hcx = self.create_stable_hashing_context();
497 let new_hash = Q::hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
498 debug!("END verify_ich({:?})", dep_node);
500 let old_hash = self.dep_graph.fingerprint_of(dep_node_index);
502 assert!(new_hash == old_hash, "found unstable fingerprints for {:?}", dep_node,);
506 fn force_query_with_job<Q: QueryDescription<'tcx>>(
509 job: JobOwner<'_, 'tcx, Q>,
511 ) -> (Q::Value, DepNodeIndex) {
512 // If the following assertion triggers, it can have two reasons:
513 // 1. Something is wrong with DepNode creation, either here or
514 // in `DepGraph::try_mark_green()`.
515 // 2. Two distinct query keys get mapped to the same `DepNode`
516 // (see for example #48923).
518 !self.dep_graph.dep_node_exists(&dep_node),
519 "forcing query with already existing `DepNode`\n\
526 let prof_timer = self.prof.query_provider(Q::NAME);
528 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
529 self.start_query(job.job.clone(), diagnostics, |tcx| {
531 tcx.dep_graph.with_eval_always_task(
539 tcx.dep_graph.with_task(dep_node, tcx, key, Q::compute, Q::hash_result)
546 if unlikely!(!diagnostics.is_empty()) {
547 if dep_node.kind != crate::dep_graph::DepKind::Null {
548 self.queries.on_disk_cache.store_diagnostics(dep_node_index, diagnostics);
552 job.complete(&result, dep_node_index);
554 (result, dep_node_index)
557 /// Ensure that either this query has all green inputs or been executed.
558 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
560 /// This function is particularly useful when executing passes for their
561 /// side-effects -- e.g., in order to report errors for erroneous programs.
563 /// Note: The optimization is only available during incr. comp.
564 pub(super) fn ensure_query<Q: QueryDescription<'tcx>>(self, key: Q::Key) -> () {
566 let _ = self.get_query::<Q>(DUMMY_SP, key);
570 // Ensuring an anonymous query makes no sense
573 let dep_node = Q::to_dep_node(self, &key);
575 if self.dep_graph.try_mark_green_and_read(self, &dep_node).is_none() {
576 // A None return from `try_mark_green_and_read` means that this is either
577 // a new dep node or that the dep node has already been marked red.
578 // Either way, we can't call `dep_graph.read()` as we don't have the
579 // DepNodeIndex. We must invoke the query itself. The performance cost
580 // this introduces should be negligible as we'll immediately hit the
581 // in-memory cache, or another query down the line will.
583 let _ = self.get_query::<Q>(DUMMY_SP, key);
585 self.prof.query_cache_hit(Q::NAME);
590 fn force_query<Q: QueryDescription<'tcx>>(self, key: Q::Key, span: Span, dep_node: DepNode) {
591 // We may be concurrently trying both execute and force a query.
592 // Ensure that only one of them runs the query.
593 let job = match JobOwner::try_get(self, span, &key) {
594 TryGetJob::NotYetStarted(job) => job,
595 TryGetJob::Cycle(_) | TryGetJob::JobCompleted(_) => return,
597 self.force_query_with_job::<Q>(key, job, dep_node);
601 macro_rules! handle_cycle_error {
602 ([][$tcx: expr, $error:expr]) => {{
603 $tcx.report_cycle($error).emit();
604 Value::from_cycle_error($tcx)
606 ([fatal_cycle$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
607 $tcx.report_cycle($error).emit();
608 $tcx.sess.abort_if_errors();
611 ([cycle_delay_bug$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
612 $tcx.report_cycle($error).delay_as_bug();
613 Value::from_cycle_error($tcx)
615 ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
616 handle_cycle_error!([$($modifiers),*][$($args)*])
620 macro_rules! is_anon {
624 ([anon$(, $modifiers:ident)*]) => {{
627 ([$other:ident$(, $modifiers:ident)*]) => {
628 is_anon!([$($modifiers),*])
632 macro_rules! is_eval_always {
636 ([eval_always$(, $modifiers:ident)*]) => {{
639 ([$other:ident$(, $modifiers:ident)*]) => {
640 is_eval_always!([$($modifiers),*])
644 macro_rules! hash_result {
645 ([][$hcx:expr, $result:expr]) => {{
646 dep_graph::hash_result($hcx, &$result)
648 ([no_hash$(, $modifiers:ident)*][$hcx:expr, $result:expr]) => {{
651 ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
652 hash_result!([$($modifiers),*][$($args)*])
656 macro_rules! define_queries {
657 (<$tcx:tt> $($category:tt {
658 $($(#[$attr:meta])* [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*
660 define_queries_inner! { <$tcx>
661 $($( $(#[$attr])* category<$category> [$($modifiers)*] fn $name: $node($K) -> $V,)*)*
666 macro_rules! define_queries_inner {
668 $($(#[$attr:meta])* category<$category:tt>
669 [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
672 use rustc_data_structures::sharded::Sharded;
674 rustc_data_structures::stable_hasher::HashStable,
675 rustc_data_structures::stable_hasher::StableHasher,
676 ich::StableHashingContext
678 use rustc_data_structures::profiling::ProfileCategory;
680 define_queries_struct! {
682 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
685 impl<$tcx> Queries<$tcx> {
687 providers: IndexVec<CrateNum, Providers<$tcx>>,
688 fallback_extern_providers: Providers<$tcx>,
689 on_disk_cache: OnDiskCache<'tcx>,
693 fallback_extern_providers: Box::new(fallback_extern_providers),
695 $($name: Default::default()),*
699 #[cfg(parallel_compiler)]
700 pub fn collect_active_jobs(&self) -> Vec<Lrc<QueryJob<$tcx>>> {
701 let mut jobs = Vec::new();
703 // We use try_lock_shards here since we are only called from the
704 // deadlock handler, and this shouldn't be locked.
706 let shards = self.$name.try_lock_shards().unwrap();
707 jobs.extend(shards.iter().flat_map(|shard| shard.active.values().filter_map(|v|
708 if let QueryResult::Started(ref job) = *v {
719 pub fn print_stats(&self) {
720 let mut queries = Vec::new();
727 key_type: &'static str,
729 value_type: &'static str,
733 fn stats<'tcx, Q: QueryConfig<'tcx>>(
735 map: &Sharded<QueryCache<'tcx, Q>>,
737 let map = map.lock_shards();
740 #[cfg(debug_assertions)]
741 cache_hits: map.iter().map(|shard| shard.cache_hits).sum(),
742 #[cfg(not(debug_assertions))]
744 key_size: mem::size_of::<Q::Key>(),
745 key_type: type_name::<Q::Key>(),
746 value_size: mem::size_of::<Q::Value>(),
747 value_type: type_name::<Q::Value>(),
748 entry_count: map.iter().map(|shard| shard.results.len()).sum(),
753 queries.push(stats::<queries::$name<'_>>(
759 if cfg!(debug_assertions) {
760 let hits: usize = queries.iter().map(|s| s.cache_hits).sum();
761 let results: usize = queries.iter().map(|s| s.entry_count).sum();
762 println!("\nQuery cache hit rate: {}", hits as f64 / (hits + results) as f64);
765 let mut query_key_sizes = queries.clone();
766 query_key_sizes.sort_by_key(|q| q.key_size);
767 println!("\nLarge query keys:");
768 for q in query_key_sizes.iter().rev()
769 .filter(|q| q.key_size > 8) {
771 " {} - {} x {} - {}",
779 let mut query_value_sizes = queries.clone();
780 query_value_sizes.sort_by_key(|q| q.value_size);
781 println!("\nLarge query values:");
782 for q in query_value_sizes.iter().rev()
783 .filter(|q| q.value_size > 8) {
785 " {} - {} x {} - {}",
793 if cfg!(debug_assertions) {
794 let mut query_cache_hits = queries.clone();
795 query_cache_hits.sort_by_key(|q| q.cache_hits);
796 println!("\nQuery cache hits:");
797 for q in query_cache_hits.iter().rev() {
802 q.cache_hits as f64 / (q.cache_hits + q.entry_count) as f64
807 let mut query_value_count = queries.clone();
808 query_value_count.sort_by_key(|q| q.entry_count);
809 println!("\nQuery value count:");
810 for q in query_value_count.iter().rev() {
811 println!(" {} - {}", q.name, q.entry_count);
816 #[allow(nonstandard_style)]
817 #[derive(Clone, Copy)]
822 impl rustc_data_structures::profiling::QueryName for QueryName {
823 fn discriminant(self) -> std::mem::Discriminant<QueryName> {
824 std::mem::discriminant(&self)
827 fn as_str(self) -> &'static str {
828 QueryName::as_str(&self)
833 pub fn register_with_profiler(
834 profiler: &rustc_data_structures::profiling::SelfProfiler,
836 $(profiler.register_query_name(QueryName::$name);)*
839 pub fn as_str(&self) -> &'static str {
841 $(QueryName::$name => stringify!($name),)*
846 #[allow(nonstandard_style)]
847 #[derive(Clone, Debug)]
848 pub enum Query<$tcx> {
849 $($(#[$attr])* $name($K)),*
852 impl<$tcx> Query<$tcx> {
853 pub fn name(&self) -> &'static str {
855 $(Query::$name(_) => stringify!($name),)*
859 pub fn describe(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
860 let (r, name) = match *self {
861 $(Query::$name(key) => {
862 (queries::$name::describe(tcx, key), stringify!($name))
865 if tcx.sess.verbose() {
866 format!("{} [{}]", r, name).into()
872 // FIXME(eddyb) Get more valid `Span`s on queries.
873 pub fn default_span(&self, tcx: TyCtxt<$tcx>, span: Span) -> Span {
874 if !span.is_dummy() {
877 // The `def_span` query is used to calculate `default_span`,
878 // so exit to avoid infinite recursion.
879 if let Query::def_span(..) = *self {
883 $(Query::$name(key) => key.default_span(tcx),)*
887 pub fn query_name(&self) -> QueryName {
889 $(Query::$name(_) => QueryName::$name,)*
894 impl<'a, $tcx> HashStable<StableHashingContext<'a>> for Query<$tcx> {
895 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
896 mem::discriminant(self).hash_stable(hcx, hasher);
898 $(Query::$name(key) => key.hash_stable(hcx, hasher),)*
904 use std::marker::PhantomData;
906 $(#[allow(nonstandard_style)]
907 pub struct $name<$tcx> {
908 data: PhantomData<&$tcx ()>
912 // This module and the functions in it exist only to provide a
913 // predictable symbol name prefix for query providers. This is helpful
914 // for analyzing queries in profilers.
915 pub(super) mod __query_compute {
917 pub fn $name<F: FnOnce() -> R, R>(f: F) -> R {
922 $(impl<$tcx> QueryConfig<$tcx> for queries::$name<$tcx> {
926 const NAME: QueryName = QueryName::$name;
927 const CATEGORY: ProfileCategory = $category;
930 impl<$tcx> QueryAccessors<$tcx> for queries::$name<$tcx> {
931 const ANON: bool = is_anon!([$($modifiers)*]);
932 const EVAL_ALWAYS: bool = is_eval_always!([$($modifiers)*]);
935 fn query(key: Self::Key) -> Query<'tcx> {
940 fn query_cache<'a>(tcx: TyCtxt<$tcx>) -> &'a Sharded<QueryCache<$tcx, Self>> {
946 fn to_dep_node(tcx: TyCtxt<$tcx>, key: &Self::Key) -> DepNode {
947 use crate::dep_graph::DepConstructor::*;
949 DepNode::new(tcx, $node(*key))
953 fn dep_kind() -> dep_graph::DepKind {
954 dep_graph::DepKind::$node
958 fn compute(tcx: TyCtxt<'tcx>, key: Self::Key) -> Self::Value {
959 __query_compute::$name(move || {
960 let provider = tcx.queries.providers.get(key.query_crate())
961 // HACK(eddyb) it's possible crates may be loaded after
962 // the query engine is created, and because crate loading
963 // is not yet integrated with the query engine, such crates
964 // would be missing appropriate entries in `providers`.
965 .unwrap_or(&tcx.queries.fallback_extern_providers)
972 _hcx: &mut StableHashingContext<'_>,
973 _result: &Self::Value
974 ) -> Option<Fingerprint> {
975 hash_result!([$($modifiers)*][_hcx, _result])
978 fn handle_cycle_error(
980 error: CycleError<'tcx>
982 handle_cycle_error!([$($modifiers)*][tcx, error])
986 #[derive(Copy, Clone)]
987 pub struct TyCtxtEnsure<'tcx> {
988 pub tcx: TyCtxt<'tcx>,
991 impl TyCtxtEnsure<$tcx> {
994 pub fn $name(self, key: $K) {
995 self.tcx.ensure_query::<queries::$name<'_>>(key)
999 #[derive(Copy, Clone)]
1000 pub struct TyCtxtAt<'tcx> {
1001 pub tcx: TyCtxt<'tcx>,
1005 impl Deref for TyCtxtAt<'tcx> {
1006 type Target = TyCtxt<'tcx>;
1008 fn deref(&self) -> &Self::Target {
1014 /// Returns a transparent wrapper for `TyCtxt`, which ensures queries
1015 /// are executed instead of just returing their results.
1017 pub fn ensure(self) -> TyCtxtEnsure<$tcx> {
1023 /// Returns a transparent wrapper for `TyCtxt` which uses
1024 /// `span` as the location of queries performed through it.
1026 pub fn at(self, span: Span) -> TyCtxtAt<$tcx> {
1035 pub fn $name(self, key: $K) -> $V {
1036 self.at(DUMMY_SP).$name(key)
1040 impl TyCtxtAt<$tcx> {
1043 pub fn $name(self, key: $K) -> $V {
1044 self.tcx.get_query::<queries::$name<'_>>(self.span, key)
1048 define_provider_struct! {
1050 input: ($(([$($modifiers)*] [$name] [$K] [$V]))*)
1053 impl<$tcx> Copy for Providers<$tcx> {}
1054 impl<$tcx> Clone for Providers<$tcx> {
1055 fn clone(&self) -> Self { *self }
1060 macro_rules! define_queries_struct {
1062 input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
1063 pub struct Queries<$tcx> {
1064 /// This provides access to the incrimental comilation on-disk cache for query results.
1065 /// Do not access this directly. It is only meant to be used by
1066 /// `DepGraph::try_mark_green()` and the query infrastructure.
1067 pub(crate) on_disk_cache: OnDiskCache<'tcx>,
1069 providers: IndexVec<CrateNum, Providers<$tcx>>,
1070 fallback_extern_providers: Box<Providers<$tcx>>,
1072 $($(#[$attr])* $name: Sharded<QueryCache<$tcx, queries::$name<$tcx>>>,)*
1077 macro_rules! define_provider_struct {
1079 input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
1080 pub struct Providers<$tcx> {
1081 $(pub $name: fn(TyCtxt<$tcx>, $K) -> $R,)*
1084 impl<$tcx> Default for Providers<$tcx> {
1085 fn default() -> Self {
1086 $(fn $name<$tcx>(_: TyCtxt<$tcx>, key: $K) -> $R {
1087 bug!("`tcx.{}({:?})` unsupported by its crate",
1088 stringify!($name), key);
1090 Providers { $($name),* }
1096 /// The red/green evaluation system will try to mark a specific DepNode in the
1097 /// dependency graph as green by recursively trying to mark the dependencies of
1098 /// that `DepNode` as green. While doing so, it will sometimes encounter a `DepNode`
1099 /// where we don't know if it is red or green and we therefore actually have
1100 /// to recompute its value in order to find out. Since the only piece of
1101 /// information that we have at that point is the `DepNode` we are trying to
1102 /// re-evaluate, we need some way to re-run a query from just that. This is what
1103 /// `force_from_dep_node()` implements.
1105 /// In the general case, a `DepNode` consists of a `DepKind` and an opaque
1106 /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
1107 /// is usually constructed by computing a stable hash of the query-key that the
1108 /// `DepNode` corresponds to. Consequently, it is not in general possible to go
1109 /// back from hash to query-key (since hash functions are not reversible). For
1110 /// this reason `force_from_dep_node()` is expected to fail from time to time
1111 /// because we just cannot find out, from the `DepNode` alone, what the
1112 /// corresponding query-key is and therefore cannot re-run the query.
1114 /// The system deals with this case letting `try_mark_green` fail which forces
1115 /// the root query to be re-evaluated.
1117 /// Now, if `force_from_dep_node()` would always fail, it would be pretty useless.
1118 /// Fortunately, we can use some contextual information that will allow us to
1119 /// reconstruct query-keys for certain kinds of `DepNode`s. In particular, we
1120 /// enforce by construction that the GUID/fingerprint of certain `DepNode`s is a
1121 /// valid `DefPathHash`. Since we also always build a huge table that maps every
1122 /// `DefPathHash` in the current codebase to the corresponding `DefId`, we have
1123 /// everything we need to re-run the query.
1125 /// Take the `mir_validated` query as an example. Like many other queries, it
1126 /// just has a single parameter: the `DefId` of the item it will compute the
1127 /// validated MIR for. Now, when we call `force_from_dep_node()` on a `DepNode`
1128 /// with kind `MirValidated`, we know that the GUID/fingerprint of the `DepNode`
1129 /// is actually a `DefPathHash`, and can therefore just look up the corresponding
1130 /// `DefId` in `tcx.def_path_hash_to_def_id`.
1132 /// When you implement a new query, it will likely have a corresponding new
1133 /// `DepKind`, and you'll have to support it here in `force_from_dep_node()`. As
1134 /// a rule of thumb, if your query takes a `DefId` or `DefIndex` as sole parameter,
1135 /// then `force_from_dep_node()` should not fail for it. Otherwise, you can just
1136 /// add it to the "We don't have enough information to reconstruct..." group in
1137 /// the match below.
1138 pub fn force_from_dep_node(tcx: TyCtxt<'_>, dep_node: &DepNode) -> bool {
1139 use crate::dep_graph::RecoverKey;
1141 // We must avoid ever having to call `force_from_dep_node()` for a
1142 // `DepNode::codegen_unit`:
1143 // Since we cannot reconstruct the query key of a `DepNode::codegen_unit`, we
1144 // would always end up having to evaluate the first caller of the
1145 // `codegen_unit` query that *is* reconstructible. This might very well be
1146 // the `compile_codegen_unit` query, thus re-codegenning the whole CGU just
1147 // to re-trigger calling the `codegen_unit` query with the right key. At
1148 // that point we would already have re-done all the work we are trying to
1149 // avoid doing in the first place.
1150 // The solution is simple: Just explicitly call the `codegen_unit` query for
1151 // each CGU, right after partitioning. This way `try_mark_green` will always
1152 // hit the cache instead of having to go through `force_from_dep_node`.
1153 // This assertion makes sure, we actually keep applying the solution above.
1155 dep_node.kind != DepKind::codegen_unit,
1156 "calling force_from_dep_node() on DepKind::codegen_unit"
1159 if !dep_node.kind.can_reconstruct_query_key() {
1163 rustc_dep_node_force!([dep_node, tcx]
1164 // These are inputs that are expected to be pre-allocated and that
1165 // should therefore always be red or green already.
1166 DepKind::AllLocalTraitImpls |
1168 DepKind::CrateMetadata |
1172 // These are anonymous nodes.
1173 DepKind::TraitSelect |
1175 // We don't have enough information to reconstruct the query key of
1177 DepKind::CompileCodegenUnit => {
1178 bug!("force_from_dep_node: encountered {:?}", dep_node)
1181 DepKind::Analysis => {
1182 let def_id = if let Some(def_id) = dep_node.extract_def_id(tcx) {
1185 // Return from the whole function.
1188 tcx.force_query::<crate::ty::query::queries::analysis<'_>>(