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::caches::QueryCache;
7 use crate::ty::query::config::{QueryContext, QueryDescription};
8 use crate::ty::query::job::{QueryInfo, QueryJob, QueryJobId, QueryJobInfo, QueryShardJobId};
9 use crate::ty::query::Query;
11 use crate::ty::{self, TyCtxt};
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, LockGuard};
18 use rustc_data_structures::thin_vec::ThinVec;
19 use rustc_errors::{struct_span_err, Diagnostic, DiagnosticBuilder, FatalError, Handler, Level};
20 use rustc_session::Session;
21 use rustc_span::def_id::DefId;
22 use rustc_span::source_map::DUMMY_SP;
24 use std::collections::hash_map::Entry;
25 use std::convert::TryFrom;
27 use std::hash::{Hash, Hasher};
29 use std::num::NonZeroU32;
31 #[cfg(debug_assertions)]
32 use std::sync::atomic::{AtomicUsize, Ordering};
34 pub(crate) struct QueryStateShard<CTX: QueryContext, K, C> {
36 active: FxHashMap<K, QueryResult<CTX>>,
38 /// Used to generate unique ids for active jobs.
42 impl<CTX: QueryContext, K, C> QueryStateShard<CTX, K, C> {
43 fn get_cache(&mut self) -> &mut C {
48 impl<CTX: QueryContext, K, C: Default> Default for QueryStateShard<CTX, K, C> {
49 fn default() -> QueryStateShard<CTX, K, C> {
50 QueryStateShard { cache: Default::default(), active: Default::default(), jobs: 0 }
54 pub(crate) struct QueryState<CTX: QueryContext, C: QueryCache<CTX>> {
56 shards: Sharded<QueryStateShard<CTX, C::Key, C::Sharded>>,
57 #[cfg(debug_assertions)]
58 pub(super) cache_hits: AtomicUsize,
61 impl<CTX: QueryContext, C: QueryCache<CTX>> QueryState<CTX, C> {
62 pub(super) fn get_lookup<K2: Hash>(
65 ) -> QueryLookup<'tcx, CTX, C::Key, C::Sharded> {
66 // We compute the key's hash once and then use it for both the
67 // shard lookup and the hashmap lookup. This relies on the fact
68 // that both of them use `FxHasher`.
69 let mut hasher = FxHasher::default();
70 key.hash(&mut hasher);
71 let key_hash = hasher.finish();
73 let shard = self.shards.get_shard_index_by_hash(key_hash);
74 let lock = self.shards.get_shard_by_index(shard).lock();
75 QueryLookup { key_hash, shard, lock }
79 /// Indicates the state of a query for a given key in a query map.
80 enum QueryResult<CTX: QueryContext> {
81 /// An already executing query. The query job can be used to await for its completion.
82 Started(QueryJob<CTX>),
84 /// The query panicked. Queries trying to wait on this will raise a fatal error which will
89 impl<CTX: QueryContext, C: QueryCache<CTX>> QueryState<CTX, C> {
90 pub(super) fn iter_results<R>(
92 f: impl for<'a> FnOnce(
93 Box<dyn Iterator<Item = (&'a C::Key, &'a C::Value, DepNodeIndex)> + 'a>,
96 self.cache.iter(&self.shards, |shard| &mut shard.cache, f)
98 pub(super) fn all_inactive(&self) -> bool {
99 let shards = self.shards.lock_shards();
100 shards.iter().all(|shard| shard.active.is_empty())
103 pub(super) fn try_collect_active_jobs(
106 make_query: fn(C::Key) -> CTX::Query,
107 jobs: &mut FxHashMap<QueryJobId, QueryJobInfo<CTX>>,
112 // We use try_lock_shards here since we are called from the
113 // deadlock handler, and this shouldn't be locked.
114 let shards = self.shards.try_lock_shards()?;
115 let shards = shards.iter().enumerate();
116 jobs.extend(shards.flat_map(|(shard_id, shard)| {
117 shard.active.iter().filter_map(move |(k, v)| {
118 if let QueryResult::Started(ref job) = *v {
120 QueryJobId { job: job.id, shard: u16::try_from(shard_id).unwrap(), kind };
121 let info = QueryInfo { span: job.span, query: make_query(k.clone()) };
122 Some((id, QueryJobInfo { info, job: job.clone() }))
133 impl<CTX: QueryContext, C: QueryCache<CTX>> Default for QueryState<CTX, C> {
134 fn default() -> QueryState<CTX, C> {
137 shards: Default::default(),
138 #[cfg(debug_assertions)]
139 cache_hits: AtomicUsize::new(0),
144 /// Values used when checking a query cache which can be reused on a cache-miss to execute the query.
145 pub(crate) struct QueryLookup<'tcx, CTX: QueryContext, K, C> {
146 pub(super) key_hash: u64,
148 pub(super) lock: LockGuard<'tcx, QueryStateShard<CTX, K, C>>,
151 /// A type representing the responsibility to execute the job in the `job` field.
152 /// This will poison the relevant query if dropped.
153 struct JobOwner<'tcx, CTX: QueryContext, C>
156 C::Key: Eq + Hash + Clone + Debug,
159 state: &'tcx QueryState<CTX, C>,
164 impl<'tcx, C> JobOwner<'tcx, TyCtxt<'tcx>, C>
166 C: QueryCache<TyCtxt<'tcx>> + 'tcx,
167 C::Key: Eq + Hash + Clone + Debug,
170 /// Either gets a `JobOwner` corresponding the query, allowing us to
171 /// start executing the query, or returns with the result of the query.
172 /// This function assumes that `try_get_cached` is already called and returned `lookup`.
173 /// If the query is executing elsewhere, this will wait for it and return the result.
174 /// If the query panicked, this will silently panic.
176 /// This function is inlined because that results in a noticeable speed-up
177 /// for some compile-time benchmarks.
179 fn try_start<'a, 'b, Q>(
183 mut lookup: QueryLookup<'a, TyCtxt<'tcx>, C::Key, C::Sharded>,
184 ) -> TryGetJob<'b, TyCtxt<'tcx>, C>
186 Q: QueryDescription<TyCtxt<'tcx>, Key = C::Key, Value = C::Value, Cache = C>,
188 let lock = &mut *lookup.lock;
190 let (latch, mut _query_blocked_prof_timer) = match lock.active.entry((*key).clone()) {
191 Entry::Occupied(mut entry) => {
192 match entry.get_mut() {
193 QueryResult::Started(job) => {
194 // For parallel queries, we'll block and wait until the query running
195 // in another thread has completed. Record how long we wait in the
197 let _query_blocked_prof_timer = if cfg!(parallel_compiler) {
198 Some(tcx.prof.query_blocked())
203 // Create the id of the job we're waiting for
204 let id = QueryJobId::new(job.id, lookup.shard, Q::DEP_KIND);
206 (job.latch(id), _query_blocked_prof_timer)
208 QueryResult::Poisoned => FatalError.raise(),
211 Entry::Vacant(entry) => {
212 // No job entry for this query. Return a new one to be started later.
214 // Generate an id unique within this shard.
215 let id = lock.jobs.checked_add(1).unwrap();
217 let id = QueryShardJobId(NonZeroU32::new(id).unwrap());
219 let global_id = QueryJobId::new(id, lookup.shard, Q::DEP_KIND);
221 let job = tls::with_related_context(tcx, |icx| QueryJob::new(id, span, icx.query));
223 entry.insert(QueryResult::Started(job));
226 JobOwner { state: Q::query_state(tcx), id: global_id, key: (*key).clone() };
227 return TryGetJob::NotYetStarted(owner);
230 mem::drop(lookup.lock);
232 // If we are single-threaded we know that we have cycle error,
233 // so we just return the error.
234 #[cfg(not(parallel_compiler))]
235 return TryGetJob::Cycle(cold_path(|| {
236 Q::handle_cycle_error(tcx, latch.find_cycle_in_stack(tcx, span))
239 // With parallel queries we might just have to wait on some other
241 #[cfg(parallel_compiler)]
243 let result = latch.wait_on(tcx, span);
245 if let Err(cycle) = result {
246 return TryGetJob::Cycle(Q::handle_cycle_error(tcx, cycle));
249 let cached = tcx.try_get_cached(
252 |value, index| (value.clone(), index),
253 |_, _| panic!("value must be in cache after waiting"),
256 if let Some(prof_timer) = _query_blocked_prof_timer.take() {
257 prof_timer.finish_with_query_invocation_id(cached.1.into());
260 return TryGetJob::JobCompleted(cached);
265 impl<'tcx, CTX: QueryContext, C> JobOwner<'tcx, CTX, C>
268 C::Key: Eq + Hash + Clone + Debug,
271 /// Completes the query by updating the query cache with the `result`,
272 /// signals the waiter and forgets the JobOwner, so it won't poison the query
274 fn complete(self, tcx: CTX, result: &C::Value, dep_node_index: DepNodeIndex) {
275 // We can move out of `self` here because we `mem::forget` it below
276 let key = unsafe { ptr::read(&self.key) };
277 let state = self.state;
279 // Forget ourself so our destructor won't poison the query
283 let result = result.clone();
284 let mut lock = state.shards.get_shard_by_value(&key).lock();
285 let job = match lock.active.remove(&key).unwrap() {
286 QueryResult::Started(job) => job,
287 QueryResult::Poisoned => panic!(),
289 state.cache.complete(tcx, &mut lock.cache, key, result, dep_node_index);
293 job.signal_complete();
298 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
300 F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R,
302 let diagnostics = Lock::new(ThinVec::new());
303 let result = f(Some(&diagnostics));
304 (result, diagnostics.into_inner())
307 impl<'tcx, CTX: QueryContext, C: QueryCache<CTX>> Drop for JobOwner<'tcx, CTX, C>
309 C::Key: Eq + Hash + Clone + Debug,
315 // Poison the query so jobs waiting on it panic.
316 let state = self.state;
317 let shard = state.shards.get_shard_by_value(&self.key);
319 let mut shard = shard.lock();
320 let job = match shard.active.remove(&self.key).unwrap() {
321 QueryResult::Started(job) => job,
322 QueryResult::Poisoned => panic!(),
324 shard.active.insert(self.key.clone(), QueryResult::Poisoned);
327 // Also signal the completion of the job, so waiters
328 // will continue execution.
329 job.signal_complete();
334 pub(crate) struct CycleError<CTX: QueryContext> {
335 /// The query and related span that uses the cycle.
336 pub(super) usage: Option<(Span, CTX::Query)>,
337 pub(super) cycle: Vec<QueryInfo<CTX>>,
340 /// The result of `try_start`.
341 enum TryGetJob<'tcx, CTX: QueryContext, C: QueryCache<CTX>>
343 C::Key: Eq + Hash + Clone + Debug,
346 /// The query is not yet started. Contains a guard to the cache eventually used to start it.
347 NotYetStarted(JobOwner<'tcx, CTX, C>),
349 /// The query was already completed.
350 /// Returns the result of the query and its dep-node index
351 /// if it succeeded or a cycle error if it failed.
352 #[cfg(parallel_compiler)]
353 JobCompleted((C::Value, DepNodeIndex)),
355 /// Trying to execute the query resulted in a cycle.
359 impl QueryContext for TyCtxt<'tcx> {
360 type Query = Query<'tcx>;
362 fn session(&self) -> &Session {
366 fn def_path_str(&self, def_id: DefId) -> String {
367 TyCtxt::def_path_str(*self, def_id)
371 impl<'tcx> TyCtxt<'tcx> {
372 /// Executes a job by changing the `ImplicitCtxt` to point to the
373 /// new query job while it executes. It returns the diagnostics
374 /// captured during execution and the actual result.
376 fn start_query<F, R>(
379 diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
383 F: FnOnce(TyCtxt<'tcx>) -> R,
385 // The `TyCtxt` stored in TLS has the same global interner lifetime
386 // as `self`, so we use `with_related_context` to relate the 'tcx lifetimes
387 // when accessing the `ImplicitCtxt`.
388 tls::with_related_context(self, move |current_icx| {
389 // Update the `ImplicitCtxt` to point to our new query job.
390 let new_icx = tls::ImplicitCtxt {
394 layout_depth: current_icx.layout_depth,
395 task_deps: current_icx.task_deps,
398 // Use the `ImplicitCtxt` while we execute the query.
399 tls::enter_context(&new_icx, |_| compute(self))
405 pub(super) fn report_cycle(
407 CycleError { usage, cycle: stack }: CycleError<TyCtxt<'tcx>>,
408 ) -> DiagnosticBuilder<'tcx> {
409 assert!(!stack.is_empty());
411 let fix_span = |span: Span, query: &Query<'tcx>| {
412 self.sess.source_map().guess_head_span(query.default_span(self, span))
415 // Disable naming impls with types in this path, since that
416 // sometimes cycles itself, leading to extra cycle errors.
417 // (And cycle errors around impls tend to occur during the
418 // collect/coherence phases anyhow.)
419 ty::print::with_forced_impl_filename_line(|| {
420 let span = fix_span(stack[1 % stack.len()].span, &stack[0].query);
421 let mut err = struct_span_err!(
425 "cycle detected when {}",
426 stack[0].query.describe(self)
429 for i in 1..stack.len() {
430 let query = &stack[i].query;
431 let span = fix_span(stack[(i + 1) % stack.len()].span, query);
432 err.span_note(span, &format!("...which requires {}...", query.describe(self)));
436 "...which again requires {}, completing the cycle",
437 stack[0].query.describe(self)
440 if let Some((span, query)) = usage {
442 fix_span(span, &query),
443 &format!("cycle used when {}", query.describe(self)),
451 pub fn try_print_query_stack(handler: &Handler) {
452 eprintln!("query stack during panic:");
454 // Be careful reyling on global state here: this code is called from
455 // a panic hook, which means that the global `Handler` may be in a weird
456 // state if it was responsible for triggering the panic.
457 tls::with_context_opt(|icx| {
458 if let Some(icx) = icx {
459 let query_map = icx.tcx.queries.try_collect_active_jobs();
461 let mut current_query = icx.query;
464 while let Some(query) = current_query {
466 if let Some(info) = query_map.as_ref().and_then(|map| map.get(&query)) {
471 let mut diag = Diagnostic::new(
476 query_info.info.query.name(),
477 query_info.info.query.describe(icx.tcx)
481 icx.tcx.sess.source_map().guess_head_span(query_info.info.span).into();
482 handler.force_print_diagnostic(diag);
484 current_query = query_info.job.parent;
490 eprintln!("end of query stack");
493 /// Checks if the query is already computed and in the cache.
494 /// It returns the shard index and a lock guard to the shard,
495 /// which will be used if the query is not in the cache and we need
498 fn try_get_cached<C, R, OnHit, OnMiss>(
500 state: &'tcx QueryState<TyCtxt<'tcx>, C>,
502 // `on_hit` can be called while holding a lock to the query cache
507 C: QueryCache<TyCtxt<'tcx>>,
508 OnHit: FnOnce(&C::Value, DepNodeIndex) -> R,
509 OnMiss: FnOnce(C::Key, QueryLookup<'_, TyCtxt<'tcx>, C::Key, C::Sharded>) -> R,
513 QueryStateShard::<TyCtxt<'tcx>, C::Key, C::Sharded>::get_cache,
516 if unlikely!(self.prof.enabled()) {
517 self.prof.query_cache_hit(index.into());
519 #[cfg(debug_assertions)]
521 state.cache_hits.fetch_add(1, Ordering::Relaxed);
530 pub(super) fn get_query<Q: QueryDescription<TyCtxt<'tcx>> + 'tcx>(
535 debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME, key, span);
538 Q::query_state(self),
541 self.dep_graph.read_index(index);
544 |key, lookup| self.try_execute_query::<Q>(span, key, lookup),
549 fn try_execute_query<Q: QueryDescription<TyCtxt<'tcx>> + 'tcx>(
557 <Q::Cache as QueryCache<TyCtxt<'tcx>>>::Sharded,
560 let job = match JobOwner::try_start::<Q>(self, span, &key, lookup) {
561 TryGetJob::NotYetStarted(job) => job,
562 TryGetJob::Cycle(result) => return result,
563 #[cfg(parallel_compiler)]
564 TryGetJob::JobCompleted((v, index)) => {
565 self.dep_graph.read_index(index);
570 // Fast path for when incr. comp. is off. `to_dep_node` is
571 // expensive for some `DepKind`s.
572 if !self.dep_graph.is_fully_enabled() {
573 let null_dep_node = DepNode::new_no_params(crate::dep_graph::DepKind::Null);
574 return self.force_query_with_job::<Q>(key, job, null_dep_node).0;
578 let prof_timer = self.prof.query_provider();
580 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
581 self.start_query(job.id, diagnostics, |tcx| {
582 tcx.dep_graph.with_anon_task(Q::DEP_KIND, || Q::compute(tcx, key))
586 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
588 self.dep_graph.read_index(dep_node_index);
590 if unlikely!(!diagnostics.is_empty()) {
593 .store_diagnostics_for_anon_node(dep_node_index, diagnostics);
596 job.complete(self, &result, dep_node_index);
601 let dep_node = Q::to_dep_node(self, &key);
604 // The diagnostics for this query will be
605 // promoted to the current session during
606 // `try_mark_green()`, so we can ignore them here.
607 let loaded = self.start_query(job.id, None, |tcx| {
608 let marked = tcx.dep_graph.try_mark_green_and_read(tcx, &dep_node);
609 marked.map(|(prev_dep_node_index, dep_node_index)| {
611 tcx.load_from_disk_and_cache_in_memory::<Q>(
621 if let Some((result, dep_node_index)) = loaded {
622 job.complete(self, &result, dep_node_index);
627 let (result, dep_node_index) = self.force_query_with_job::<Q>(key, job, dep_node);
628 self.dep_graph.read_index(dep_node_index);
632 fn load_from_disk_and_cache_in_memory<Q: QueryDescription<TyCtxt<'tcx>>>(
635 prev_dep_node_index: SerializedDepNodeIndex,
636 dep_node_index: DepNodeIndex,
639 // Note this function can be called concurrently from the same query
640 // We must ensure that this is handled correctly.
642 debug_assert!(self.dep_graph.is_green(dep_node));
644 // First we try to load the result from the on-disk cache.
645 let result = if Q::cache_on_disk(self, key.clone(), None) {
646 let prof_timer = self.prof.incr_cache_loading();
647 let result = Q::try_load_from_disk(self, prev_dep_node_index);
648 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
650 // We always expect to find a cached result for things that
651 // can be forced from `DepNode`.
653 !dep_node.kind.can_reconstruct_query_key() || result.is_some(),
654 "missing on-disk cache entry for {:?}",
659 // Some things are never cached on disk.
663 let result = if let Some(result) = result {
666 // We could not load a result from the on-disk cache, so
668 let prof_timer = self.prof.query_provider();
670 // The dep-graph for this computation is already in-place.
671 let result = self.dep_graph.with_ignore(|| Q::compute(self, key));
673 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
678 // If `-Zincremental-verify-ich` is specified, re-hash results from
679 // the cache and make sure that they have the expected fingerprint.
680 if unlikely!(self.sess.opts.debugging_opts.incremental_verify_ich) {
681 self.incremental_verify_ich::<Q>(&result, dep_node, dep_node_index);
689 fn incremental_verify_ich<Q: QueryDescription<TyCtxt<'tcx>>>(
693 dep_node_index: DepNodeIndex,
695 use rustc_data_structures::fingerprint::Fingerprint;
698 Some(self.dep_graph.fingerprint_of(dep_node_index))
699 == self.dep_graph.prev_fingerprint_of(dep_node),
700 "fingerprint for green query instance not loaded from cache: {:?}",
704 debug!("BEGIN verify_ich({:?})", dep_node);
705 let mut hcx = self.create_stable_hashing_context();
707 let new_hash = Q::hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
708 debug!("END verify_ich({:?})", dep_node);
710 let old_hash = self.dep_graph.fingerprint_of(dep_node_index);
712 assert!(new_hash == old_hash, "found unstable fingerprints for {:?}", dep_node,);
716 fn force_query_with_job<Q: QueryDescription<TyCtxt<'tcx>> + 'tcx>(
719 job: JobOwner<'tcx, TyCtxt<'tcx>, Q::Cache>,
721 ) -> (Q::Value, DepNodeIndex) {
722 // If the following assertion triggers, it can have two reasons:
723 // 1. Something is wrong with DepNode creation, either here or
724 // in `DepGraph::try_mark_green()`.
725 // 2. Two distinct query keys get mapped to the same `DepNode`
726 // (see for example #48923).
728 !self.dep_graph.dep_node_exists(&dep_node),
729 "forcing query with already existing `DepNode`\n\
736 let prof_timer = self.prof.query_provider();
738 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
739 self.start_query(job.id, diagnostics, |tcx| {
741 tcx.dep_graph.with_eval_always_task(
749 tcx.dep_graph.with_task(dep_node, tcx, key, Q::compute, Q::hash_result)
754 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
756 if unlikely!(!diagnostics.is_empty()) {
757 if dep_node.kind != crate::dep_graph::DepKind::Null {
758 self.queries.on_disk_cache.store_diagnostics(dep_node_index, diagnostics);
762 job.complete(self, &result, dep_node_index);
764 (result, dep_node_index)
767 /// Ensure that either this query has all green inputs or been executed.
768 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
770 /// This function is particularly useful when executing passes for their
771 /// side-effects -- e.g., in order to report errors for erroneous programs.
773 /// Note: The optimization is only available during incr. comp.
774 pub(super) fn ensure_query<Q: QueryDescription<TyCtxt<'tcx>> + 'tcx>(self, key: Q::Key) {
776 let _ = self.get_query::<Q>(DUMMY_SP, key);
780 // Ensuring an anonymous query makes no sense
783 let dep_node = Q::to_dep_node(self, &key);
785 match self.dep_graph.try_mark_green_and_read(self, &dep_node) {
787 // A None return from `try_mark_green_and_read` means that this is either
788 // a new dep node or that the dep node has already been marked red.
789 // Either way, we can't call `dep_graph.read()` as we don't have the
790 // DepNodeIndex. We must invoke the query itself. The performance cost
791 // this introduces should be negligible as we'll immediately hit the
792 // in-memory cache, or another query down the line will.
793 let _ = self.get_query::<Q>(DUMMY_SP, key);
795 Some((_, dep_node_index)) => {
796 self.prof.query_cache_hit(dep_node_index.into());
802 pub(super) fn force_query<Q: QueryDescription<TyCtxt<'tcx>> + 'tcx>(
808 // We may be concurrently trying both execute and force a query.
809 // Ensure that only one of them runs the query.
812 Q::query_state(self),
815 // Cache hit, do nothing
818 let job = match JobOwner::try_start::<Q>(self, span, &key, lookup) {
819 TryGetJob::NotYetStarted(job) => job,
820 TryGetJob::Cycle(_) => return,
821 #[cfg(parallel_compiler)]
822 TryGetJob::JobCompleted(_) => return,
824 self.force_query_with_job::<Q>(key, job, dep_node);
830 macro_rules! handle_cycle_error {
831 ([][$tcx: expr, $error:expr]) => {{
832 $tcx.report_cycle($error).emit();
833 Value::from_cycle_error($tcx)
835 ([fatal_cycle $($rest:tt)*][$tcx:expr, $error:expr]) => {{
836 $tcx.report_cycle($error).emit();
837 $tcx.sess.abort_if_errors();
840 ([cycle_delay_bug $($rest:tt)*][$tcx:expr, $error:expr]) => {{
841 $tcx.report_cycle($error).delay_as_bug();
842 Value::from_cycle_error($tcx)
844 ([$other:ident $(($($other_args:tt)*))* $(, $($modifiers:tt)*)*][$($args:tt)*]) => {
845 handle_cycle_error!([$($($modifiers)*)*][$($args)*])
849 macro_rules! is_anon {
853 ([anon $($rest:tt)*]) => {{
856 ([$other:ident $(($($other_args:tt)*))* $(, $($modifiers:tt)*)*]) => {
857 is_anon!([$($($modifiers)*)*])
861 macro_rules! is_eval_always {
865 ([eval_always $($rest:tt)*]) => {{
868 ([$other:ident $(($($other_args:tt)*))* $(, $($modifiers:tt)*)*]) => {
869 is_eval_always!([$($($modifiers)*)*])
873 macro_rules! query_storage {
874 (<$tcx:tt>[][$K:ty, $V:ty]) => {
875 <<$K as Key>::CacheSelector as CacheSelector<TyCtxt<$tcx>, $K, $V>>::Cache
877 (<$tcx:tt>[storage($ty:ty) $($rest:tt)*][$K:ty, $V:ty]) => {
880 (<$tcx:tt>[$other:ident $(($($other_args:tt)*))* $(, $($modifiers:tt)*)*][$($args:tt)*]) => {
881 query_storage!(<$tcx>[$($($modifiers)*)*][$($args)*])
885 macro_rules! hash_result {
886 ([][$hcx:expr, $result:expr]) => {{
887 dep_graph::hash_result($hcx, &$result)
889 ([no_hash $($rest:tt)*][$hcx:expr, $result:expr]) => {{
892 ([$other:ident $(($($other_args:tt)*))* $(, $($modifiers:tt)*)*][$($args:tt)*]) => {
893 hash_result!([$($($modifiers)*)*][$($args)*])
897 macro_rules! define_queries {
898 (<$tcx:tt> $($category:tt {
899 $($(#[$attr:meta])* [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*
901 define_queries_inner! { <$tcx>
902 $($( $(#[$attr])* category<$category> [$($modifiers)*] fn $name: $node($K) -> $V,)*)*
907 macro_rules! define_queries_inner {
909 $($(#[$attr:meta])* category<$category:tt>
910 [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
914 rustc_data_structures::stable_hasher::HashStable,
915 rustc_data_structures::stable_hasher::StableHasher,
916 ich::StableHashingContext
918 use rustc_data_structures::profiling::ProfileCategory;
920 define_queries_struct! {
922 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
925 #[allow(nonstandard_style)]
926 #[derive(Clone, Debug)]
927 pub enum Query<$tcx> {
928 $($(#[$attr])* $name($K)),*
931 impl<$tcx> Query<$tcx> {
932 pub fn name(&self) -> &'static str {
934 $(Query::$name(_) => stringify!($name),)*
938 pub fn describe(&self, tcx: TyCtxt<$tcx>) -> Cow<'static, str> {
939 let (r, name) = match *self {
940 $(Query::$name(key) => {
941 (queries::$name::describe(tcx, key), stringify!($name))
944 if tcx.sess.verbose() {
945 format!("{} [{}]", r, name).into()
951 // FIXME(eddyb) Get more valid `Span`s on queries.
952 pub fn default_span(&self, tcx: TyCtxt<$tcx>, span: Span) -> Span {
953 if !span.is_dummy() {
956 // The `def_span` query is used to calculate `default_span`,
957 // so exit to avoid infinite recursion.
958 if let Query::def_span(..) = *self {
962 $(Query::$name(key) => key.default_span(tcx),)*
967 impl<'a, $tcx> HashStable<StableHashingContext<'a>> for Query<$tcx> {
968 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
969 mem::discriminant(self).hash_stable(hcx, hasher);
971 $(Query::$name(key) => key.hash_stable(hcx, hasher),)*
977 use std::marker::PhantomData;
979 $(#[allow(nonstandard_style)]
980 pub struct $name<$tcx> {
981 data: PhantomData<&$tcx ()>
985 $(impl<$tcx> QueryConfig<TyCtxt<$tcx>> for queries::$name<$tcx> {
988 const NAME: &'static str = stringify!($name);
989 const CATEGORY: ProfileCategory = $category;
992 impl<$tcx> QueryAccessors<TyCtxt<$tcx>> for queries::$name<$tcx> {
993 const ANON: bool = is_anon!([$($modifiers)*]);
994 const EVAL_ALWAYS: bool = is_eval_always!([$($modifiers)*]);
995 const DEP_KIND: dep_graph::DepKind = dep_graph::DepKind::$node;
997 type Cache = query_storage!(<$tcx>[$($modifiers)*][$K, $V]);
1000 fn query_state<'a>(tcx: TyCtxt<$tcx>) -> &'a QueryState<TyCtxt<$tcx>, Self::Cache> {
1006 fn to_dep_node(tcx: TyCtxt<$tcx>, key: &Self::Key) -> DepNode {
1007 DepConstructor::$node(tcx, *key)
1011 fn compute(tcx: TyCtxt<'tcx>, key: Self::Key) -> Self::Value {
1012 let provider = tcx.queries.providers.get(key.query_crate())
1013 // HACK(eddyb) it's possible crates may be loaded after
1014 // the query engine is created, and because crate loading
1015 // is not yet integrated with the query engine, such crates
1016 // would be missing appropriate entries in `providers`.
1017 .unwrap_or(&tcx.queries.fallback_extern_providers)
1023 _hcx: &mut StableHashingContext<'_>,
1024 _result: &Self::Value
1025 ) -> Option<Fingerprint> {
1026 hash_result!([$($modifiers)*][_hcx, _result])
1029 fn handle_cycle_error(
1031 error: CycleError<TyCtxt<'tcx>>
1033 handle_cycle_error!([$($modifiers)*][tcx, error])
1037 #[derive(Copy, Clone)]
1038 pub struct TyCtxtEnsure<'tcx> {
1039 pub tcx: TyCtxt<'tcx>,
1042 impl TyCtxtEnsure<$tcx> {
1045 pub fn $name(self, key: $K) {
1046 self.tcx.ensure_query::<queries::$name<'_>>(key)
1050 #[derive(Copy, Clone)]
1051 pub struct TyCtxtAt<'tcx> {
1052 pub tcx: TyCtxt<'tcx>,
1056 impl Deref for TyCtxtAt<'tcx> {
1057 type Target = TyCtxt<'tcx>;
1059 fn deref(&self) -> &Self::Target {
1065 /// Returns a transparent wrapper for `TyCtxt`, which ensures queries
1066 /// are executed instead of just returning their results.
1068 pub fn ensure(self) -> TyCtxtEnsure<$tcx> {
1074 /// Returns a transparent wrapper for `TyCtxt` which uses
1075 /// `span` as the location of queries performed through it.
1077 pub fn at(self, span: Span) -> TyCtxtAt<$tcx> {
1086 pub fn $name(self, key: $K) -> $V {
1087 self.at(DUMMY_SP).$name(key)
1090 /// All self-profiling events generated by the query engine use
1091 /// virtual `StringId`s for their `event_id`. This method makes all
1092 /// those virtual `StringId`s point to actual strings.
1094 /// If we are recording only summary data, the ids will point to
1095 /// just the query names. If we are recording query keys too, we
1096 /// allocate the corresponding strings here.
1097 pub fn alloc_self_profile_query_strings(self) {
1098 use crate::ty::query::profiling_support::{
1099 alloc_self_profile_query_strings_for_query_cache,
1100 QueryKeyStringCache,
1103 if !self.prof.enabled() {
1107 let mut string_cache = QueryKeyStringCache::new();
1110 alloc_self_profile_query_strings_for_query_cache(
1113 &self.queries.$name,
1120 impl TyCtxtAt<$tcx> {
1123 pub fn $name(self, key: $K) -> $V {
1124 self.tcx.get_query::<queries::$name<'_>>(self.span, key)
1128 define_provider_struct! {
1130 input: ($(([$($modifiers)*] [$name] [$K] [$V]))*)
1133 impl<$tcx> Copy for Providers<$tcx> {}
1134 impl<$tcx> Clone for Providers<$tcx> {
1135 fn clone(&self) -> Self { *self }
1140 macro_rules! define_queries_struct {
1142 input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
1143 pub struct Queries<$tcx> {
1144 /// This provides access to the incrimental comilation on-disk cache for query results.
1145 /// Do not access this directly. It is only meant to be used by
1146 /// `DepGraph::try_mark_green()` and the query infrastructure.
1147 pub(crate) on_disk_cache: OnDiskCache<'tcx>,
1149 providers: IndexVec<CrateNum, Providers<$tcx>>,
1150 fallback_extern_providers: Box<Providers<$tcx>>,
1152 $($(#[$attr])* $name: QueryState<
1154 <queries::$name<$tcx> as QueryAccessors<TyCtxt<'tcx>>>::Cache,
1158 impl<$tcx> Queries<$tcx> {
1160 providers: IndexVec<CrateNum, Providers<$tcx>>,
1161 fallback_extern_providers: Providers<$tcx>,
1162 on_disk_cache: OnDiskCache<'tcx>,
1166 fallback_extern_providers: Box::new(fallback_extern_providers),
1168 $($name: Default::default()),*
1172 pub(crate) fn try_collect_active_jobs(
1174 ) -> Option<FxHashMap<QueryJobId, QueryJobInfo<TyCtxt<'tcx>>>> {
1175 let mut jobs = FxHashMap::default();
1178 self.$name.try_collect_active_jobs(
1179 <queries::$name<'tcx> as QueryAccessors<TyCtxt<'tcx>>>::DEP_KIND,
1191 macro_rules! define_provider_struct {
1193 input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
1194 pub struct Providers<$tcx> {
1195 $(pub $name: fn(TyCtxt<$tcx>, $K) -> $R,)*
1198 impl<$tcx> Default for Providers<$tcx> {
1199 fn default() -> Self {
1200 $(fn $name<$tcx>(_: TyCtxt<$tcx>, key: $K) -> $R {
1201 bug!("`tcx.{}({:?})` unsupported by its crate",
1202 stringify!($name), key);
1204 Providers { $($name),* }