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};
6 use crate::dep_graph::{DepNodeIndex, SerializedDepNodeIndex};
7 use crate::query::caches::QueryCache;
8 use crate::query::config::{QueryContext, QueryDescription};
9 use crate::query::job::{QueryInfo, QueryJob, QueryJobId, QueryJobInfo, QueryShardJobId};
11 #[cfg(not(parallel_compiler))]
12 use rustc_data_structures::cold_path;
13 use rustc_data_structures::fingerprint::Fingerprint;
14 use rustc_data_structures::fx::{FxHashMap, FxHasher};
15 use rustc_data_structures::sharded::Sharded;
16 use rustc_data_structures::sync::{Lock, LockGuard};
17 use rustc_data_structures::thin_vec::ThinVec;
18 use rustc_errors::{Diagnostic, FatalError};
19 use rustc_span::source_map::DUMMY_SP;
21 use std::collections::hash_map::Entry;
22 use std::convert::TryFrom;
24 use std::hash::{Hash, Hasher};
26 use std::num::NonZeroU32;
28 #[cfg(debug_assertions)]
29 use std::sync::atomic::{AtomicUsize, Ordering};
31 pub struct QueryStateShard<CTX: QueryContext, K, C> {
33 active: FxHashMap<K, QueryResult<CTX>>,
35 /// Used to generate unique ids for active jobs.
39 impl<CTX: QueryContext, K, C: Default> Default for QueryStateShard<CTX, K, C> {
40 fn default() -> QueryStateShard<CTX, K, C> {
41 QueryStateShard { cache: Default::default(), active: Default::default(), jobs: 0 }
45 pub struct QueryState<CTX: QueryContext, C: QueryCache> {
47 shards: Sharded<QueryStateShard<CTX, C::Key, C::Sharded>>,
48 #[cfg(debug_assertions)]
49 pub cache_hits: AtomicUsize,
52 impl<CTX: QueryContext, C: QueryCache> QueryState<CTX, C> {
53 pub(super) fn get_lookup<'tcx>(
56 ) -> QueryLookup<'tcx, CTX, C::Key, C::Sharded> {
57 // We compute the key's hash once and then use it for both the
58 // shard lookup and the hashmap lookup. This relies on the fact
59 // that both of them use `FxHasher`.
60 let mut hasher = FxHasher::default();
61 key.hash(&mut hasher);
62 let key_hash = hasher.finish();
64 let shard = self.shards.get_shard_index_by_hash(key_hash);
65 let lock = self.shards.get_shard_by_index(shard).lock();
66 QueryLookup { key_hash, shard, lock }
70 /// Indicates the state of a query for a given key in a query map.
71 enum QueryResult<CTX: QueryContext> {
72 /// An already executing query. The query job can be used to await for its completion.
73 Started(QueryJob<CTX>),
75 /// The query panicked. Queries trying to wait on this will raise a fatal error which will
80 impl<CTX: QueryContext, C: QueryCache> QueryState<CTX, C> {
81 pub fn iter_results<R>(
83 f: impl for<'a> FnOnce(
84 Box<dyn Iterator<Item = (&'a C::Key, &'a C::Value, DepNodeIndex)> + 'a>,
87 self.cache.iter(&self.shards, |shard| &mut shard.cache, f)
90 pub fn all_inactive(&self) -> bool {
91 let shards = self.shards.lock_shards();
92 shards.iter().all(|shard| shard.active.is_empty())
95 pub fn try_collect_active_jobs(
98 make_query: fn(C::Key) -> CTX::Query,
99 jobs: &mut FxHashMap<QueryJobId<CTX::DepKind>, QueryJobInfo<CTX>>,
104 // We use try_lock_shards here since we are called from the
105 // deadlock handler, and this shouldn't be locked.
106 let shards = self.shards.try_lock_shards()?;
107 let shards = shards.iter().enumerate();
108 jobs.extend(shards.flat_map(|(shard_id, shard)| {
109 shard.active.iter().filter_map(move |(k, v)| {
110 if let QueryResult::Started(ref job) = *v {
112 QueryJobId { job: job.id, shard: u16::try_from(shard_id).unwrap(), kind };
113 let info = QueryInfo { span: job.span, query: make_query(k.clone()) };
114 Some((id, QueryJobInfo { info, job: job.clone() }))
125 impl<CTX: QueryContext, C: QueryCache> Default for QueryState<CTX, C> {
126 fn default() -> QueryState<CTX, C> {
129 shards: Default::default(),
130 #[cfg(debug_assertions)]
131 cache_hits: AtomicUsize::new(0),
136 /// Values used when checking a query cache which can be reused on a cache-miss to execute the query.
137 pub struct QueryLookup<'tcx, CTX: QueryContext, K, C> {
138 pub(super) key_hash: u64,
140 pub(super) lock: LockGuard<'tcx, QueryStateShard<CTX, K, C>>,
143 /// A type representing the responsibility to execute the job in the `job` field.
144 /// This will poison the relevant query if dropped.
145 struct JobOwner<'tcx, CTX: QueryContext, C>
148 C::Key: Eq + Hash + Clone + Debug,
151 state: &'tcx QueryState<CTX, C>,
153 id: QueryJobId<CTX::DepKind>,
156 impl<'tcx, CTX: QueryContext, C> JobOwner<'tcx, CTX, C>
159 C::Key: Eq + Hash + Clone + Debug,
162 /// Either gets a `JobOwner` corresponding the query, allowing us to
163 /// start executing the query, or returns with the result of the query.
164 /// This function assumes that `try_get_cached` is already called and returned `lookup`.
165 /// If the query is executing elsewhere, this will wait for it and return the result.
166 /// If the query panicked, this will silently panic.
168 /// This function is inlined because that results in a noticeable speed-up
169 /// for some compile-time benchmarks.
171 fn try_start<'a, 'b, Q, K>(
175 mut lookup: QueryLookup<'a, CTX, C::Key, C::Sharded>,
176 ) -> TryGetJob<'b, CTX, C>
179 Q: QueryDescription<CTX, Key = C::Key, Value = C::Value, Cache = C>,
180 CTX: QueryContext<DepKind = K>,
182 let lock = &mut *lookup.lock;
184 let (latch, mut _query_blocked_prof_timer) = match lock.active.entry((*key).clone()) {
185 Entry::Occupied(mut entry) => {
186 match entry.get_mut() {
187 QueryResult::Started(job) => {
188 // For parallel queries, we'll block and wait until the query running
189 // in another thread has completed. Record how long we wait in the
191 let _query_blocked_prof_timer = if cfg!(parallel_compiler) {
192 Some(tcx.profiler().query_blocked())
197 // Create the id of the job we're waiting for
198 let id = QueryJobId::new(job.id, lookup.shard, Q::DEP_KIND);
200 (job.latch(id), _query_blocked_prof_timer)
202 QueryResult::Poisoned => FatalError.raise(),
205 Entry::Vacant(entry) => {
206 // No job entry for this query. Return a new one to be started later.
208 // Generate an id unique within this shard.
209 let id = lock.jobs.checked_add(1).unwrap();
211 let id = QueryShardJobId(NonZeroU32::new(id).unwrap());
213 let global_id = QueryJobId::new(id, lookup.shard, Q::DEP_KIND);
215 let job = tcx.read_query_job(|query| QueryJob::new(id, span, query));
217 entry.insert(QueryResult::Started(job));
220 JobOwner { state: Q::query_state(tcx), id: global_id, key: (*key).clone() };
221 return TryGetJob::NotYetStarted(owner);
224 mem::drop(lookup.lock);
226 // If we are single-threaded we know that we have cycle error,
227 // so we just return the error.
228 #[cfg(not(parallel_compiler))]
229 return TryGetJob::Cycle(cold_path(|| {
230 Q::handle_cycle_error(tcx, latch.find_cycle_in_stack(tcx, span))
233 // With parallel queries we might just have to wait on some other
235 #[cfg(parallel_compiler)]
237 let result = latch.wait_on(tcx, span);
239 if let Err(cycle) = result {
240 return TryGetJob::Cycle(Q::handle_cycle_error(tcx, cycle));
243 let cached = try_get_cached(
247 |value, index| (value.clone(), index),
248 |_, _| panic!("value must be in cache after waiting"),
251 if let Some(prof_timer) = _query_blocked_prof_timer.take() {
252 prof_timer.finish_with_query_invocation_id(cached.1.into());
255 return TryGetJob::JobCompleted(cached);
259 /// Completes the query by updating the query cache with the `result`,
260 /// signals the waiter and forgets the JobOwner, so it won't poison the query
262 fn complete(self, tcx: CTX, result: &C::Value, dep_node_index: DepNodeIndex) {
263 // We can move out of `self` here because we `mem::forget` it below
264 let key = unsafe { ptr::read(&self.key) };
265 let state = self.state;
267 // Forget ourself so our destructor won't poison the query
271 let result = result.clone();
272 let mut lock = state.shards.get_shard_by_value(&key).lock();
273 let job = match lock.active.remove(&key).unwrap() {
274 QueryResult::Started(job) => job,
275 QueryResult::Poisoned => panic!(),
277 state.cache.complete(tcx, &mut lock.cache, key, result, dep_node_index);
281 job.signal_complete();
286 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
288 F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R,
290 let diagnostics = Lock::new(ThinVec::new());
291 let result = f(Some(&diagnostics));
292 (result, diagnostics.into_inner())
295 impl<'tcx, CTX: QueryContext, C: QueryCache> Drop for JobOwner<'tcx, CTX, C>
297 C::Key: Eq + Hash + Clone + Debug,
303 // Poison the query so jobs waiting on it panic.
304 let state = self.state;
305 let shard = state.shards.get_shard_by_value(&self.key);
307 let mut shard = shard.lock();
308 let job = match shard.active.remove(&self.key).unwrap() {
309 QueryResult::Started(job) => job,
310 QueryResult::Poisoned => panic!(),
312 shard.active.insert(self.key.clone(), QueryResult::Poisoned);
315 // Also signal the completion of the job, so waiters
316 // will continue execution.
317 job.signal_complete();
322 pub struct CycleError<Q> {
323 /// The query and related span that uses the cycle.
324 pub usage: Option<(Span, Q)>,
325 pub cycle: Vec<QueryInfo<Q>>,
328 /// The result of `try_start`.
329 enum TryGetJob<'tcx, CTX: QueryContext, C: QueryCache>
331 C::Key: Eq + Hash + Clone + Debug,
334 /// The query is not yet started. Contains a guard to the cache eventually used to start it.
335 NotYetStarted(JobOwner<'tcx, CTX, C>),
337 /// The query was already completed.
338 /// Returns the result of the query and its dep-node index
339 /// if it succeeded or a cycle error if it failed.
340 #[cfg(parallel_compiler)]
341 JobCompleted((C::Value, DepNodeIndex)),
343 /// Trying to execute the query resulted in a cycle.
347 /// Checks if the query is already computed and in the cache.
348 /// It returns the shard index and a lock guard to the shard,
349 /// which will be used if the query is not in the cache and we need
352 fn try_get_cached<CTX, C, R, OnHit, OnMiss>(
354 state: &QueryState<CTX, C>,
356 // `on_hit` can be called while holding a lock to the query cache
363 OnHit: FnOnce(&C::Value, DepNodeIndex) -> R,
364 OnMiss: FnOnce(C::Key, QueryLookup<'_, CTX, C::Key, C::Sharded>) -> R,
370 if unlikely!(tcx.profiler().enabled()) {
371 tcx.profiler().query_cache_hit(index.into());
373 #[cfg(debug_assertions)]
375 state.cache_hits.fetch_add(1, Ordering::Relaxed);
384 fn try_execute_query<Q, CTX>(
388 lookup: QueryLookup<'_, CTX, Q::Key, <Q::Cache as QueryCache>::Sharded>,
391 Q: QueryDescription<CTX>,
394 let job = match JobOwner::try_start::<Q, _>(tcx, span, &key, lookup) {
395 TryGetJob::NotYetStarted(job) => job,
396 TryGetJob::Cycle(result) => return result,
397 #[cfg(parallel_compiler)]
398 TryGetJob::JobCompleted((v, index)) => {
399 tcx.dep_graph().read_index(index);
404 // Fast path for when incr. comp. is off. `to_dep_node` is
405 // expensive for some `DepKind`s.
406 if !tcx.dep_graph().is_fully_enabled() {
407 let null_dep_node = DepNode::new_no_params(DepKind::NULL);
408 return force_query_with_job::<Q, _>(tcx, key, job, null_dep_node).0;
412 let prof_timer = tcx.profiler().query_provider();
414 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
415 tcx.start_query(job.id, diagnostics, |tcx| {
416 tcx.dep_graph().with_anon_task(Q::DEP_KIND, || Q::compute(tcx, key))
420 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
422 tcx.dep_graph().read_index(dep_node_index);
424 if unlikely!(!diagnostics.is_empty()) {
425 tcx.store_diagnostics_for_anon_node(dep_node_index, diagnostics);
428 job.complete(tcx, &result, dep_node_index);
433 let dep_node = Q::to_dep_node(tcx, &key);
436 // The diagnostics for this query will be
437 // promoted to the current session during
438 // `try_mark_green()`, so we can ignore them here.
439 let loaded = tcx.start_query(job.id, None, |tcx| {
440 let marked = tcx.dep_graph().try_mark_green_and_read(tcx, &dep_node);
441 marked.map(|(prev_dep_node_index, dep_node_index)| {
443 load_from_disk_and_cache_in_memory::<Q, _>(
454 if let Some((result, dep_node_index)) = loaded {
455 job.complete(tcx, &result, dep_node_index);
460 let (result, dep_node_index) = force_query_with_job::<Q, _>(tcx, key, job, dep_node);
461 tcx.dep_graph().read_index(dep_node_index);
465 fn load_from_disk_and_cache_in_memory<Q, CTX>(
468 prev_dep_node_index: SerializedDepNodeIndex,
469 dep_node_index: DepNodeIndex,
470 dep_node: &DepNode<CTX::DepKind>,
474 Q: QueryDescription<CTX>,
476 // Note this function can be called concurrently from the same query
477 // We must ensure that this is handled correctly.
479 debug_assert!(tcx.dep_graph().is_green(dep_node));
481 // First we try to load the result from the on-disk cache.
482 let result = if Q::cache_on_disk(tcx, key.clone(), None) {
483 let prof_timer = tcx.profiler().incr_cache_loading();
484 let result = Q::try_load_from_disk(tcx, prev_dep_node_index);
485 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
487 // We always expect to find a cached result for things that
488 // can be forced from `DepNode`.
490 !dep_node.kind.can_reconstruct_query_key() || result.is_some(),
491 "missing on-disk cache entry for {:?}",
496 // Some things are never cached on disk.
500 let result = if let Some(result) = result {
503 // We could not load a result from the on-disk cache, so
505 let prof_timer = tcx.profiler().query_provider();
507 // The dep-graph for this computation is already in-place.
508 let result = tcx.dep_graph().with_ignore(|| Q::compute(tcx, key));
510 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
515 // If `-Zincremental-verify-ich` is specified, re-hash results from
516 // the cache and make sure that they have the expected fingerprint.
517 if unlikely!(tcx.session().opts.debugging_opts.incremental_verify_ich) {
518 incremental_verify_ich::<Q, _>(tcx, &result, dep_node, dep_node_index);
526 fn incremental_verify_ich<Q, CTX>(
529 dep_node: &DepNode<CTX::DepKind>,
530 dep_node_index: DepNodeIndex,
533 Q: QueryDescription<CTX>,
536 Some(tcx.dep_graph().fingerprint_of(dep_node_index))
537 == tcx.dep_graph().prev_fingerprint_of(dep_node),
538 "fingerprint for green query instance not loaded from cache: {:?}",
542 debug!("BEGIN verify_ich({:?})", dep_node);
543 let mut hcx = tcx.create_stable_hashing_context();
545 let new_hash = Q::hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
546 debug!("END verify_ich({:?})", dep_node);
548 let old_hash = tcx.dep_graph().fingerprint_of(dep_node_index);
550 assert!(new_hash == old_hash, "found unstable fingerprints for {:?}", dep_node,);
554 fn force_query_with_job<Q, CTX>(
557 job: JobOwner<'_, CTX, Q::Cache>,
558 dep_node: DepNode<CTX::DepKind>,
559 ) -> (Q::Value, DepNodeIndex)
561 Q: QueryDescription<CTX>,
564 // If the following assertion triggers, it can have two reasons:
565 // 1. Something is wrong with DepNode creation, either here or
566 // in `DepGraph::try_mark_green()`.
567 // 2. Two distinct query keys get mapped to the same `DepNode`
568 // (see for example #48923).
570 !tcx.dep_graph().dep_node_exists(&dep_node),
571 "forcing query with already existing `DepNode`\n\
578 let prof_timer = tcx.profiler().query_provider();
580 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
581 tcx.start_query(job.id, diagnostics, |tcx| {
583 tcx.dep_graph().with_eval_always_task(
591 tcx.dep_graph().with_task(dep_node, tcx, key, Q::compute, Q::hash_result)
596 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
598 if unlikely!(!diagnostics.is_empty()) {
599 if dep_node.kind != DepKind::NULL {
600 tcx.store_diagnostics(dep_node_index, diagnostics);
604 job.complete(tcx, &result, dep_node_index);
606 (result, dep_node_index)
609 pub trait QueryGetter: QueryContext {
610 fn get_query<Q: QueryDescription<Self>>(self, span: Span, key: Q::Key) -> Q::Value;
612 /// Ensure that either this query has all green inputs or been executed.
613 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
615 /// This function is particularly useful when executing passes for their
616 /// side-effects -- e.g., in order to report errors for erroneous programs.
618 /// Note: The optimization is only available during incr. comp.
619 fn ensure_query<Q: QueryDescription<Self>>(self, key: Q::Key);
621 fn force_query<Q: QueryDescription<Self>>(
625 dep_node: DepNode<Self::DepKind>,
629 impl<CTX> QueryGetter for CTX
634 fn get_query<Q: QueryDescription<Self>>(self, span: Span, key: Q::Key) -> Q::Value {
635 debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME, key, span);
639 Q::query_state(self),
642 self.dep_graph().read_index(index);
645 |key, lookup| try_execute_query::<Q, _>(self, span, key, lookup),
649 /// Ensure that either this query has all green inputs or been executed.
650 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
652 /// This function is particularly useful when executing passes for their
653 /// side-effects -- e.g., in order to report errors for erroneous programs.
655 /// Note: The optimization is only available during incr. comp.
656 fn ensure_query<Q: QueryDescription<Self>>(self, key: Q::Key) {
658 let _ = self.get_query::<Q>(DUMMY_SP, key);
662 // Ensuring an anonymous query makes no sense
665 let dep_node = Q::to_dep_node(self, &key);
667 match self.dep_graph().try_mark_green_and_read(self, &dep_node) {
669 // A None return from `try_mark_green_and_read` means that this is either
670 // a new dep node or that the dep node has already been marked red.
671 // Either way, we can't call `dep_graph.read()` as we don't have the
672 // DepNodeIndex. We must invoke the query itself. The performance cost
673 // this introduces should be negligible as we'll immediately hit the
674 // in-memory cache, or another query down the line will.
675 let _ = self.get_query::<Q>(DUMMY_SP, key);
677 Some((_, dep_node_index)) => {
678 self.profiler().query_cache_hit(dep_node_index.into());
683 fn force_query<Q: QueryDescription<Self>>(
687 dep_node: DepNode<Self::DepKind>,
689 // We may be concurrently trying both execute and force a query.
690 // Ensure that only one of them runs the query.
694 Q::query_state(self),
697 // Cache hit, do nothing
700 let job = match JobOwner::try_start::<Q, _>(self, span, &key, lookup) {
701 TryGetJob::NotYetStarted(job) => job,
702 TryGetJob::Cycle(_) => return,
703 #[cfg(parallel_compiler)]
704 TryGetJob::JobCompleted(_) => return,
706 force_query_with_job::<Q, _>(self, key, job, dep_node);