Skip to main content

rustc_query_impl/
execution.rs

1use std::hash::Hash;
2use std::mem;
3
4use rustc_data_structures::hash_table::{Entry, HashTable};
5use rustc_data_structures::stack::ensure_sufficient_stack;
6use rustc_data_structures::sync::{DynSend, DynSync};
7use rustc_data_structures::{outline, sharded, sync};
8use rustc_errors::{FatalError, StashKey};
9use rustc_middle::dep_graph::{DepGraphData, DepNodeKey, SerializedDepNodeIndex};
10use rustc_middle::query::plumbing::QueryVTable;
11use rustc_middle::query::{
12    ActiveKeyStatus, CycleError, CycleErrorHandling, EnsureMode, QueryCache, QueryJob, QueryJobId,
13    QueryKey, QueryLatch, QueryMode, QueryState,
14};
15use rustc_middle::ty::TyCtxt;
16use rustc_middle::verify_ich::incremental_verify_ich;
17use rustc_span::{DUMMY_SP, Span};
18
19use crate::collect_active_jobs_from_all_queries;
20use crate::dep_graph::{DepNode, DepNodeIndex};
21use crate::job::{QueryJobInfo, QueryJobMap, find_cycle_in_stack, report_cycle};
22use crate::plumbing::{current_query_job, next_job_id, start_query};
23
24#[inline]
25fn equivalent_key<K: Eq, V>(k: &K) -> impl Fn(&(K, V)) -> bool + '_ {
26    move |x| x.0 == *k
27}
28
29/// Obtains the enclosed [`QueryJob`], or panics if this query evaluation
30/// was poisoned by a panic.
31fn expect_job<'tcx>(status: ActiveKeyStatus<'tcx>) -> QueryJob<'tcx> {
32    match status {
33        ActiveKeyStatus::Started(job) => job,
34        ActiveKeyStatus::Poisoned => {
35            {
    ::core::panicking::panic_fmt(format_args!("job for query failed to start and was poisoned"));
}panic!("job for query failed to start and was poisoned")
36        }
37    }
38}
39
40pub(crate) fn all_inactive<'tcx, K>(state: &QueryState<'tcx, K>) -> bool {
41    state.active.lock_shards().all(|shard| shard.is_empty())
42}
43
44/// Internal plumbing for collecting the set of active jobs for this query.
45///
46/// Should only be called from `collect_active_jobs_from_all_queries`.
47///
48/// (We arbitrarily use the word "gather" when collecting the jobs for
49/// each individual query, so that we have distinct function names to
50/// grep for.)
51pub(crate) fn gather_active_jobs<'tcx, C>(
52    query: &'tcx QueryVTable<'tcx, C>,
53    tcx: TyCtxt<'tcx>,
54    require_complete: bool,
55    job_map_out: &mut QueryJobMap<'tcx>, // Out-param; job info is gathered into this map
56) -> Option<()>
57where
58    C: QueryCache<Key: QueryKey + DynSend + DynSync>,
59    QueryVTable<'tcx, C>: DynSync,
60{
61    let mut active = Vec::new();
62
63    // Helper to gather active jobs from a single shard.
64    let mut gather_shard_jobs = |shard: &HashTable<(C::Key, ActiveKeyStatus<'tcx>)>| {
65        for (k, v) in shard.iter() {
66            if let ActiveKeyStatus::Started(ref job) = *v {
67                active.push((*k, job.clone()));
68            }
69        }
70    };
71
72    // Lock shards and gather jobs from each shard.
73    if require_complete {
74        for shard in query.state.active.lock_shards() {
75            gather_shard_jobs(&shard);
76        }
77    } else {
78        // We use try_lock_shards here since we are called from the
79        // deadlock handler, and this shouldn't be locked.
80        for shard in query.state.active.try_lock_shards() {
81            // This can be called during unwinding, and the function has a `try_`-prefix, so
82            // don't `unwrap()` here, just manually check for `None` and do best-effort error
83            // reporting.
84            match shard {
85                None => {
86                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_query_impl/src/execution.rs:86",
                        "rustc_query_impl::execution", ::tracing::Level::WARN,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_query_impl/src/execution.rs"),
                        ::tracing_core::__macro_support::Option::Some(86u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_query_impl::execution"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::WARN <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Failed to collect active jobs for query with name `{0}`!",
                                                    query.name) as &dyn Value))])
            });
    } else { ; }
};tracing::warn!(
87                        "Failed to collect active jobs for query with name `{}`!",
88                        query.name
89                    );
90                    return None;
91                }
92                Some(shard) => gather_shard_jobs(&shard),
93            }
94        }
95    }
96
97    // Call `make_frame` while we're not holding a `state.active` lock as `make_frame` may call
98    // queries leading to a deadlock.
99    for (key, job) in active {
100        let frame = crate::plumbing::create_deferred_query_stack_frame(tcx, query, key);
101        job_map_out.insert(job.id, QueryJobInfo { frame, job });
102    }
103
104    Some(())
105}
106
107/// Guard object representing the responsibility to execute a query job and
108/// mark it as completed.
109///
110/// This will poison the relevant query key if it is dropped without calling
111/// [`Self::complete`].
112struct ActiveJobGuard<'tcx, K>
113where
114    K: Eq + Hash + Copy,
115{
116    state: &'tcx QueryState<'tcx, K>,
117    key: K,
118    key_hash: u64,
119}
120
121#[cold]
122#[inline(never)]
123fn mk_cycle<'tcx, C: QueryCache>(
124    query: &'tcx QueryVTable<'tcx, C>,
125    tcx: TyCtxt<'tcx>,
126    cycle_error: CycleError,
127) -> C::Value {
128    let error = report_cycle(tcx.sess, &cycle_error);
129    match query.cycle_error_handling {
130        CycleErrorHandling::Error => {
131            let guar = error.emit();
132            query.value_from_cycle_error(tcx, cycle_error, guar)
133        }
134        CycleErrorHandling::Fatal => {
135            let guar = error.emit();
136            guar.raise_fatal();
137        }
138        CycleErrorHandling::DelayBug => {
139            let guar = error.delay_as_bug();
140            query.value_from_cycle_error(tcx, cycle_error, guar)
141        }
142        CycleErrorHandling::Stash => {
143            let guar = if let Some(root) = cycle_error.cycle.first()
144                && let Some(span) = root.frame.info.span
145            {
146                error.stash(span, StashKey::Cycle).unwrap()
147            } else {
148                error.emit()
149            };
150            query.value_from_cycle_error(tcx, cycle_error, guar)
151        }
152    }
153}
154
155impl<'tcx, K> ActiveJobGuard<'tcx, K>
156where
157    K: Eq + Hash + Copy,
158{
159    /// Completes the query by updating the query cache with the `result`,
160    /// signals the waiter, and forgets the guard so it won't poison the query.
161    fn complete<C>(self, cache: &C, result: C::Value, dep_node_index: DepNodeIndex)
162    where
163        C: QueryCache<Key = K>,
164    {
165        // Forget ourself so our destructor won't poison the query.
166        // (Extract fields by value first to make sure we don't leak anything.)
167        let Self { state, key, key_hash }: Self = self;
168        mem::forget(self);
169
170        // Mark as complete before we remove the job from the active state
171        // so no other thread can re-execute this query.
172        cache.complete(key, result, dep_node_index);
173
174        let job = {
175            // don't keep the lock during the `unwrap()` of the retrieved value, or we taint the
176            // underlying shard.
177            // since unwinding also wants to look at this map, this can also prevent a double
178            // panic.
179            let mut shard = state.active.lock_shard_by_hash(key_hash);
180            match shard.find_entry(key_hash, equivalent_key(&key)) {
181                Err(_) => None,
182                Ok(occupied) => Some(occupied.remove().0.1),
183            }
184        };
185        let job = expect_job(job.expect("active query job entry"));
186
187        job.signal_complete();
188    }
189}
190
191impl<'tcx, K> Drop for ActiveJobGuard<'tcx, K>
192where
193    K: Eq + Hash + Copy,
194{
195    #[inline(never)]
196    #[cold]
197    fn drop(&mut self) {
198        // Poison the query so jobs waiting on it panic.
199        let Self { state, key, key_hash } = *self;
200        let job = {
201            let mut shard = state.active.lock_shard_by_hash(key_hash);
202            match shard.find_entry(key_hash, equivalent_key(&key)) {
203                Err(_) => ::core::panicking::panic("explicit panic")panic!(),
204                Ok(occupied) => {
205                    let ((key, value), vacant) = occupied.remove();
206                    vacant.insert((key, ActiveKeyStatus::Poisoned));
207                    expect_job(value)
208                }
209            }
210        };
211        // Also signal the completion of the job, so waiters
212        // will continue execution.
213        job.signal_complete();
214    }
215}
216
217#[cold]
218#[inline(never)]
219fn cycle_error<'tcx, C: QueryCache>(
220    query: &'tcx QueryVTable<'tcx, C>,
221    tcx: TyCtxt<'tcx>,
222    try_execute: QueryJobId,
223    span: Span,
224) -> (C::Value, Option<DepNodeIndex>) {
225    // Ensure there was no errors collecting all active jobs.
226    // We need the complete map to ensure we find a cycle to break.
227    let job_map = collect_active_jobs_from_all_queries(tcx, false)
228        .ok()
229        .expect("failed to collect active queries");
230
231    let error = find_cycle_in_stack(try_execute, job_map, &current_query_job(tcx), span);
232    (mk_cycle(query, tcx, error.lift()), None)
233}
234
235#[inline(always)]
236fn wait_for_query<'tcx, C: QueryCache>(
237    query: &'tcx QueryVTable<'tcx, C>,
238    tcx: TyCtxt<'tcx>,
239    span: Span,
240    key: C::Key,
241    latch: QueryLatch<'tcx>,
242    current: Option<QueryJobId>,
243) -> (C::Value, Option<DepNodeIndex>) {
244    // For parallel queries, we'll block and wait until the query running
245    // in another thread has completed. Record how long we wait in the
246    // self-profiler.
247    let query_blocked_prof_timer = tcx.prof.query_blocked();
248
249    // With parallel queries we might just have to wait on some other
250    // thread.
251    let result = latch.wait_on(tcx, current, span);
252
253    match result {
254        Ok(()) => {
255            let Some((v, index)) = query.cache.lookup(&key) else {
256                outline(|| {
257                    // We didn't find the query result in the query cache. Check if it was
258                    // poisoned due to a panic instead.
259                    let key_hash = sharded::make_hash(&key);
260                    let shard = query.state.active.lock_shard_by_hash(key_hash);
261                    match shard.find(key_hash, equivalent_key(&key)) {
262                        // The query we waited on panicked. Continue unwinding here.
263                        Some((_, ActiveKeyStatus::Poisoned)) => FatalError.raise(),
264                        _ => {
    ::core::panicking::panic_fmt(format_args!("query \'{0}\' result must be in the cache or the query must be poisoned after a wait",
            query.name));
}panic!(
265                            "query '{}' result must be in the cache or the query must be poisoned after a wait",
266                            query.name
267                        ),
268                    }
269                })
270            };
271
272            tcx.prof.query_cache_hit(index.into());
273            query_blocked_prof_timer.finish_with_query_invocation_id(index.into());
274
275            (v, Some(index))
276        }
277        Err(cycle) => (mk_cycle(query, tcx, cycle.lift()), None),
278    }
279}
280
281/// Shared main part of both [`execute_query_incr_inner`] and [`execute_query_non_incr_inner`].
282#[inline(never)]
283fn try_execute_query<'tcx, C: QueryCache, const INCR: bool>(
284    query: &'tcx QueryVTable<'tcx, C>,
285    tcx: TyCtxt<'tcx>,
286    span: Span,
287    key: C::Key,
288    // If present, some previous step has already created a `DepNode` for this
289    // query+key, which we should reuse instead of creating a new one.
290    dep_node: Option<DepNode>,
291) -> (C::Value, Option<DepNodeIndex>) {
292    let key_hash = sharded::make_hash(&key);
293    let mut state_lock = query.state.active.lock_shard_by_hash(key_hash);
294
295    // For the parallel compiler we need to check both the query cache and query state structures
296    // while holding the state lock to ensure that 1) the query has not yet completed and 2) the
297    // query is not still executing. Without checking the query cache here, we can end up
298    // re-executing the query since `try_start` only checks that the query is not currently
299    // executing, but another thread may have already completed the query and stores it result
300    // in the query cache.
301    if tcx.sess.threads() > 1 {
302        if let Some((value, index)) = query.cache.lookup(&key) {
303            tcx.prof.query_cache_hit(index.into());
304            return (value, Some(index));
305        }
306    }
307
308    let current_job_id = current_query_job(tcx);
309
310    match state_lock.entry(key_hash, equivalent_key(&key), |(k, _)| sharded::make_hash(k)) {
311        Entry::Vacant(entry) => {
312            // Nothing has computed or is computing the query, so we start a new job and insert it in the
313            // state map.
314            let id = next_job_id(tcx);
315            let job = QueryJob::new(id, span, current_job_id);
316            entry.insert((key, ActiveKeyStatus::Started(job)));
317
318            // Drop the lock before we start executing the query
319            drop(state_lock);
320
321            execute_job::<C, INCR>(query, tcx, key, key_hash, id, dep_node)
322        }
323        Entry::Occupied(mut entry) => {
324            match &mut entry.get_mut().1 {
325                ActiveKeyStatus::Started(job) => {
326                    if sync::is_dyn_thread_safe() {
327                        // Get the latch out
328                        let latch = job.latch();
329                        drop(state_lock);
330
331                        // Only call `wait_for_query` if we're using a Rayon thread pool
332                        // as it will attempt to mark the worker thread as blocked.
333                        wait_for_query(query, tcx, span, key, latch, current_job_id)
334                    } else {
335                        let id = job.id;
336                        drop(state_lock);
337
338                        // If we are single-threaded we know that we have cycle error,
339                        // so we just return the error.
340                        cycle_error(query, tcx, id, span)
341                    }
342                }
343                ActiveKeyStatus::Poisoned => FatalError.raise(),
344            }
345        }
346    }
347}
348
349#[inline(always)]
350fn execute_job<'tcx, C: QueryCache, const INCR: bool>(
351    query: &'tcx QueryVTable<'tcx, C>,
352    tcx: TyCtxt<'tcx>,
353    key: C::Key,
354    key_hash: u64,
355    id: QueryJobId,
356    dep_node: Option<DepNode>,
357) -> (C::Value, Option<DepNodeIndex>) {
358    // Set up a guard object that will automatically poison the query if a
359    // panic occurs while executing the query (or any intermediate plumbing).
360    let job_guard = ActiveJobGuard { state: &query.state, key, key_hash };
361
362    if true {
    match (&tcx.dep_graph.is_fully_enabled(), &INCR) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(tcx.dep_graph.is_fully_enabled(), INCR);
363
364    // Delegate to another function to actually execute the query job.
365    let (value, dep_node_index) = if INCR {
366        execute_job_incr(query, tcx, key, dep_node, id)
367    } else {
368        execute_job_non_incr(query, tcx, key, id)
369    };
370
371    let cache = &query.cache;
372    if query.feedable {
373        // We should not compute queries that also got a value via feeding.
374        // This can't happen, as query feeding adds the very dependencies to the fed query
375        // as its feeding query had. So if the fed query is red, so is its feeder, which will
376        // get evaluated first, and re-feed the query.
377        if let Some((cached_value, _)) = cache.lookup(&key) {
378            let Some(hash_value_fn) = query.hash_value_fn else {
379                {
    ::core::panicking::panic_fmt(format_args!("no_hash fed query later has its value computed.\nRemove `no_hash` modifier to allow recomputation.\nThe already cached value: {0}",
            (query.format_value)(&cached_value)));
};panic!(
380                    "no_hash fed query later has its value computed.\n\
381                    Remove `no_hash` modifier to allow recomputation.\n\
382                    The already cached value: {}",
383                    (query.format_value)(&cached_value)
384                );
385            };
386
387            let (old_hash, new_hash) = tcx.with_stable_hashing_context(|mut hcx| {
388                (hash_value_fn(&mut hcx, &cached_value), hash_value_fn(&mut hcx, &value))
389            });
390            let formatter = query.format_value;
391            if old_hash != new_hash {
392                // We have an inconsistency. This can happen if one of the two
393                // results is tainted by errors.
394                if !tcx.dcx().has_errors().is_some() {
    {
        ::core::panicking::panic_fmt(format_args!("Computed query value for {0:?}({1:?}) is inconsistent with fed value,\ncomputed={2:#?}\nfed={3:#?}",
                query.dep_kind, key, formatter(&value),
                formatter(&cached_value)));
    }
};assert!(
395                    tcx.dcx().has_errors().is_some(),
396                    "Computed query value for {:?}({:?}) is inconsistent with fed value,\n\
397                        computed={:#?}\nfed={:#?}",
398                    query.dep_kind,
399                    key,
400                    formatter(&value),
401                    formatter(&cached_value),
402                );
403            }
404        }
405    }
406
407    // Tell the guard to perform completion bookkeeping, and also to not poison the query.
408    job_guard.complete(cache, value, dep_node_index);
409
410    (value, Some(dep_node_index))
411}
412
413// Fast path for when incr. comp. is off.
414#[inline(always)]
415fn execute_job_non_incr<'tcx, C: QueryCache>(
416    query: &'tcx QueryVTable<'tcx, C>,
417    tcx: TyCtxt<'tcx>,
418    key: C::Key,
419    job_id: QueryJobId,
420) -> (C::Value, DepNodeIndex) {
421    if true {
    if !!tcx.dep_graph.is_fully_enabled() {
        ::core::panicking::panic("assertion failed: !tcx.dep_graph.is_fully_enabled()")
    };
};debug_assert!(!tcx.dep_graph.is_fully_enabled());
422
423    let prof_timer = tcx.prof.query_provider();
424    // Call the query provider.
425    let value =
426        start_query(tcx, job_id, query.depth_limit, || (query.invoke_provider_fn)(tcx, key));
427    let dep_node_index = tcx.dep_graph.next_virtual_depnode_index();
428    prof_timer.finish_with_query_invocation_id(dep_node_index.into());
429
430    // Sanity: Fingerprint the key and the result to assert they don't contain anything unhashable.
431    if truecfg!(debug_assertions) {
432        let _ = key.to_fingerprint(tcx);
433        if let Some(hash_value_fn) = query.hash_value_fn {
434            tcx.with_stable_hashing_context(|mut hcx| {
435                hash_value_fn(&mut hcx, &value);
436            });
437        }
438    }
439
440    (value, dep_node_index)
441}
442
443#[inline(always)]
444fn execute_job_incr<'tcx, C: QueryCache>(
445    query: &'tcx QueryVTable<'tcx, C>,
446    tcx: TyCtxt<'tcx>,
447    key: C::Key,
448    mut dep_node_opt: Option<DepNode>,
449    job_id: QueryJobId,
450) -> (C::Value, DepNodeIndex) {
451    let dep_graph_data =
452        tcx.dep_graph.data().expect("should always be present in incremental mode");
453
454    if !query.anon && !query.eval_always {
455        // `to_dep_node` is expensive for some `DepKind`s.
456        let dep_node = dep_node_opt.get_or_insert_with(|| query.construct_dep_node(tcx, &key));
457
458        // The diagnostics for this query will be promoted to the current session during
459        // `try_mark_green()`, so we can ignore them here.
460        if let Some(ret) = start_query(tcx, job_id, false, || try {
461            let (prev_index, dep_node_index) = dep_graph_data.try_mark_green(tcx, dep_node)?;
462            let value = load_from_disk_or_invoke_provider_green(
463                tcx,
464                dep_graph_data,
465                query,
466                &key,
467                dep_node,
468                prev_index,
469                dep_node_index,
470            );
471            (value, dep_node_index)
472        }) {
473            return ret;
474        }
475    }
476
477    let prof_timer = tcx.prof.query_provider();
478
479    let (result, dep_node_index) = start_query(tcx, job_id, query.depth_limit, || {
480        if query.anon {
481            // Call the query provider inside an anon task.
482            return dep_graph_data.with_anon_task_inner(tcx, query.dep_kind, || {
483                (query.invoke_provider_fn)(tcx, key)
484            });
485        }
486
487        // `to_dep_node` is expensive for some `DepKind`s.
488        let dep_node = dep_node_opt.unwrap_or_else(|| query.construct_dep_node(tcx, &key));
489
490        // Call the query provider.
491        dep_graph_data.with_task(
492            dep_node,
493            tcx,
494            (query, key),
495            |tcx, (query, key)| (query.invoke_provider_fn)(tcx, key),
496            query.hash_value_fn,
497        )
498    });
499
500    prof_timer.finish_with_query_invocation_id(dep_node_index.into());
501
502    (result, dep_node_index)
503}
504
505/// Given that the dep node for this query+key is green, obtain a value for it
506/// by loading one from disk if possible, or by invoking its query provider if
507/// necessary.
508#[inline(always)]
509fn load_from_disk_or_invoke_provider_green<'tcx, C: QueryCache>(
510    tcx: TyCtxt<'tcx>,
511    dep_graph_data: &DepGraphData,
512    query: &'tcx QueryVTable<'tcx, C>,
513    key: &C::Key,
514    dep_node: &DepNode,
515    prev_index: SerializedDepNodeIndex,
516    dep_node_index: DepNodeIndex,
517) -> C::Value {
518    // Note this function can be called concurrently from the same query
519    // We must ensure that this is handled correctly.
520
521    if true {
    if !dep_graph_data.is_index_green(prev_index) {
        ::core::panicking::panic("assertion failed: dep_graph_data.is_index_green(prev_index)")
    };
};debug_assert!(dep_graph_data.is_index_green(prev_index));
522
523    // First we try to load the result from the on-disk cache.
524    // Some things are never cached on disk.
525    if let Some(value) = query.try_load_from_disk(tcx, key, prev_index, dep_node_index) {
526        if std::intrinsics::unlikely(tcx.sess.opts.unstable_opts.query_dep_graph) {
527            dep_graph_data.mark_debug_loaded_from_disk(*dep_node)
528        }
529
530        let prev_fingerprint = dep_graph_data.prev_value_fingerprint_of(prev_index);
531        // If `-Zincremental-verify-ich` is specified, re-hash results from
532        // the cache and make sure that they have the expected fingerprint.
533        //
534        // If not, we still seek to verify a subset of fingerprints loaded
535        // from disk. Re-hashing results is fairly expensive, so we can't
536        // currently afford to verify every hash. This subset should still
537        // give us some coverage of potential bugs though.
538        let try_verify = prev_fingerprint.split().1.as_u64().is_multiple_of(32);
539        if std::intrinsics::unlikely(
540            try_verify || tcx.sess.opts.unstable_opts.incremental_verify_ich,
541        ) {
542            incremental_verify_ich(
543                tcx,
544                dep_graph_data,
545                &value,
546                prev_index,
547                query.hash_value_fn,
548                query.format_value,
549            );
550        }
551
552        return value;
553    }
554
555    // We always expect to find a cached result for things that
556    // can be forced from `DepNode`.
557    if true {
    if !(!query.will_cache_on_disk_for_key(tcx, key) ||
                !tcx.key_fingerprint_style(dep_node.kind).is_maybe_recoverable())
        {
        {
            ::core::panicking::panic_fmt(format_args!("missing on-disk cache entry for {0:?}",
                    dep_node));
        }
    };
};debug_assert!(
558        !query.will_cache_on_disk_for_key(tcx, key)
559            || !tcx.key_fingerprint_style(dep_node.kind).is_maybe_recoverable(),
560        "missing on-disk cache entry for {dep_node:?}"
561    );
562
563    // Sanity check for the logic in `ensure`: if the node is green and the result loadable,
564    // we should actually be able to load it.
565    if true {
    if !!query.is_loadable_from_disk(tcx, key, prev_index) {
        {
            ::core::panicking::panic_fmt(format_args!("missing on-disk cache entry for loadable {0:?}",
                    dep_node));
        }
    };
};debug_assert!(
566        !query.is_loadable_from_disk(tcx, key, prev_index),
567        "missing on-disk cache entry for loadable {dep_node:?}"
568    );
569
570    // We could not load a result from the on-disk cache, so
571    // recompute.
572    let prof_timer = tcx.prof.query_provider();
573
574    // The dep-graph for this computation is already in-place.
575    // Call the query provider.
576    let value = tcx.dep_graph.with_ignore(|| (query.invoke_provider_fn)(tcx, *key));
577
578    prof_timer.finish_with_query_invocation_id(dep_node_index.into());
579
580    // Verify that re-running the query produced a result with the expected hash
581    // This catches bugs in query implementations, turning them into ICEs.
582    // For example, a query might sort its result by `DefId` - since `DefId`s are
583    // not stable across compilation sessions, the result could get up getting sorted
584    // in a different order when the query is re-run, even though all of the inputs
585    // (e.g. `DefPathHash` values) were green.
586    //
587    // See issue #82920 for an example of a miscompilation that would get turned into
588    // an ICE by this check
589    incremental_verify_ich(
590        tcx,
591        dep_graph_data,
592        &value,
593        prev_index,
594        query.hash_value_fn,
595        query.format_value,
596    );
597
598    value
599}
600
601/// Return value struct for [`check_if_ensure_can_skip_execution`].
602struct EnsureCanSkip {
603    /// If true, the current `tcx.ensure_ok()` or `tcx.ensure_done()` query
604    /// can return early without actually trying to execute.
605    skip_execution: bool,
606    /// A dep node that was prepared while checking whether execution can be
607    /// skipped, to be reused by execution itself if _not_ skipped.
608    dep_node: Option<DepNode>,
609}
610
611/// Checks whether a `tcx.ensure_ok()` or `tcx.ensure_done()` query call can
612/// return early without actually trying to execute.
613///
614/// This only makes sense during incremental compilation, because it relies
615/// on having the dependency graph (and in some cases a disk-cached value)
616/// from the previous incr-comp session.
617#[inline(never)]
618fn check_if_ensure_can_skip_execution<'tcx, C: QueryCache>(
619    query: &'tcx QueryVTable<'tcx, C>,
620    tcx: TyCtxt<'tcx>,
621    key: &C::Key,
622    ensure_mode: EnsureMode,
623) -> EnsureCanSkip {
624    // Queries with `eval_always` should never skip execution.
625    if query.eval_always {
626        return EnsureCanSkip { skip_execution: false, dep_node: None };
627    }
628
629    // Ensuring an anonymous query makes no sense
630    if !!query.anon { ::core::panicking::panic("assertion failed: !query.anon") };assert!(!query.anon);
631
632    let dep_node = query.construct_dep_node(tcx, key);
633
634    let dep_graph = &tcx.dep_graph;
635    let serialized_dep_node_index = match dep_graph.try_mark_green(tcx, &dep_node) {
636        None => {
637            // A None return from `try_mark_green` means that this is either
638            // a new dep node or that the dep node has already been marked red.
639            // Either way, we can't call `dep_graph.read()` as we don't have the
640            // DepNodeIndex. We must invoke the query itself. The performance cost
641            // this introduces should be negligible as we'll immediately hit the
642            // in-memory cache, or another query down the line will.
643            return EnsureCanSkip { skip_execution: false, dep_node: Some(dep_node) };
644        }
645        Some((serialized_dep_node_index, dep_node_index)) => {
646            dep_graph.read_index(dep_node_index);
647            tcx.prof.query_cache_hit(dep_node_index.into());
648            serialized_dep_node_index
649        }
650    };
651
652    match ensure_mode {
653        EnsureMode::Ok => {
654            // In ensure-ok mode, we can skip execution for this key if the node
655            // is green. It must have succeeded in the previous session, and
656            // therefore would succeed in the current session if executed.
657            EnsureCanSkip { skip_execution: true, dep_node: None }
658        }
659        EnsureMode::Done => {
660            // In ensure-done mode, we can only skip execution for this key if
661            // there's a disk-cached value available to load later if needed,
662            // which guarantees the query provider will never run for this key.
663            let is_loadable = query.is_loadable_from_disk(tcx, key, serialized_dep_node_index);
664            EnsureCanSkip { skip_execution: is_loadable, dep_node: Some(dep_node) }
665        }
666    }
667}
668
669/// Called by a macro-generated impl of [`QueryVTable::execute_query_fn`],
670/// in non-incremental mode.
671#[inline(always)]
672pub(super) fn execute_query_non_incr_inner<'tcx, C: QueryCache>(
673    query: &'tcx QueryVTable<'tcx, C>,
674    tcx: TyCtxt<'tcx>,
675    span: Span,
676    key: C::Key,
677) -> C::Value {
678    if true {
    if !!tcx.dep_graph.is_fully_enabled() {
        ::core::panicking::panic("assertion failed: !tcx.dep_graph.is_fully_enabled()")
    };
};debug_assert!(!tcx.dep_graph.is_fully_enabled());
679
680    ensure_sufficient_stack(|| try_execute_query::<C, false>(query, tcx, span, key, None).0)
681}
682
683/// Called by a macro-generated impl of [`QueryVTable::execute_query_fn`],
684/// in incremental mode.
685#[inline(always)]
686pub(super) fn execute_query_incr_inner<'tcx, C: QueryCache>(
687    query: &'tcx QueryVTable<'tcx, C>,
688    tcx: TyCtxt<'tcx>,
689    span: Span,
690    key: C::Key,
691    mode: QueryMode,
692) -> Option<C::Value> {
693    if true {
    if !tcx.dep_graph.is_fully_enabled() {
        ::core::panicking::panic("assertion failed: tcx.dep_graph.is_fully_enabled()")
    };
};debug_assert!(tcx.dep_graph.is_fully_enabled());
694
695    // Check if query execution can be skipped, for `ensure_ok` or `ensure_done`.
696    // This might have the side-effect of creating a suitable DepNode, which
697    // we should reuse for execution instead of creating a new one.
698    let dep_node: Option<DepNode> = match mode {
699        QueryMode::Ensure { ensure_mode } => {
700            let EnsureCanSkip { skip_execution, dep_node } =
701                check_if_ensure_can_skip_execution(query, tcx, &key, ensure_mode);
702            if skip_execution {
703                // Return early to skip execution.
704                return None;
705            }
706            dep_node
707        }
708        QueryMode::Get => None,
709    };
710
711    let (result, dep_node_index) =
712        ensure_sufficient_stack(|| try_execute_query::<C, true>(query, tcx, span, key, dep_node));
713    if let Some(dep_node_index) = dep_node_index {
714        tcx.dep_graph.read_index(dep_node_index)
715    }
716    Some(result)
717}
718
719pub(crate) fn force_query<'tcx, C: QueryCache>(
720    query: &'tcx QueryVTable<'tcx, C>,
721    tcx: TyCtxt<'tcx>,
722    key: C::Key,
723    dep_node: DepNode,
724) {
725    // We may be concurrently trying both execute and force a query.
726    // Ensure that only one of them runs the query.
727    if let Some((_, index)) = query.cache.lookup(&key) {
728        tcx.prof.query_cache_hit(index.into());
729        return;
730    }
731
732    if true {
    if !!query.anon {
        ::core::panicking::panic("assertion failed: !query.anon")
    };
};debug_assert!(!query.anon);
733
734    ensure_sufficient_stack(|| {
735        try_execute_query::<C, true>(query, tcx, DUMMY_SP, key, Some(dep_node))
736    });
737}