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::{DepContext, DepNode, DepNodeIndex, DepNodeParams};
6 use crate::query::caches::QueryCache;
7 use crate::query::config::QueryVTable;
8 use crate::query::job::{report_cycle, QueryInfo, QueryJob, QueryJobId, QueryJobInfo};
9 use crate::query::{QueryContext, QueryMap, QuerySideEffects, QueryStackFrame};
10 use crate::values::Value;
11 use crate::HandleCycleError;
12 use rustc_data_structures::fingerprint::Fingerprint;
13 use rustc_data_structures::fx::FxHashMap;
14 #[cfg(parallel_compiler)]
15 use rustc_data_structures::profiling::TimingGuard;
16 #[cfg(parallel_compiler)]
17 use rustc_data_structures::sharded::Sharded;
18 use rustc_data_structures::sync::Lock;
19 use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed, FatalError};
20 use rustc_session::Session;
21 use rustc_span::{Span, DUMMY_SP};
23 use std::collections::hash_map::Entry;
28 use thin_vec::ThinVec;
30 use super::QueryConfig;
32 pub struct QueryState<K> {
33 #[cfg(parallel_compiler)]
34 active: Sharded<FxHashMap<K, QueryResult>>,
35 #[cfg(not(parallel_compiler))]
36 active: Lock<FxHashMap<K, QueryResult>>,
39 /// Indicates the state of a query for a given key in a query map.
41 /// An already executing query. The query job can be used to await for its completion.
44 /// The query panicked. Queries trying to wait on this will raise a fatal error which will
51 K: Eq + Hash + Clone + Debug,
53 pub fn all_inactive(&self) -> bool {
54 #[cfg(parallel_compiler)]
56 let shards = self.active.lock_shards();
57 shards.iter().all(|shard| shard.is_empty())
59 #[cfg(not(parallel_compiler))]
61 self.active.lock().is_empty()
65 pub fn try_collect_active_jobs<Qcx: Copy>(
68 make_query: fn(Qcx, K) -> QueryStackFrame,
71 #[cfg(parallel_compiler)]
73 // We use try_lock_shards here since we are called from the
74 // deadlock handler, and this shouldn't be locked.
75 let shards = self.active.try_lock_shards()?;
76 for shard in shards.iter() {
77 for (k, v) in shard.iter() {
78 if let QueryResult::Started(ref job) = *v {
79 let query = make_query(qcx, k.clone());
80 jobs.insert(job.id, QueryJobInfo { query, job: job.clone() });
85 #[cfg(not(parallel_compiler))]
87 // We use try_lock here since we are called from the
88 // deadlock handler, and this shouldn't be locked.
89 // (FIXME: Is this relevant for non-parallel compilers? It doesn't
91 for (k, v) in self.active.try_lock()?.iter() {
92 if let QueryResult::Started(ref job) = *v {
93 let query = make_query(qcx, k.clone());
94 jobs.insert(job.id, QueryJobInfo { query, job: job.clone() });
103 impl<K> Default for QueryState<K> {
104 fn default() -> QueryState<K> {
105 QueryState { active: Default::default() }
109 /// A type representing the responsibility to execute the job in the `job` field.
110 /// This will poison the relevant query if dropped.
111 struct JobOwner<'tcx, K>
113 K: Eq + Hash + Clone,
115 state: &'tcx QueryState<K>,
122 fn mk_cycle<Qcx, V, R>(
124 cycle_error: CycleError,
125 handler: HandleCycleError,
126 cache: &dyn crate::query::QueryStorage<Value = V, Stored = R>,
130 V: std::fmt::Debug + Value<Qcx::DepContext>,
133 let error = report_cycle(qcx.dep_context().sess(), &cycle_error);
134 let value = handle_cycle_error(*qcx.dep_context(), &cycle_error, error, handler);
135 cache.store_nocache(value)
138 fn handle_cycle_error<Tcx, V>(
140 cycle_error: &CycleError,
141 mut error: DiagnosticBuilder<'_, ErrorGuaranteed>,
142 handler: HandleCycleError,
148 use HandleCycleError::*;
152 Value::from_cycle_error(tcx, &cycle_error.cycle)
156 tcx.sess().abort_if_errors();
160 error.delay_as_bug();
161 Value::from_cycle_error(tcx, &cycle_error.cycle)
166 impl<'tcx, K> JobOwner<'tcx, K>
168 K: Eq + Hash + Clone,
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<'b, Qcx>(
181 state: &'b QueryState<K>,
184 ) -> TryGetJob<'b, K>
188 #[cfg(parallel_compiler)]
189 let mut state_lock = state.active.get_shard_by_value(&key).lock();
190 #[cfg(not(parallel_compiler))]
191 let mut state_lock = state.active.lock();
192 let lock = &mut *state_lock;
194 match lock.entry(key) {
195 Entry::Vacant(entry) => {
196 let id = qcx.next_job_id();
197 let job = qcx.current_query_job();
198 let job = QueryJob::new(id, span, job);
200 let key = entry.key().clone();
201 entry.insert(QueryResult::Started(job));
203 let owner = JobOwner { state, id, key };
204 return TryGetJob::NotYetStarted(owner);
206 Entry::Occupied(mut entry) => {
207 match entry.get_mut() {
208 #[cfg(not(parallel_compiler))]
209 QueryResult::Started(job) => {
213 // If we are single-threaded we know that we have cycle error,
214 // so we just return the error.
215 return TryGetJob::Cycle(id.find_cycle_in_stack(
216 qcx.try_collect_active_jobs().unwrap(),
217 &qcx.current_query_job(),
221 #[cfg(parallel_compiler)]
222 QueryResult::Started(job) => {
223 // For parallel queries, we'll block and wait until the query running
224 // in another thread has completed. Record how long we wait in the
226 let query_blocked_prof_timer = qcx.dep_context().profiler().query_blocked();
229 let latch = job.latch();
233 // With parallel queries we might just have to wait on some other
235 let result = latch.wait_on(qcx.current_query_job(), span);
238 Ok(()) => TryGetJob::JobCompleted(query_blocked_prof_timer),
239 Err(cycle) => TryGetJob::Cycle(cycle),
242 QueryResult::Poisoned => FatalError.raise(),
248 /// Completes the query by updating the query cache with the `result`,
249 /// signals the waiter and forgets the JobOwner, so it won't poison the query
250 fn complete<C>(self, cache: &C, result: C::Value, dep_node_index: DepNodeIndex) -> C::Stored
252 C: QueryCache<Key = K>,
254 // We can move out of `self` here because we `mem::forget` it below
255 let key = unsafe { ptr::read(&self.key) };
256 let state = self.state;
258 // Forget ourself so our destructor won't poison the query
261 let (job, result) = {
263 #[cfg(parallel_compiler)]
264 let mut lock = state.active.get_shard_by_value(&key).lock();
265 #[cfg(not(parallel_compiler))]
266 let mut lock = state.active.lock();
267 match lock.remove(&key).unwrap() {
268 QueryResult::Started(job) => job,
269 QueryResult::Poisoned => panic!(),
272 let result = cache.complete(key, result, dep_node_index);
276 job.signal_complete();
281 impl<'tcx, K> Drop for JobOwner<'tcx, K>
283 K: Eq + Hash + Clone,
288 // Poison the query so jobs waiting on it panic.
289 let state = self.state;
291 #[cfg(parallel_compiler)]
292 let mut shard = state.active.get_shard_by_value(&self.key).lock();
293 #[cfg(not(parallel_compiler))]
294 let mut shard = state.active.lock();
295 let job = match shard.remove(&self.key).unwrap() {
296 QueryResult::Started(job) => job,
297 QueryResult::Poisoned => panic!(),
299 shard.insert(self.key.clone(), QueryResult::Poisoned);
302 // Also signal the completion of the job, so waiters
303 // will continue execution.
304 job.signal_complete();
309 pub(crate) struct CycleError {
310 /// The query and related span that uses the cycle.
311 pub usage: Option<(Span, QueryStackFrame)>,
312 pub cycle: Vec<QueryInfo>,
315 /// The result of `try_start`.
316 enum TryGetJob<'tcx, K>
318 K: Eq + Hash + Clone,
320 /// The query is not yet started. Contains a guard to the cache eventually used to start it.
321 NotYetStarted(JobOwner<'tcx, K>),
323 /// The query was already completed.
324 /// Returns the result of the query and its dep-node index
325 /// if it succeeded or a cycle error if it failed.
326 #[cfg(parallel_compiler)]
327 JobCompleted(TimingGuard<'tcx>),
329 /// Trying to execute the query resulted in a cycle.
333 /// Checks if the query is already computed and in the cache.
334 /// It returns the shard index and a lock guard to the shard,
335 /// which will be used if the query is not in the cache and we need
338 pub fn try_get_cached<'a, Tcx, C, R, OnHit>(
342 // `on_hit` can be called while holding a lock to the query cache
348 OnHit: FnOnce(&C::Stored) -> R,
350 cache.lookup(&key, |value, index| {
351 if std::intrinsics::unlikely(tcx.profiler().enabled()) {
352 tcx.profiler().query_cache_hit(index.into());
354 tcx.dep_graph().read_index(index);
359 fn try_execute_query<Qcx, C>(
361 state: &QueryState<C::Key>,
365 dep_node: Option<DepNode<Qcx::DepKind>>,
366 query: &QueryVTable<Qcx, C::Key, C::Value>,
367 ) -> (C::Stored, Option<DepNodeIndex>)
370 C::Key: Clone + DepNodeParams<Qcx::DepContext>,
371 C::Value: Value<Qcx::DepContext>,
374 match JobOwner::<'_, C::Key>::try_start(&qcx, state, span, key.clone()) {
375 TryGetJob::NotYetStarted(job) => {
376 let (result, dep_node_index) = execute_job(qcx, key, dep_node, query, job.id);
377 let result = job.complete(cache, result, dep_node_index);
378 (result, Some(dep_node_index))
380 TryGetJob::Cycle(error) => {
381 let result = mk_cycle(qcx, error, query.handle_cycle_error, cache);
384 #[cfg(parallel_compiler)]
385 TryGetJob::JobCompleted(query_blocked_prof_timer) => {
386 let (v, index) = cache
387 .lookup(&key, |value, index| (value.clone(), index))
388 .unwrap_or_else(|_| panic!("value must be in cache after waiting"));
390 if std::intrinsics::unlikely(qcx.dep_context().profiler().enabled()) {
391 qcx.dep_context().profiler().query_cache_hit(index.into());
393 query_blocked_prof_timer.finish_with_query_invocation_id(index.into());
400 fn execute_job<Qcx, K, V>(
403 mut dep_node_opt: Option<DepNode<Qcx::DepKind>>,
404 query: &QueryVTable<Qcx, K, V>,
406 ) -> (V, DepNodeIndex)
408 K: Clone + DepNodeParams<Qcx::DepContext>,
412 let dep_graph = qcx.dep_context().dep_graph();
414 // Fast path for when incr. comp. is off.
415 if !dep_graph.is_fully_enabled() {
416 let prof_timer = qcx.dep_context().profiler().query_provider();
417 let result = qcx.start_query(job_id, query.depth_limit, None, || {
418 query.compute(*qcx.dep_context(), key)
420 let dep_node_index = dep_graph.next_virtual_depnode_index();
421 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
422 return (result, dep_node_index);
425 if !query.anon && !query.eval_always {
426 // `to_dep_node` is expensive for some `DepKind`s.
428 dep_node_opt.get_or_insert_with(|| query.to_dep_node(*qcx.dep_context(), &key));
430 // The diagnostics for this query will be promoted to the current session during
431 // `try_mark_green()`, so we can ignore them here.
432 if let Some(ret) = qcx.start_query(job_id, false, None, || {
433 try_load_from_disk_and_cache_in_memory(qcx, &key, &dep_node, query)
439 let prof_timer = qcx.dep_context().profiler().query_provider();
440 let diagnostics = Lock::new(ThinVec::new());
442 let (result, dep_node_index) =
443 qcx.start_query(job_id, query.depth_limit, Some(&diagnostics), || {
445 return dep_graph.with_anon_task(*qcx.dep_context(), query.dep_kind, || {
446 query.compute(*qcx.dep_context(), key)
450 // `to_dep_node` is expensive for some `DepKind`s.
452 dep_node_opt.unwrap_or_else(|| query.to_dep_node(*qcx.dep_context(), &key));
454 dep_graph.with_task(dep_node, *qcx.dep_context(), key, query.compute, query.hash_result)
457 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
459 let diagnostics = diagnostics.into_inner();
460 let side_effects = QuerySideEffects { diagnostics };
462 if std::intrinsics::unlikely(!side_effects.is_empty()) {
464 qcx.store_side_effects_for_anon_node(dep_node_index, side_effects);
466 qcx.store_side_effects(dep_node_index, side_effects);
470 (result, dep_node_index)
473 fn try_load_from_disk_and_cache_in_memory<Qcx, K, V>(
476 dep_node: &DepNode<Qcx::DepKind>,
477 query: &QueryVTable<Qcx, K, V>,
478 ) -> Option<(V, DepNodeIndex)>
484 // Note this function can be called concurrently from the same query
485 // We must ensure that this is handled correctly.
487 let dep_graph = qcx.dep_context().dep_graph();
488 let (prev_dep_node_index, dep_node_index) = dep_graph.try_mark_green(qcx, &dep_node)?;
490 debug_assert!(dep_graph.is_green(dep_node));
492 // First we try to load the result from the on-disk cache.
493 // Some things are never cached on disk.
494 if let Some(try_load_from_disk) = query.try_load_from_disk {
495 let prof_timer = qcx.dep_context().profiler().incr_cache_loading();
497 // The call to `with_query_deserialization` enforces that no new `DepNodes`
498 // are created during deserialization. See the docs of that method for more
501 dep_graph.with_query_deserialization(|| try_load_from_disk(qcx, prev_dep_node_index));
503 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
505 if let Some(result) = result {
506 if std::intrinsics::unlikely(
507 qcx.dep_context().sess().opts.unstable_opts.query_dep_graph,
509 dep_graph.mark_debug_loaded_from_disk(*dep_node)
512 let prev_fingerprint = qcx
515 .prev_fingerprint_of(dep_node)
516 .unwrap_or(Fingerprint::ZERO);
517 // If `-Zincremental-verify-ich` is specified, re-hash results from
518 // the cache and make sure that they have the expected fingerprint.
520 // If not, we still seek to verify a subset of fingerprints loaded
521 // from disk. Re-hashing results is fairly expensive, so we can't
522 // currently afford to verify every hash. This subset should still
523 // give us some coverage of potential bugs though.
524 let try_verify = prev_fingerprint.as_value().1 % 32 == 0;
525 if std::intrinsics::unlikely(
526 try_verify || qcx.dep_context().sess().opts.unstable_opts.incremental_verify_ich,
528 incremental_verify_ich(*qcx.dep_context(), &result, dep_node, query);
531 return Some((result, dep_node_index));
534 // We always expect to find a cached result for things that
535 // can be forced from `DepNode`.
537 !qcx.dep_context().fingerprint_style(dep_node.kind).reconstructible(),
538 "missing on-disk cache entry for {:?}",
543 // We could not load a result from the on-disk cache, so
545 let prof_timer = qcx.dep_context().profiler().query_provider();
547 // The dep-graph for this computation is already in-place.
548 let result = dep_graph.with_ignore(|| query.compute(*qcx.dep_context(), key.clone()));
550 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
552 // Verify that re-running the query produced a result with the expected hash
553 // This catches bugs in query implementations, turning them into ICEs.
554 // For example, a query might sort its result by `DefId` - since `DefId`s are
555 // not stable across compilation sessions, the result could get up getting sorted
556 // in a different order when the query is re-run, even though all of the inputs
557 // (e.g. `DefPathHash` values) were green.
559 // See issue #82920 for an example of a miscompilation that would get turned into
560 // an ICE by this check
561 incremental_verify_ich(*qcx.dep_context(), &result, dep_node, query);
563 Some((result, dep_node_index))
566 #[instrument(skip(qcx, result, query), level = "debug")]
567 fn incremental_verify_ich<Qcx, K, V: Debug>(
568 qcx: Qcx::DepContext,
570 dep_node: &DepNode<Qcx::DepKind>,
571 query: &QueryVTable<Qcx, K, V>,
576 qcx.dep_graph().is_green(dep_node),
577 "fingerprint for green query instance not loaded from cache: {:?}",
581 let new_hash = query.hash_result.map_or(Fingerprint::ZERO, |f| {
582 qcx.with_stable_hashing_context(|mut hcx| f(&mut hcx, result))
585 let old_hash = qcx.dep_graph().prev_fingerprint_of(dep_node);
587 if Some(new_hash) != old_hash {
588 incremental_verify_ich_failed(
590 DebugArg::from(&dep_node),
591 DebugArg::from(&result),
596 // This DebugArg business is largely a mirror of std::fmt::ArgumentV1, which is
597 // currently not exposed publicly.
599 // The PR which added this attempted to use `&dyn Debug` instead, but that
600 // showed statistically significant worse compiler performance. It's not
601 // actually clear what the cause there was -- the code should be cold. If this
602 // can be replaced with `&dyn Debug` with on perf impact, then it probably
608 struct DebugArg<'a> {
610 fmt: fn(&Opaque, &mut std::fmt::Formatter<'_>) -> std::fmt::Result,
613 impl<'a, T> From<&'a T> for DebugArg<'a>
617 fn from(value: &'a T) -> DebugArg<'a> {
619 value: unsafe { std::mem::transmute(value) },
621 std::mem::transmute(<T as std::fmt::Debug>::fmt as fn(_, _) -> std::fmt::Result)
627 impl std::fmt::Debug for DebugArg<'_> {
628 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
629 (self.fmt)(self.value, f)
633 // Note that this is marked #[cold] and intentionally takes the equivalent of
634 // `dyn Debug` for its arguments, as we want to avoid generating a bunch of
635 // different implementations for LLVM to chew on (and filling up the final
638 fn incremental_verify_ich_failed(sess: &Session, dep_node: DebugArg<'_>, result: DebugArg<'_>) {
639 // When we emit an error message and panic, we try to debug-print the `DepNode`
640 // and query result. Unfortunately, this can cause us to run additional queries,
641 // which may result in another fingerprint mismatch while we're in the middle
642 // of processing this one. To avoid a double-panic (which kills the process
643 // before we can print out the query static), we print out a terse
644 // but 'safe' message if we detect a re-entrant call to this method.
646 static INSIDE_VERIFY_PANIC: Cell<bool> = const { Cell::new(false) };
649 let old_in_panic = INSIDE_VERIFY_PANIC.with(|in_panic| in_panic.replace(true));
652 sess.emit_err(crate::error::Reentrant);
654 let run_cmd = if let Some(crate_name) = &sess.opts.crate_name {
655 format!("`cargo clean -p {}` or `cargo clean`", crate_name)
657 "`cargo clean`".to_string()
660 sess.emit_err(crate::error::IncrementCompilation {
662 dep_node: format!("{:?}", dep_node),
664 panic!("Found unstable fingerprints for {:?}: {:?}", dep_node, result);
667 INSIDE_VERIFY_PANIC.with(|in_panic| in_panic.set(old_in_panic));
670 /// Ensure that either this query has all green inputs or been executed.
671 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
672 /// Returns true if the query should still run.
674 /// This function is particularly useful when executing passes for their
675 /// side-effects -- e.g., in order to report errors for erroneous programs.
677 /// Note: The optimization is only available during incr. comp.
679 fn ensure_must_run<Qcx, K, V>(
682 query: &QueryVTable<Qcx, K, V>,
683 ) -> (bool, Option<DepNode<Qcx::DepKind>>)
685 K: crate::dep_graph::DepNodeParams<Qcx::DepContext>,
688 if query.eval_always {
692 // Ensuring an anonymous query makes no sense
693 assert!(!query.anon);
695 let dep_node = query.to_dep_node(*qcx.dep_context(), key);
697 let dep_graph = qcx.dep_context().dep_graph();
698 match dep_graph.try_mark_green(qcx, &dep_node) {
700 // A None return from `try_mark_green` means that this is either
701 // a new dep node or that the dep node has already been marked red.
702 // Either way, we can't call `dep_graph.read()` as we don't have the
703 // DepNodeIndex. We must invoke the query itself. The performance cost
704 // this introduces should be negligible as we'll immediately hit the
705 // in-memory cache, or another query down the line will.
706 (true, Some(dep_node))
708 Some((_, dep_node_index)) => {
709 dep_graph.read_index(dep_node_index);
710 qcx.dep_context().profiler().query_cache_hit(dep_node_index.into());
722 pub fn get_query<Q, Qcx>(qcx: Qcx, span: Span, key: Q::Key, mode: QueryMode) -> Option<Q::Stored>
725 Q::Key: DepNodeParams<Qcx::DepContext>,
726 Q::Value: Value<Qcx::DepContext>,
729 let query = Q::make_vtable(qcx, &key);
730 let dep_node = if let QueryMode::Ensure = mode {
731 let (must_run, dep_node) = ensure_must_run(qcx, &key, &query);
740 let (result, dep_node_index) = try_execute_query(
749 if let Some(dep_node_index) = dep_node_index {
750 qcx.dep_context().dep_graph().read_index(dep_node_index)
755 pub fn force_query<Q, Qcx>(qcx: Qcx, key: Q::Key, dep_node: DepNode<Qcx::DepKind>)
758 Q::Key: DepNodeParams<Qcx::DepContext>,
759 Q::Value: Value<Qcx::DepContext>,
762 // We may be concurrently trying both execute and force a query.
763 // Ensure that only one of them runs the query.
764 let cache = Q::query_cache(qcx);
765 let cached = cache.lookup(&key, |_, index| {
766 if std::intrinsics::unlikely(qcx.dep_context().profiler().enabled()) {
767 qcx.dep_context().profiler().query_cache_hit(index.into());
776 let query = Q::make_vtable(qcx, &key);
777 let state = Q::query_state(qcx);
778 debug_assert!(!query.anon);
780 try_execute_query(qcx, state, cache, DUMMY_SP, key, Some(dep_node), &query);