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 #[cfg(parallel_compiler)]
17 use rustc_data_structures::profiling::TimingGuard;
18 use rustc_data_structures::sharded::Sharded;
19 use rustc_data_structures::sync::{Lock, Lrc};
20 use rustc_data_structures::thin_vec::ThinVec;
21 use rustc_span::source_map::DUMMY_SP;
23 use std::collections::hash_map::Entry;
24 use std::hash::{Hash, Hasher};
28 use rustc_error_codes::*;
30 pub struct QueryCache<'tcx, D: QueryConfig<'tcx> + ?Sized> {
31 pub(super) results: FxHashMap<D::Key, QueryValue<D::Value>>,
32 pub(super) active: FxHashMap<D::Key, QueryResult<'tcx>>,
33 #[cfg(debug_assertions)]
34 pub(super) cache_hits: usize,
37 pub(super) struct QueryValue<T> {
39 pub(super) index: DepNodeIndex,
42 impl<T> QueryValue<T> {
43 pub(super) fn new(value: T, dep_node_index: DepNodeIndex) -> QueryValue<T> {
44 QueryValue { value, index: dep_node_index }
48 /// Indicates the state of a query for a given key in a query map.
49 pub(super) enum QueryResult<'tcx> {
50 /// An already executing query. The query job can be used to await for its completion.
51 Started(Lrc<QueryJob<'tcx>>),
53 /// The query panicked. Queries trying to wait on this will raise a fatal error or
58 impl<'tcx, M: QueryConfig<'tcx>> Default for QueryCache<'tcx, M> {
59 fn default() -> QueryCache<'tcx, M> {
61 results: FxHashMap::default(),
62 active: FxHashMap::default(),
63 #[cfg(debug_assertions)]
69 /// A type representing the responsibility to execute the job in the `job` field.
70 /// This will poison the relevant query if dropped.
71 pub(super) struct JobOwner<'a, 'tcx, Q: QueryDescription<'tcx>> {
72 cache: &'a Sharded<QueryCache<'tcx, Q>>,
74 job: Lrc<QueryJob<'tcx>>,
77 impl<'a, 'tcx, Q: QueryDescription<'tcx>> JobOwner<'a, 'tcx, Q> {
78 /// Either gets a `JobOwner` corresponding the query, allowing us to
79 /// start executing the query, or returns with the result of the query.
80 /// If the query is executing elsewhere, this will wait for it.
81 /// If the query panicked, this will silently panic.
83 /// This function is inlined because that results in a noticeable speed-up
84 /// for some compile-time benchmarks.
86 pub(super) fn try_get(tcx: TyCtxt<'tcx>, span: Span, key: &Q::Key) -> TryGetJob<'a, 'tcx, Q> {
87 // Handling the `query_blocked_prof_timer` is a bit weird because of the
88 // control flow in this function: Blocking is implemented by
89 // awaiting a running job and, once that is done, entering the loop below
90 // again from the top. In that second iteration we will hit the
91 // cache which provides us with the information we need for
92 // finishing the "query-blocked" event.
94 // We thus allocate `query_blocked_prof_timer` outside the loop,
95 // initialize it during the first iteration and finish it during the
97 #[cfg(parallel_compiler)]
98 let mut query_blocked_prof_timer: Option<TimingGuard<'_>> = None;
100 let cache = Q::query_cache(tcx);
102 // We compute the key's hash once and then use it for both the
103 // shard lookup and the hashmap lookup. This relies on the fact
104 // that both of them use `FxHasher`.
105 let mut state = FxHasher::default();
106 key.hash(&mut state);
107 let key_hash = state.finish();
109 let mut lock = cache.get_shard_by_hash(key_hash).lock();
110 if let Some((_, value)) =
111 lock.results.raw_entry().from_key_hashed_nocheck(key_hash, key)
113 if unlikely!(tcx.prof.enabled()) {
114 tcx.prof.query_cache_hit(value.index.into());
116 #[cfg(parallel_compiler)]
118 if let Some(prof_timer) = query_blocked_prof_timer.take() {
119 prof_timer.finish_with_query_invocation_id(value.index.into());
124 let result = (value.value.clone(), value.index);
125 #[cfg(debug_assertions)]
127 lock.cache_hits += 1;
129 return TryGetJob::JobCompleted(result);
132 let job = match lock.active.entry((*key).clone()) {
133 Entry::Occupied(entry) => {
135 QueryResult::Started(ref job) => {
136 // For parallel queries, we'll block and wait until the query running
137 // in another thread has completed. Record how long we wait in the
139 #[cfg(parallel_compiler)]
141 query_blocked_prof_timer = Some(tcx.prof.query_blocked());
146 QueryResult::Poisoned => FatalError.raise(),
149 Entry::Vacant(entry) => {
150 // No job entry for this query. Return a new one to be started later.
151 return tls::with_related_context(tcx, |icx| {
152 // Create the `parent` variable before `info`. This allows LLVM
153 // to elide the move of `info`
154 let parent = icx.query.clone();
155 let info = QueryInfo { span, query: Q::query(key.clone()) };
156 let job = Lrc::new(QueryJob::new(info, parent));
157 let owner = JobOwner { cache, job: job.clone(), key: (*key).clone() };
158 entry.insert(QueryResult::Started(job));
159 TryGetJob::NotYetStarted(owner)
165 // If we are single-threaded we know that we have cycle error,
166 // so we just return the error.
167 #[cfg(not(parallel_compiler))]
168 return TryGetJob::Cycle(cold_path(|| {
169 Q::handle_cycle_error(tcx, job.find_cycle_in_stack(tcx, span))
172 // With parallel queries we might just have to wait on some other
174 #[cfg(parallel_compiler)]
176 let result = job.r#await(tcx, span);
178 if let Err(cycle) = result {
179 return TryGetJob::Cycle(Q::handle_cycle_error(tcx, cycle));
185 /// Completes the query by updating the query cache with the `result`,
186 /// signals the waiter and forgets the JobOwner, so it won't poison the query
188 pub(super) fn complete(self, result: &Q::Value, dep_node_index: DepNodeIndex) {
189 // We can move out of `self` here because we `mem::forget` it below
190 let key = unsafe { ptr::read(&self.key) };
191 let job = unsafe { ptr::read(&self.job) };
192 let cache = self.cache;
194 // Forget ourself so our destructor won't poison the query
197 let value = QueryValue::new(result.clone(), dep_node_index);
199 let mut lock = cache.get_shard_by_value(&key).lock();
200 lock.active.remove(&key);
201 lock.results.insert(key, value);
204 job.signal_complete();
209 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
211 F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R,
213 let diagnostics = Lock::new(ThinVec::new());
214 let result = f(Some(&diagnostics));
215 (result, diagnostics.into_inner())
218 impl<'a, 'tcx, Q: QueryDescription<'tcx>> Drop for JobOwner<'a, 'tcx, Q> {
222 // Poison the query so jobs waiting on it panic.
223 let shard = self.cache.get_shard_by_value(&self.key);
224 shard.lock().active.insert(self.key.clone(), QueryResult::Poisoned);
225 // Also signal the completion of the job, so waiters
226 // will continue execution.
227 self.job.signal_complete();
232 pub struct CycleError<'tcx> {
233 /// The query and related span that uses the cycle.
234 pub(super) usage: Option<(Span, Query<'tcx>)>,
235 pub(super) cycle: Vec<QueryInfo<'tcx>>,
238 /// The result of `try_get_lock`.
239 pub(super) enum TryGetJob<'a, 'tcx, D: QueryDescription<'tcx>> {
240 /// The query is not yet started. Contains a guard to the cache eventually used to start it.
241 NotYetStarted(JobOwner<'a, 'tcx, D>),
243 /// The query was already completed.
244 /// Returns the result of the query and its dep-node index
245 /// if it succeeded or a cycle error if it failed.
246 JobCompleted((D::Value, DepNodeIndex)),
248 /// Trying to execute the query resulted in a cycle.
252 impl<'tcx> TyCtxt<'tcx> {
253 /// Executes a job by changing the `ImplicitCtxt` to point to the
254 /// new query job while it executes. It returns the diagnostics
255 /// captured during execution and the actual result.
257 pub(super) fn start_query<F, R>(
259 job: Lrc<QueryJob<'tcx>>,
260 diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
264 F: FnOnce(TyCtxt<'tcx>) -> R,
266 // The `TyCtxt` stored in TLS has the same global interner lifetime
267 // as `self`, so we use `with_related_context` to relate the 'tcx lifetimes
268 // when accessing the `ImplicitCtxt`.
269 tls::with_related_context(self, move |current_icx| {
270 // Update the `ImplicitCtxt` to point to our new query job.
271 let new_icx = tls::ImplicitCtxt {
275 layout_depth: current_icx.layout_depth,
276 task_deps: current_icx.task_deps,
279 // Use the `ImplicitCtxt` while we execute the query.
280 tls::enter_context(&new_icx, |_| compute(self))
286 pub(super) fn report_cycle(
288 CycleError { usage, cycle: stack }: CycleError<'tcx>,
289 ) -> DiagnosticBuilder<'tcx> {
290 assert!(!stack.is_empty());
292 let fix_span = |span: Span, query: &Query<'tcx>| {
293 self.sess.source_map().def_span(query.default_span(self, span))
296 // Disable naming impls with types in this path, since that
297 // sometimes cycles itself, leading to extra cycle errors.
298 // (And cycle errors around impls tend to occur during the
299 // collect/coherence phases anyhow.)
300 ty::print::with_forced_impl_filename_line(|| {
301 let span = fix_span(stack[1 % stack.len()].span, &stack[0].query);
302 let mut err = struct_span_err!(
306 "cycle detected when {}",
307 stack[0].query.describe(self)
310 for i in 1..stack.len() {
311 let query = &stack[i].query;
312 let span = fix_span(stack[(i + 1) % stack.len()].span, query);
313 err.span_note(span, &format!("...which requires {}...", query.describe(self)));
317 "...which again requires {}, completing the cycle",
318 stack[0].query.describe(self)
321 if let Some((span, query)) = usage {
323 fix_span(span, &query),
324 &format!("cycle used when {}", query.describe(self)),
332 pub fn try_print_query_stack(handler: &Handler) {
333 eprintln!("query stack during panic:");
335 // Be careful reyling on global state here: this code is called from
336 // a panic hook, which means that the global `Handler` may be in a weird
337 // state if it was responsible for triggering the panic.
338 tls::with_context_opt(|icx| {
339 if let Some(icx) = icx {
340 let mut current_query = icx.query.clone();
343 while let Some(query) = current_query {
344 let mut diag = Diagnostic::new(
349 query.info.query.name(),
350 query.info.query.describe(icx.tcx)
353 diag.span = icx.tcx.sess.source_map().def_span(query.info.span).into();
354 handler.force_print_diagnostic(diag);
356 current_query = query.parent.clone();
362 eprintln!("end of query stack");
366 pub(super) fn get_query<Q: QueryDescription<'tcx>>(self, span: Span, key: Q::Key) -> Q::Value {
367 debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME, key, span);
369 let job = match JobOwner::try_get(self, span, &key) {
370 TryGetJob::NotYetStarted(job) => job,
371 TryGetJob::Cycle(result) => return result,
372 TryGetJob::JobCompleted((v, index)) => {
373 self.dep_graph.read_index(index);
378 // Fast path for when incr. comp. is off. `to_dep_node` is
379 // expensive for some `DepKind`s.
380 if !self.dep_graph.is_fully_enabled() {
381 let null_dep_node = DepNode::new_no_params(crate::dep_graph::DepKind::Null);
382 return self.force_query_with_job::<Q>(key, job, null_dep_node).0;
386 let prof_timer = self.prof.query_provider();
388 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
389 self.start_query(job.job.clone(), diagnostics, |tcx| {
390 tcx.dep_graph.with_anon_task(Q::dep_kind(), || Q::compute(tcx, key))
394 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
396 self.dep_graph.read_index(dep_node_index);
398 if unlikely!(!diagnostics.is_empty()) {
401 .store_diagnostics_for_anon_node(dep_node_index, diagnostics);
404 job.complete(&result, dep_node_index);
409 let dep_node = Q::to_dep_node(self, &key);
412 // The diagnostics for this query will be
413 // promoted to the current session during
414 // `try_mark_green()`, so we can ignore them here.
415 let loaded = self.start_query(job.job.clone(), None, |tcx| {
416 let marked = tcx.dep_graph.try_mark_green_and_read(tcx, &dep_node);
417 marked.map(|(prev_dep_node_index, dep_node_index)| {
419 tcx.load_from_disk_and_cache_in_memory::<Q>(
429 if let Some((result, dep_node_index)) = loaded {
430 job.complete(&result, dep_node_index);
435 let (result, dep_node_index) = self.force_query_with_job::<Q>(key, job, dep_node);
436 self.dep_graph.read_index(dep_node_index);
440 fn load_from_disk_and_cache_in_memory<Q: QueryDescription<'tcx>>(
443 prev_dep_node_index: SerializedDepNodeIndex,
444 dep_node_index: DepNodeIndex,
447 // Note this function can be called concurrently from the same query
448 // We must ensure that this is handled correctly.
450 debug_assert!(self.dep_graph.is_green(dep_node));
452 // First we try to load the result from the on-disk cache.
453 let result = if Q::cache_on_disk(self, key.clone(), None)
454 && self.sess.opts.debugging_opts.incremental_queries
456 let prof_timer = self.prof.incr_cache_loading();
457 let result = Q::try_load_from_disk(self, prev_dep_node_index);
458 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
460 // We always expect to find a cached result for things that
461 // can be forced from `DepNode`.
463 !dep_node.kind.can_reconstruct_query_key() || result.is_some(),
464 "missing on-disk cache entry for {:?}",
469 // Some things are never cached on disk.
473 let result = if let Some(result) = result {
476 // We could not load a result from the on-disk cache, so
478 let prof_timer = self.prof.query_provider();
480 // The dep-graph for this computation is already in-place.
481 let result = self.dep_graph.with_ignore(|| Q::compute(self, key));
483 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
488 // If `-Zincremental-verify-ich` is specified, re-hash results from
489 // the cache and make sure that they have the expected fingerprint.
490 if unlikely!(self.sess.opts.debugging_opts.incremental_verify_ich) {
491 self.incremental_verify_ich::<Q>(&result, dep_node, dep_node_index);
499 fn incremental_verify_ich<Q: QueryDescription<'tcx>>(
503 dep_node_index: DepNodeIndex,
505 use crate::ich::Fingerprint;
508 Some(self.dep_graph.fingerprint_of(dep_node_index))
509 == self.dep_graph.prev_fingerprint_of(dep_node),
510 "fingerprint for green query instance not loaded from cache: {:?}",
514 debug!("BEGIN verify_ich({:?})", dep_node);
515 let mut hcx = self.create_stable_hashing_context();
517 let new_hash = Q::hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
518 debug!("END verify_ich({:?})", dep_node);
520 let old_hash = self.dep_graph.fingerprint_of(dep_node_index);
522 assert!(new_hash == old_hash, "found unstable fingerprints for {:?}", dep_node,);
526 fn force_query_with_job<Q: QueryDescription<'tcx>>(
529 job: JobOwner<'_, 'tcx, Q>,
531 ) -> (Q::Value, DepNodeIndex) {
532 // If the following assertion triggers, it can have two reasons:
533 // 1. Something is wrong with DepNode creation, either here or
534 // in `DepGraph::try_mark_green()`.
535 // 2. Two distinct query keys get mapped to the same `DepNode`
536 // (see for example #48923).
538 !self.dep_graph.dep_node_exists(&dep_node),
539 "forcing query with already existing `DepNode`\n\
546 let prof_timer = self.prof.query_provider();
548 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
549 self.start_query(job.job.clone(), diagnostics, |tcx| {
551 tcx.dep_graph.with_eval_always_task(
559 tcx.dep_graph.with_task(dep_node, tcx, key, Q::compute, Q::hash_result)
564 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
566 if unlikely!(!diagnostics.is_empty()) {
567 if dep_node.kind != crate::dep_graph::DepKind::Null {
568 self.queries.on_disk_cache.store_diagnostics(dep_node_index, diagnostics);
572 job.complete(&result, dep_node_index);
574 (result, dep_node_index)
577 /// Ensure that either this query has all green inputs or been executed.
578 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
580 /// This function is particularly useful when executing passes for their
581 /// side-effects -- e.g., in order to report errors for erroneous programs.
583 /// Note: The optimization is only available during incr. comp.
584 pub(super) fn ensure_query<Q: QueryDescription<'tcx>>(self, key: Q::Key) -> () {
586 let _ = self.get_query::<Q>(DUMMY_SP, key);
590 // Ensuring an anonymous query makes no sense
593 let dep_node = Q::to_dep_node(self, &key);
595 match self.dep_graph.try_mark_green_and_read(self, &dep_node) {
597 // A None return from `try_mark_green_and_read` means that this is either
598 // a new dep node or that the dep node has already been marked red.
599 // Either way, we can't call `dep_graph.read()` as we don't have the
600 // DepNodeIndex. We must invoke the query itself. The performance cost
601 // this introduces should be negligible as we'll immediately hit the
602 // in-memory cache, or another query down the line will.
603 let _ = self.get_query::<Q>(DUMMY_SP, key);
605 Some((_, dep_node_index)) => {
606 self.prof.query_cache_hit(dep_node_index.into());
612 fn force_query<Q: QueryDescription<'tcx>>(self, key: Q::Key, span: Span, dep_node: DepNode) {
613 // We may be concurrently trying both execute and force a query.
614 // Ensure that only one of them runs the query.
615 let job = match JobOwner::try_get(self, span, &key) {
616 TryGetJob::NotYetStarted(job) => job,
617 TryGetJob::Cycle(_) | TryGetJob::JobCompleted(_) => return,
619 self.force_query_with_job::<Q>(key, job, dep_node);
623 macro_rules! handle_cycle_error {
624 ([][$tcx: expr, $error:expr]) => {{
625 $tcx.report_cycle($error).emit();
626 Value::from_cycle_error($tcx)
628 ([fatal_cycle$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
629 $tcx.report_cycle($error).emit();
630 $tcx.sess.abort_if_errors();
633 ([cycle_delay_bug$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
634 $tcx.report_cycle($error).delay_as_bug();
635 Value::from_cycle_error($tcx)
637 ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
638 handle_cycle_error!([$($modifiers),*][$($args)*])
642 macro_rules! is_anon {
646 ([anon$(, $modifiers:ident)*]) => {{
649 ([$other:ident$(, $modifiers:ident)*]) => {
650 is_anon!([$($modifiers),*])
654 macro_rules! is_eval_always {
658 ([eval_always$(, $modifiers:ident)*]) => {{
661 ([$other:ident$(, $modifiers:ident)*]) => {
662 is_eval_always!([$($modifiers),*])
666 macro_rules! hash_result {
667 ([][$hcx:expr, $result:expr]) => {{
668 dep_graph::hash_result($hcx, &$result)
670 ([no_hash$(, $modifiers:ident)*][$hcx:expr, $result:expr]) => {{
673 ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
674 hash_result!([$($modifiers),*][$($args)*])
678 macro_rules! define_queries {
679 (<$tcx:tt> $($category:tt {
680 $($(#[$attr:meta])* [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*
682 define_queries_inner! { <$tcx>
683 $($( $(#[$attr])* category<$category> [$($modifiers)*] fn $name: $node($K) -> $V,)*)*
688 macro_rules! define_queries_inner {
690 $($(#[$attr:meta])* category<$category:tt>
691 [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
694 use rustc_data_structures::sharded::Sharded;
696 rustc_data_structures::stable_hasher::HashStable,
697 rustc_data_structures::stable_hasher::StableHasher,
698 ich::StableHashingContext
700 use rustc_data_structures::profiling::ProfileCategory;
702 define_queries_struct! {
704 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
707 impl<$tcx> Queries<$tcx> {
709 providers: IndexVec<CrateNum, Providers<$tcx>>,
710 fallback_extern_providers: Providers<$tcx>,
711 on_disk_cache: OnDiskCache<'tcx>,
715 fallback_extern_providers: Box::new(fallback_extern_providers),
717 $($name: Default::default()),*
721 #[cfg(parallel_compiler)]
722 pub fn collect_active_jobs(&self) -> Vec<Lrc<QueryJob<$tcx>>> {
723 let mut jobs = Vec::new();
725 // We use try_lock_shards here since we are only called from the
726 // deadlock handler, and this shouldn't be locked.
728 let shards = self.$name.try_lock_shards().unwrap();
729 jobs.extend(shards.iter().flat_map(|shard| shard.active.values().filter_map(|v|
730 if let QueryResult::Started(ref job) = *v {
741 pub fn print_stats(&self) {
742 let mut queries = Vec::new();
749 key_type: &'static str,
751 value_type: &'static str,
755 fn stats<'tcx, Q: QueryConfig<'tcx>>(
757 map: &Sharded<QueryCache<'tcx, Q>>,
759 let map = map.lock_shards();
762 #[cfg(debug_assertions)]
763 cache_hits: map.iter().map(|shard| shard.cache_hits).sum(),
764 #[cfg(not(debug_assertions))]
766 key_size: mem::size_of::<Q::Key>(),
767 key_type: type_name::<Q::Key>(),
768 value_size: mem::size_of::<Q::Value>(),
769 value_type: type_name::<Q::Value>(),
770 entry_count: map.iter().map(|shard| shard.results.len()).sum(),
775 queries.push(stats::<queries::$name<'_>>(
781 if cfg!(debug_assertions) {
782 let hits: usize = queries.iter().map(|s| s.cache_hits).sum();
783 let results: usize = queries.iter().map(|s| s.entry_count).sum();
784 println!("\nQuery cache hit rate: {}", hits as f64 / (hits + results) as f64);
787 let mut query_key_sizes = queries.clone();
788 query_key_sizes.sort_by_key(|q| q.key_size);
789 println!("\nLarge query keys:");
790 for q in query_key_sizes.iter().rev()
791 .filter(|q| q.key_size > 8) {
793 " {} - {} x {} - {}",
801 let mut query_value_sizes = queries.clone();
802 query_value_sizes.sort_by_key(|q| q.value_size);
803 println!("\nLarge query values:");
804 for q in query_value_sizes.iter().rev()
805 .filter(|q| q.value_size > 8) {
807 " {} - {} x {} - {}",
815 if cfg!(debug_assertions) {
816 let mut query_cache_hits = queries.clone();
817 query_cache_hits.sort_by_key(|q| q.cache_hits);
818 println!("\nQuery cache hits:");
819 for q in query_cache_hits.iter().rev() {
824 q.cache_hits as f64 / (q.cache_hits + q.entry_count) as f64
829 let mut query_value_count = queries.clone();
830 query_value_count.sort_by_key(|q| q.entry_count);
831 println!("\nQuery value count:");
832 for q in query_value_count.iter().rev() {
833 println!(" {} - {}", q.name, q.entry_count);
838 #[allow(nonstandard_style)]
839 #[derive(Clone, Debug)]
840 pub enum Query<$tcx> {
841 $($(#[$attr])* $name($K)),*
844 impl<$tcx> Query<$tcx> {
845 pub fn name(&self) -> &'static str {
847 $(Query::$name(_) => stringify!($name),)*
851 pub fn describe(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
852 let (r, name) = match *self {
853 $(Query::$name(key) => {
854 (queries::$name::describe(tcx, key), stringify!($name))
857 if tcx.sess.verbose() {
858 format!("{} [{}]", r, name).into()
864 // FIXME(eddyb) Get more valid `Span`s on queries.
865 pub fn default_span(&self, tcx: TyCtxt<$tcx>, span: Span) -> Span {
866 if !span.is_dummy() {
869 // The `def_span` query is used to calculate `default_span`,
870 // so exit to avoid infinite recursion.
871 if let Query::def_span(..) = *self {
875 $(Query::$name(key) => key.default_span(tcx),)*
880 impl<'a, $tcx> HashStable<StableHashingContext<'a>> for Query<$tcx> {
881 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
882 mem::discriminant(self).hash_stable(hcx, hasher);
884 $(Query::$name(key) => key.hash_stable(hcx, hasher),)*
890 use std::marker::PhantomData;
892 $(#[allow(nonstandard_style)]
893 pub struct $name<$tcx> {
894 data: PhantomData<&$tcx ()>
898 // This module and the functions in it exist only to provide a
899 // predictable symbol name prefix for query providers. This is helpful
900 // for analyzing queries in profilers.
901 pub(super) mod __query_compute {
903 pub fn $name<F: FnOnce() -> R, R>(f: F) -> R {
908 $(impl<$tcx> QueryConfig<$tcx> for queries::$name<$tcx> {
912 const NAME: &'static str = stringify!($name);
913 const CATEGORY: ProfileCategory = $category;
916 impl<$tcx> QueryAccessors<$tcx> for queries::$name<$tcx> {
917 const ANON: bool = is_anon!([$($modifiers)*]);
918 const EVAL_ALWAYS: bool = is_eval_always!([$($modifiers)*]);
921 fn query(key: Self::Key) -> Query<'tcx> {
926 fn query_cache<'a>(tcx: TyCtxt<$tcx>) -> &'a Sharded<QueryCache<$tcx, Self>> {
932 fn to_dep_node(tcx: TyCtxt<$tcx>, key: &Self::Key) -> DepNode {
933 use crate::dep_graph::DepConstructor::*;
935 DepNode::new(tcx, $node(*key))
939 fn dep_kind() -> dep_graph::DepKind {
940 dep_graph::DepKind::$node
944 fn compute(tcx: TyCtxt<'tcx>, key: Self::Key) -> Self::Value {
945 __query_compute::$name(move || {
946 let provider = tcx.queries.providers.get(key.query_crate())
947 // HACK(eddyb) it's possible crates may be loaded after
948 // the query engine is created, and because crate loading
949 // is not yet integrated with the query engine, such crates
950 // would be missing appropriate entries in `providers`.
951 .unwrap_or(&tcx.queries.fallback_extern_providers)
958 _hcx: &mut StableHashingContext<'_>,
959 _result: &Self::Value
960 ) -> Option<Fingerprint> {
961 hash_result!([$($modifiers)*][_hcx, _result])
964 fn handle_cycle_error(
966 error: CycleError<'tcx>
968 handle_cycle_error!([$($modifiers)*][tcx, error])
972 #[derive(Copy, Clone)]
973 pub struct TyCtxtEnsure<'tcx> {
974 pub tcx: TyCtxt<'tcx>,
977 impl TyCtxtEnsure<$tcx> {
980 pub fn $name(self, key: $K) {
981 self.tcx.ensure_query::<queries::$name<'_>>(key)
985 #[derive(Copy, Clone)]
986 pub struct TyCtxtAt<'tcx> {
987 pub tcx: TyCtxt<'tcx>,
991 impl Deref for TyCtxtAt<'tcx> {
992 type Target = TyCtxt<'tcx>;
994 fn deref(&self) -> &Self::Target {
1000 /// Returns a transparent wrapper for `TyCtxt`, which ensures queries
1001 /// are executed instead of just returing their results.
1003 pub fn ensure(self) -> TyCtxtEnsure<$tcx> {
1009 /// Returns a transparent wrapper for `TyCtxt` which uses
1010 /// `span` as the location of queries performed through it.
1012 pub fn at(self, span: Span) -> TyCtxtAt<$tcx> {
1021 pub fn $name(self, key: $K) -> $V {
1022 self.at(DUMMY_SP).$name(key)
1025 /// All self-profiling events generated by the query engine use
1026 /// virtual `StringId`s for their `event_id`. This method makes all
1027 /// those virtual `StringId`s point to actual strings.
1029 /// If we are recording only summary data, the ids will point to
1030 /// just the query names. If we are recording query keys too, we
1031 /// allocate the corresponding strings here.
1032 pub fn alloc_self_profile_query_strings(self) {
1033 use crate::ty::query::profiling_support::{
1034 alloc_self_profile_query_strings_for_query_cache,
1035 QueryKeyStringCache,
1038 if !self.prof.enabled() {
1042 let mut string_cache = QueryKeyStringCache::new();
1045 alloc_self_profile_query_strings_for_query_cache(
1048 &self.queries.$name,
1055 impl TyCtxtAt<$tcx> {
1058 pub fn $name(self, key: $K) -> $V {
1059 self.tcx.get_query::<queries::$name<'_>>(self.span, key)
1063 define_provider_struct! {
1065 input: ($(([$($modifiers)*] [$name] [$K] [$V]))*)
1068 impl<$tcx> Copy for Providers<$tcx> {}
1069 impl<$tcx> Clone for Providers<$tcx> {
1070 fn clone(&self) -> Self { *self }
1075 macro_rules! define_queries_struct {
1077 input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
1078 pub struct Queries<$tcx> {
1079 /// This provides access to the incrimental comilation on-disk cache for query results.
1080 /// Do not access this directly. It is only meant to be used by
1081 /// `DepGraph::try_mark_green()` and the query infrastructure.
1082 pub(crate) on_disk_cache: OnDiskCache<'tcx>,
1084 providers: IndexVec<CrateNum, Providers<$tcx>>,
1085 fallback_extern_providers: Box<Providers<$tcx>>,
1087 $($(#[$attr])* $name: Sharded<QueryCache<$tcx, queries::$name<$tcx>>>,)*
1092 macro_rules! define_provider_struct {
1094 input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
1095 pub struct Providers<$tcx> {
1096 $(pub $name: fn(TyCtxt<$tcx>, $K) -> $R,)*
1099 impl<$tcx> Default for Providers<$tcx> {
1100 fn default() -> Self {
1101 $(fn $name<$tcx>(_: TyCtxt<$tcx>, key: $K) -> $R {
1102 bug!("`tcx.{}({:?})` unsupported by its crate",
1103 stringify!($name), key);
1105 Providers { $($name),* }
1111 /// The red/green evaluation system will try to mark a specific DepNode in the
1112 /// dependency graph as green by recursively trying to mark the dependencies of
1113 /// that `DepNode` as green. While doing so, it will sometimes encounter a `DepNode`
1114 /// where we don't know if it is red or green and we therefore actually have
1115 /// to recompute its value in order to find out. Since the only piece of
1116 /// information that we have at that point is the `DepNode` we are trying to
1117 /// re-evaluate, we need some way to re-run a query from just that. This is what
1118 /// `force_from_dep_node()` implements.
1120 /// In the general case, a `DepNode` consists of a `DepKind` and an opaque
1121 /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
1122 /// is usually constructed by computing a stable hash of the query-key that the
1123 /// `DepNode` corresponds to. Consequently, it is not in general possible to go
1124 /// back from hash to query-key (since hash functions are not reversible). For
1125 /// this reason `force_from_dep_node()` is expected to fail from time to time
1126 /// because we just cannot find out, from the `DepNode` alone, what the
1127 /// corresponding query-key is and therefore cannot re-run the query.
1129 /// The system deals with this case letting `try_mark_green` fail which forces
1130 /// the root query to be re-evaluated.
1132 /// Now, if `force_from_dep_node()` would always fail, it would be pretty useless.
1133 /// Fortunately, we can use some contextual information that will allow us to
1134 /// reconstruct query-keys for certain kinds of `DepNode`s. In particular, we
1135 /// enforce by construction that the GUID/fingerprint of certain `DepNode`s is a
1136 /// valid `DefPathHash`. Since we also always build a huge table that maps every
1137 /// `DefPathHash` in the current codebase to the corresponding `DefId`, we have
1138 /// everything we need to re-run the query.
1140 /// Take the `mir_validated` query as an example. Like many other queries, it
1141 /// just has a single parameter: the `DefId` of the item it will compute the
1142 /// validated MIR for. Now, when we call `force_from_dep_node()` on a `DepNode`
1143 /// with kind `MirValidated`, we know that the GUID/fingerprint of the `DepNode`
1144 /// is actually a `DefPathHash`, and can therefore just look up the corresponding
1145 /// `DefId` in `tcx.def_path_hash_to_def_id`.
1147 /// When you implement a new query, it will likely have a corresponding new
1148 /// `DepKind`, and you'll have to support it here in `force_from_dep_node()`. As
1149 /// a rule of thumb, if your query takes a `DefId` or `DefIndex` as sole parameter,
1150 /// then `force_from_dep_node()` should not fail for it. Otherwise, you can just
1151 /// add it to the "We don't have enough information to reconstruct..." group in
1152 /// the match below.
1153 pub fn force_from_dep_node(tcx: TyCtxt<'_>, dep_node: &DepNode) -> bool {
1154 use crate::dep_graph::RecoverKey;
1156 // We must avoid ever having to call `force_from_dep_node()` for a
1157 // `DepNode::codegen_unit`:
1158 // Since we cannot reconstruct the query key of a `DepNode::codegen_unit`, we
1159 // would always end up having to evaluate the first caller of the
1160 // `codegen_unit` query that *is* reconstructible. This might very well be
1161 // the `compile_codegen_unit` query, thus re-codegenning the whole CGU just
1162 // to re-trigger calling the `codegen_unit` query with the right key. At
1163 // that point we would already have re-done all the work we are trying to
1164 // avoid doing in the first place.
1165 // The solution is simple: Just explicitly call the `codegen_unit` query for
1166 // each CGU, right after partitioning. This way `try_mark_green` will always
1167 // hit the cache instead of having to go through `force_from_dep_node`.
1168 // This assertion makes sure, we actually keep applying the solution above.
1170 dep_node.kind != DepKind::codegen_unit,
1171 "calling force_from_dep_node() on DepKind::codegen_unit"
1174 if !dep_node.kind.can_reconstruct_query_key() {
1178 rustc_dep_node_force!([dep_node, tcx]
1179 // These are inputs that are expected to be pre-allocated and that
1180 // should therefore always be red or green already.
1181 DepKind::AllLocalTraitImpls |
1183 DepKind::CrateMetadata |
1187 // These are anonymous nodes.
1188 DepKind::TraitSelect |
1190 // We don't have enough information to reconstruct the query key of
1192 DepKind::CompileCodegenUnit => {
1193 bug!("force_from_dep_node: encountered {:?}", dep_node)
1196 DepKind::Analysis => {
1197 let def_id = if let Some(def_id) = dep_node.extract_def_id(tcx) {
1200 // Return from the whole function.
1203 tcx.force_query::<crate::ty::query::queries::analysis<'_>>(