]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_query_system/src/query/plumbing.rs
Auto merge of #107644 - Zoxc:query-cache-tweak, r=cjgillot
[rust.git] / compiler / rustc_query_system / src / query / plumbing.rs
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.
4
5 use crate::dep_graph::{DepContext, DepKind, DepNode, DepNodeIndex};
6 use crate::ich::StableHashingContext;
7 use crate::query::caches::QueryCache;
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};
22 use std::borrow::Borrow;
23 use std::cell::Cell;
24 use std::collections::hash_map::Entry;
25 use std::fmt::Debug;
26 use std::hash::Hash;
27 use std::mem;
28 use std::ptr;
29 use thin_vec::ThinVec;
30
31 use super::QueryConfig;
32
33 pub struct QueryState<K, D: DepKind> {
34     #[cfg(parallel_compiler)]
35     active: Sharded<FxHashMap<K, QueryResult<D>>>,
36     #[cfg(not(parallel_compiler))]
37     active: Lock<FxHashMap<K, QueryResult<D>>>,
38 }
39
40 /// Indicates the state of a query for a given key in a query map.
41 enum QueryResult<D: DepKind> {
42     /// An already executing query. The query job can be used to await for its completion.
43     Started(QueryJob<D>),
44
45     /// The query panicked. Queries trying to wait on this will raise a fatal error which will
46     /// silently panic.
47     Poisoned,
48 }
49
50 impl<K, D> QueryState<K, D>
51 where
52     K: Eq + Hash + Clone + Debug,
53     D: DepKind,
54 {
55     pub fn all_inactive(&self) -> bool {
56         #[cfg(parallel_compiler)]
57         {
58             let shards = self.active.lock_shards();
59             shards.iter().all(|shard| shard.is_empty())
60         }
61         #[cfg(not(parallel_compiler))]
62         {
63             self.active.lock().is_empty()
64         }
65     }
66
67     pub fn try_collect_active_jobs<Qcx: Copy>(
68         &self,
69         qcx: Qcx,
70         make_query: fn(Qcx, K) -> QueryStackFrame<D>,
71         jobs: &mut QueryMap<D>,
72     ) -> Option<()> {
73         #[cfg(parallel_compiler)]
74         {
75             // We use try_lock_shards here since we are called from the
76             // deadlock handler, and this shouldn't be locked.
77             let shards = self.active.try_lock_shards()?;
78             for shard in shards.iter() {
79                 for (k, v) in shard.iter() {
80                     if let QueryResult::Started(ref job) = *v {
81                         let query = make_query(qcx, k.clone());
82                         jobs.insert(job.id, QueryJobInfo { query, job: job.clone() });
83                     }
84                 }
85             }
86         }
87         #[cfg(not(parallel_compiler))]
88         {
89             // We use try_lock here since we are called from the
90             // deadlock handler, and this shouldn't be locked.
91             // (FIXME: Is this relevant for non-parallel compilers? It doesn't
92             // really hurt much.)
93             for (k, v) in self.active.try_lock()?.iter() {
94                 if let QueryResult::Started(ref job) = *v {
95                     let query = make_query(qcx, k.clone());
96                     jobs.insert(job.id, QueryJobInfo { query, job: job.clone() });
97                 }
98             }
99         }
100
101         Some(())
102     }
103 }
104
105 impl<K, D: DepKind> Default for QueryState<K, D> {
106     fn default() -> QueryState<K, D> {
107         QueryState { active: Default::default() }
108     }
109 }
110
111 /// A type representing the responsibility to execute the job in the `job` field.
112 /// This will poison the relevant query if dropped.
113 struct JobOwner<'tcx, K, D: DepKind>
114 where
115     K: Eq + Hash + Clone,
116 {
117     state: &'tcx QueryState<K, D>,
118     key: K,
119     id: QueryJobId,
120 }
121
122 #[cold]
123 #[inline(never)]
124 fn mk_cycle<Qcx, R, D: DepKind>(
125     qcx: Qcx,
126     cycle_error: CycleError<D>,
127     handler: HandleCycleError,
128 ) -> R
129 where
130     Qcx: QueryContext + crate::query::HasDepContext<DepKind = D>,
131     R: std::fmt::Debug + Value<Qcx::DepContext, Qcx::DepKind>,
132 {
133     let error = report_cycle(qcx.dep_context().sess(), &cycle_error);
134     handle_cycle_error(*qcx.dep_context(), &cycle_error, error, handler)
135 }
136
137 fn handle_cycle_error<Tcx, V>(
138     tcx: Tcx,
139     cycle_error: &CycleError<Tcx::DepKind>,
140     mut error: DiagnosticBuilder<'_, ErrorGuaranteed>,
141     handler: HandleCycleError,
142 ) -> V
143 where
144     Tcx: DepContext,
145     V: Value<Tcx, Tcx::DepKind>,
146 {
147     use HandleCycleError::*;
148     match handler {
149         Error => {
150             error.emit();
151             Value::from_cycle_error(tcx, &cycle_error.cycle)
152         }
153         Fatal => {
154             error.emit();
155             tcx.sess().abort_if_errors();
156             unreachable!()
157         }
158         DelayBug => {
159             error.delay_as_bug();
160             Value::from_cycle_error(tcx, &cycle_error.cycle)
161         }
162     }
163 }
164
165 impl<'tcx, K, D: DepKind> JobOwner<'tcx, K, D>
166 where
167     K: Eq + Hash + Clone,
168 {
169     /// Either gets a `JobOwner` corresponding the query, allowing us to
170     /// start executing the query, or returns with the result of the query.
171     /// This function assumes that `try_get_cached` is already called and returned `lookup`.
172     /// If the query is executing elsewhere, this will wait for it and return the result.
173     /// If the query panicked, this will silently panic.
174     ///
175     /// This function is inlined because that results in a noticeable speed-up
176     /// for some compile-time benchmarks.
177     #[inline(always)]
178     fn try_start<'b, Qcx>(
179         qcx: &'b Qcx,
180         state: &'b QueryState<K, Qcx::DepKind>,
181         span: Span,
182         key: K,
183     ) -> TryGetJob<'b, K, D>
184     where
185         Qcx: QueryContext + crate::query::HasDepContext<DepKind = D>,
186     {
187         #[cfg(parallel_compiler)]
188         let mut state_lock = state.active.get_shard_by_value(&key).lock();
189         #[cfg(not(parallel_compiler))]
190         let mut state_lock = state.active.lock();
191         let lock = &mut *state_lock;
192
193         match lock.entry(key) {
194             Entry::Vacant(entry) => {
195                 let id = qcx.next_job_id();
196                 let job = qcx.current_query_job();
197                 let job = QueryJob::new(id, span, job);
198
199                 let key = entry.key().clone();
200                 entry.insert(QueryResult::Started(job));
201
202                 let owner = JobOwner { state, id, key };
203                 return TryGetJob::NotYetStarted(owner);
204             }
205             Entry::Occupied(mut entry) => {
206                 match entry.get_mut() {
207                     #[cfg(not(parallel_compiler))]
208                     QueryResult::Started(job) => {
209                         let id = job.id;
210                         drop(state_lock);
211
212                         // If we are single-threaded we know that we have cycle error,
213                         // so we just return the error.
214                         return TryGetJob::Cycle(id.find_cycle_in_stack(
215                             qcx.try_collect_active_jobs().unwrap(),
216                             &qcx.current_query_job(),
217                             span,
218                         ));
219                     }
220                     #[cfg(parallel_compiler)]
221                     QueryResult::Started(job) => {
222                         // For parallel queries, we'll block and wait until the query running
223                         // in another thread has completed. Record how long we wait in the
224                         // self-profiler.
225                         let query_blocked_prof_timer = qcx.dep_context().profiler().query_blocked();
226
227                         // Get the latch out
228                         let latch = job.latch();
229
230                         drop(state_lock);
231
232                         // With parallel queries we might just have to wait on some other
233                         // thread.
234                         let result = latch.wait_on(qcx.current_query_job(), span);
235
236                         match result {
237                             Ok(()) => TryGetJob::JobCompleted(query_blocked_prof_timer),
238                             Err(cycle) => TryGetJob::Cycle(cycle),
239                         }
240                     }
241                     QueryResult::Poisoned => FatalError.raise(),
242                 }
243             }
244         }
245     }
246
247     /// Completes the query by updating the query cache with the `result`,
248     /// signals the waiter and forgets the JobOwner, so it won't poison the query
249     fn complete<C>(self, cache: &C, result: C::Value, dep_node_index: DepNodeIndex) -> C::Stored
250     where
251         C: QueryCache<Key = K>,
252     {
253         // We can move out of `self` here because we `mem::forget` it below
254         let key = unsafe { ptr::read(&self.key) };
255         let state = self.state;
256
257         // Forget ourself so our destructor won't poison the query
258         mem::forget(self);
259
260         let (job, result) = {
261             let job = {
262                 #[cfg(parallel_compiler)]
263                 let mut lock = state.active.get_shard_by_value(&key).lock();
264                 #[cfg(not(parallel_compiler))]
265                 let mut lock = state.active.lock();
266                 match lock.remove(&key).unwrap() {
267                     QueryResult::Started(job) => job,
268                     QueryResult::Poisoned => panic!(),
269                 }
270             };
271             let result = cache.complete(key, result, dep_node_index);
272             (job, result)
273         };
274
275         job.signal_complete();
276         result
277     }
278 }
279
280 impl<'tcx, K, D> Drop for JobOwner<'tcx, K, D>
281 where
282     K: Eq + Hash + Clone,
283     D: DepKind,
284 {
285     #[inline(never)]
286     #[cold]
287     fn drop(&mut self) {
288         // Poison the query so jobs waiting on it panic.
289         let state = self.state;
290         let job = {
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!(),
298             };
299             shard.insert(self.key.clone(), QueryResult::Poisoned);
300             job
301         };
302         // Also signal the completion of the job, so waiters
303         // will continue execution.
304         job.signal_complete();
305     }
306 }
307
308 #[derive(Clone)]
309 pub(crate) struct CycleError<D: DepKind> {
310     /// The query and related span that uses the cycle.
311     pub usage: Option<(Span, QueryStackFrame<D>)>,
312     pub cycle: Vec<QueryInfo<D>>,
313 }
314
315 /// The result of `try_start`.
316 enum TryGetJob<'tcx, K, D>
317 where
318     K: Eq + Hash + Clone,
319     D: DepKind,
320 {
321     /// The query is not yet started. Contains a guard to the cache eventually used to start it.
322     NotYetStarted(JobOwner<'tcx, K, D>),
323
324     /// The query was already completed.
325     /// Returns the result of the query and its dep-node index
326     /// if it succeeded or a cycle error if it failed.
327     #[cfg(parallel_compiler)]
328     JobCompleted(TimingGuard<'tcx>),
329
330     /// Trying to execute the query resulted in a cycle.
331     Cycle(CycleError<D>),
332 }
333
334 /// Checks if the query is already computed and in the cache.
335 /// It returns the shard index and a lock guard to the shard,
336 /// which will be used if the query is not in the cache and we need
337 /// to compute it.
338 #[inline]
339 pub fn try_get_cached<Tcx, C>(tcx: Tcx, cache: &C, key: &C::Key) -> Option<C::Stored>
340 where
341     C: QueryCache,
342     Tcx: DepContext,
343 {
344     match cache.lookup(&key) {
345         Some((value, index)) => {
346             tcx.profiler().query_cache_hit(index.into());
347             tcx.dep_graph().read_index(index);
348             Some(value)
349         }
350         None => None,
351     }
352 }
353
354 fn try_execute_query<Q, Qcx>(
355     qcx: Qcx,
356     state: &QueryState<Q::Key, Qcx::DepKind>,
357     cache: &Q::Cache,
358     span: Span,
359     key: Q::Key,
360     dep_node: Option<DepNode<Qcx::DepKind>>,
361 ) -> (Q::Stored, Option<DepNodeIndex>)
362 where
363     Q: QueryConfig<Qcx>,
364     Qcx: QueryContext,
365 {
366     match JobOwner::<'_, Q::Key, Qcx::DepKind>::try_start(&qcx, state, span, key.clone()) {
367         TryGetJob::NotYetStarted(job) => {
368             let (result, dep_node_index) =
369                 execute_job::<Q, Qcx>(qcx, key.clone(), dep_node, job.id);
370             if Q::FEEDABLE {
371                 // We may have put a value inside the cache from inside the execution.
372                 // Verify that it has the same hash as what we have now, to ensure consistency.
373                 if let Some((cached_result, _)) = cache.lookup(&key) {
374                     let hasher = Q::HASH_RESULT.expect("feedable forbids no_hash");
375
376                     let old_hash = qcx.dep_context().with_stable_hashing_context(|mut hcx| {
377                         hasher(&mut hcx, cached_result.borrow())
378                     });
379                     let new_hash = qcx
380                         .dep_context()
381                         .with_stable_hashing_context(|mut hcx| hasher(&mut hcx, &result));
382                     debug_assert_eq!(
383                         old_hash,
384                         new_hash,
385                         "Computed query value for {:?}({:?}) is inconsistent with fed value,\ncomputed={:#?}\nfed={:#?}",
386                         Q::DEP_KIND,
387                         key,
388                         result,
389                         cached_result,
390                     );
391                 }
392             }
393             let result = job.complete(cache, result, dep_node_index);
394             (result, Some(dep_node_index))
395         }
396         TryGetJob::Cycle(error) => {
397             let result = mk_cycle(qcx, error, Q::HANDLE_CYCLE_ERROR);
398             (result, None)
399         }
400         #[cfg(parallel_compiler)]
401         TryGetJob::JobCompleted(query_blocked_prof_timer) => {
402             let Some((v, index)) = cache.lookup(&key) else {
403                 panic!("value must be in cache after waiting")
404             };
405
406             qcx.dep_context().profiler().query_cache_hit(index.into());
407             query_blocked_prof_timer.finish_with_query_invocation_id(index.into());
408
409             (v, Some(index))
410         }
411     }
412 }
413
414 fn execute_job<Q, Qcx>(
415     qcx: Qcx,
416     key: Q::Key,
417     mut dep_node_opt: Option<DepNode<Qcx::DepKind>>,
418     job_id: QueryJobId,
419 ) -> (Q::Value, DepNodeIndex)
420 where
421     Q: QueryConfig<Qcx>,
422     Qcx: QueryContext,
423 {
424     let dep_graph = qcx.dep_context().dep_graph();
425
426     // Fast path for when incr. comp. is off.
427     if !dep_graph.is_fully_enabled() {
428         let prof_timer = qcx.dep_context().profiler().query_provider();
429         let result = qcx.start_query(job_id, Q::DEPTH_LIMIT, None, || {
430             Q::compute(qcx, &key)(*qcx.dep_context(), key)
431         });
432         let dep_node_index = dep_graph.next_virtual_depnode_index();
433         prof_timer.finish_with_query_invocation_id(dep_node_index.into());
434         return (result, dep_node_index);
435     }
436
437     if !Q::ANON && !Q::EVAL_ALWAYS {
438         // `to_dep_node` is expensive for some `DepKind`s.
439         let dep_node =
440             dep_node_opt.get_or_insert_with(|| Q::construct_dep_node(*qcx.dep_context(), &key));
441
442         // The diagnostics for this query will be promoted to the current session during
443         // `try_mark_green()`, so we can ignore them here.
444         if let Some(ret) = qcx.start_query(job_id, false, None, || {
445             try_load_from_disk_and_cache_in_memory::<Q, Qcx>(qcx, &key, &dep_node)
446         }) {
447             return ret;
448         }
449     }
450
451     let prof_timer = qcx.dep_context().profiler().query_provider();
452     let diagnostics = Lock::new(ThinVec::new());
453
454     let (result, dep_node_index) =
455         qcx.start_query(job_id, Q::DEPTH_LIMIT, Some(&diagnostics), || {
456             if Q::ANON {
457                 return dep_graph.with_anon_task(*qcx.dep_context(), Q::DEP_KIND, || {
458                     Q::compute(qcx, &key)(*qcx.dep_context(), key)
459                 });
460             }
461
462             // `to_dep_node` is expensive for some `DepKind`s.
463             let dep_node =
464                 dep_node_opt.unwrap_or_else(|| Q::construct_dep_node(*qcx.dep_context(), &key));
465
466             let task = Q::compute(qcx, &key);
467             dep_graph.with_task(dep_node, *qcx.dep_context(), key, task, Q::HASH_RESULT)
468         });
469
470     prof_timer.finish_with_query_invocation_id(dep_node_index.into());
471
472     let diagnostics = diagnostics.into_inner();
473     let side_effects = QuerySideEffects { diagnostics };
474
475     if std::intrinsics::unlikely(!side_effects.is_empty()) {
476         if Q::ANON {
477             qcx.store_side_effects_for_anon_node(dep_node_index, side_effects);
478         } else {
479             qcx.store_side_effects(dep_node_index, side_effects);
480         }
481     }
482
483     (result, dep_node_index)
484 }
485
486 fn try_load_from_disk_and_cache_in_memory<Q, Qcx>(
487     qcx: Qcx,
488     key: &Q::Key,
489     dep_node: &DepNode<Qcx::DepKind>,
490 ) -> Option<(Q::Value, DepNodeIndex)>
491 where
492     Q: QueryConfig<Qcx>,
493     Qcx: QueryContext,
494 {
495     // Note this function can be called concurrently from the same query
496     // We must ensure that this is handled correctly.
497
498     let dep_graph = qcx.dep_context().dep_graph();
499     let (prev_dep_node_index, dep_node_index) = dep_graph.try_mark_green(qcx, &dep_node)?;
500
501     debug_assert!(dep_graph.is_green(dep_node));
502
503     // First we try to load the result from the on-disk cache.
504     // Some things are never cached on disk.
505     if let Some(try_load_from_disk) = Q::try_load_from_disk(qcx, &key) {
506         let prof_timer = qcx.dep_context().profiler().incr_cache_loading();
507
508         // The call to `with_query_deserialization` enforces that no new `DepNodes`
509         // are created during deserialization. See the docs of that method for more
510         // details.
511         let result =
512             dep_graph.with_query_deserialization(|| try_load_from_disk(qcx, prev_dep_node_index));
513
514         prof_timer.finish_with_query_invocation_id(dep_node_index.into());
515
516         if let Some(result) = result {
517             if std::intrinsics::unlikely(
518                 qcx.dep_context().sess().opts.unstable_opts.query_dep_graph,
519             ) {
520                 dep_graph.mark_debug_loaded_from_disk(*dep_node)
521             }
522
523             let prev_fingerprint = qcx
524                 .dep_context()
525                 .dep_graph()
526                 .prev_fingerprint_of(dep_node)
527                 .unwrap_or(Fingerprint::ZERO);
528             // If `-Zincremental-verify-ich` is specified, re-hash results from
529             // the cache and make sure that they have the expected fingerprint.
530             //
531             // If not, we still seek to verify a subset of fingerprints loaded
532             // from disk. Re-hashing results is fairly expensive, so we can't
533             // currently afford to verify every hash. This subset should still
534             // give us some coverage of potential bugs though.
535             let try_verify = prev_fingerprint.as_value().1 % 32 == 0;
536             if std::intrinsics::unlikely(
537                 try_verify || qcx.dep_context().sess().opts.unstable_opts.incremental_verify_ich,
538             ) {
539                 incremental_verify_ich(*qcx.dep_context(), &result, dep_node, Q::HASH_RESULT);
540             }
541
542             return Some((result, dep_node_index));
543         }
544
545         // We always expect to find a cached result for things that
546         // can be forced from `DepNode`.
547         debug_assert!(
548             !qcx.dep_context().fingerprint_style(dep_node.kind).reconstructible(),
549             "missing on-disk cache entry for {dep_node:?}"
550         );
551     }
552
553     // We could not load a result from the on-disk cache, so
554     // recompute.
555     let prof_timer = qcx.dep_context().profiler().query_provider();
556
557     // The dep-graph for this computation is already in-place.
558     let result = dep_graph.with_ignore(|| Q::compute(qcx, key)(*qcx.dep_context(), key.clone()));
559
560     prof_timer.finish_with_query_invocation_id(dep_node_index.into());
561
562     // Verify that re-running the query produced a result with the expected hash
563     // This catches bugs in query implementations, turning them into ICEs.
564     // For example, a query might sort its result by `DefId` - since `DefId`s are
565     // not stable across compilation sessions, the result could get up getting sorted
566     // in a different order when the query is re-run, even though all of the inputs
567     // (e.g. `DefPathHash` values) were green.
568     //
569     // See issue #82920 for an example of a miscompilation that would get turned into
570     // an ICE by this check
571     incremental_verify_ich(*qcx.dep_context(), &result, dep_node, Q::HASH_RESULT);
572
573     Some((result, dep_node_index))
574 }
575
576 #[instrument(skip(tcx, result, hash_result), level = "debug")]
577 pub(crate) fn incremental_verify_ich<Tcx, V: Debug>(
578     tcx: Tcx,
579     result: &V,
580     dep_node: &DepNode<Tcx::DepKind>,
581     hash_result: Option<fn(&mut StableHashingContext<'_>, &V) -> Fingerprint>,
582 ) -> Fingerprint
583 where
584     Tcx: DepContext,
585 {
586     assert!(
587         tcx.dep_graph().is_green(dep_node),
588         "fingerprint for green query instance not loaded from cache: {dep_node:?}",
589     );
590
591     let new_hash = hash_result.map_or(Fingerprint::ZERO, |f| {
592         tcx.with_stable_hashing_context(|mut hcx| f(&mut hcx, result))
593     });
594
595     let old_hash = tcx.dep_graph().prev_fingerprint_of(dep_node);
596
597     if Some(new_hash) != old_hash {
598         incremental_verify_ich_failed(
599             tcx.sess(),
600             DebugArg::from(&dep_node),
601             DebugArg::from(&result),
602         );
603     }
604
605     new_hash
606 }
607
608 // This DebugArg business is largely a mirror of std::fmt::ArgumentV1, which is
609 // currently not exposed publicly.
610 //
611 // The PR which added this attempted to use `&dyn Debug` instead, but that
612 // showed statistically significant worse compiler performance. It's not
613 // actually clear what the cause there was -- the code should be cold. If this
614 // can be replaced with `&dyn Debug` with on perf impact, then it probably
615 // should be.
616 extern "C" {
617     type Opaque;
618 }
619
620 struct DebugArg<'a> {
621     value: &'a Opaque,
622     fmt: fn(&Opaque, &mut std::fmt::Formatter<'_>) -> std::fmt::Result,
623 }
624
625 impl<'a, T> From<&'a T> for DebugArg<'a>
626 where
627     T: std::fmt::Debug,
628 {
629     fn from(value: &'a T) -> DebugArg<'a> {
630         DebugArg {
631             value: unsafe { std::mem::transmute(value) },
632             fmt: unsafe {
633                 std::mem::transmute(<T as std::fmt::Debug>::fmt as fn(_, _) -> std::fmt::Result)
634             },
635         }
636     }
637 }
638
639 impl std::fmt::Debug for DebugArg<'_> {
640     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
641         (self.fmt)(self.value, f)
642     }
643 }
644
645 // Note that this is marked #[cold] and intentionally takes the equivalent of
646 // `dyn Debug` for its arguments, as we want to avoid generating a bunch of
647 // different implementations for LLVM to chew on (and filling up the final
648 // binary, too).
649 #[cold]
650 fn incremental_verify_ich_failed(sess: &Session, dep_node: DebugArg<'_>, result: DebugArg<'_>) {
651     // When we emit an error message and panic, we try to debug-print the `DepNode`
652     // and query result. Unfortunately, this can cause us to run additional queries,
653     // which may result in another fingerprint mismatch while we're in the middle
654     // of processing this one. To avoid a double-panic (which kills the process
655     // before we can print out the query static), we print out a terse
656     // but 'safe' message if we detect a re-entrant call to this method.
657     thread_local! {
658         static INSIDE_VERIFY_PANIC: Cell<bool> = const { Cell::new(false) };
659     };
660
661     let old_in_panic = INSIDE_VERIFY_PANIC.with(|in_panic| in_panic.replace(true));
662
663     if old_in_panic {
664         sess.emit_err(crate::error::Reentrant);
665     } else {
666         let run_cmd = if let Some(crate_name) = &sess.opts.crate_name {
667             format!("`cargo clean -p {crate_name}` or `cargo clean`")
668         } else {
669             "`cargo clean`".to_string()
670         };
671
672         sess.emit_err(crate::error::IncrementCompilation {
673             run_cmd,
674             dep_node: format!("{dep_node:?}"),
675         });
676         panic!("Found unstable fingerprints for {dep_node:?}: {result:?}");
677     }
678
679     INSIDE_VERIFY_PANIC.with(|in_panic| in_panic.set(old_in_panic));
680 }
681
682 /// Ensure that either this query has all green inputs or been executed.
683 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
684 /// Returns true if the query should still run.
685 ///
686 /// This function is particularly useful when executing passes for their
687 /// side-effects -- e.g., in order to report errors for erroneous programs.
688 ///
689 /// Note: The optimization is only available during incr. comp.
690 #[inline(never)]
691 fn ensure_must_run<Q, Qcx>(qcx: Qcx, key: &Q::Key) -> (bool, Option<DepNode<Qcx::DepKind>>)
692 where
693     Q: QueryConfig<Qcx>,
694     Qcx: QueryContext,
695 {
696     if Q::EVAL_ALWAYS {
697         return (true, None);
698     }
699
700     // Ensuring an anonymous query makes no sense
701     assert!(!Q::ANON);
702
703     let dep_node = Q::construct_dep_node(*qcx.dep_context(), key);
704
705     let dep_graph = qcx.dep_context().dep_graph();
706     match dep_graph.try_mark_green(qcx, &dep_node) {
707         None => {
708             // A None return from `try_mark_green` means that this is either
709             // a new dep node or that the dep node has already been marked red.
710             // Either way, we can't call `dep_graph.read()` as we don't have the
711             // DepNodeIndex. We must invoke the query itself. The performance cost
712             // this introduces should be negligible as we'll immediately hit the
713             // in-memory cache, or another query down the line will.
714             (true, Some(dep_node))
715         }
716         Some((_, dep_node_index)) => {
717             dep_graph.read_index(dep_node_index);
718             qcx.dep_context().profiler().query_cache_hit(dep_node_index.into());
719             (false, None)
720         }
721     }
722 }
723
724 #[derive(Debug)]
725 pub enum QueryMode {
726     Get,
727     Ensure,
728 }
729
730 pub fn get_query<Q, Qcx, D>(qcx: Qcx, span: Span, key: Q::Key, mode: QueryMode) -> Option<Q::Stored>
731 where
732     D: DepKind,
733     Q: QueryConfig<Qcx>,
734     Q::Value: Value<Qcx::DepContext, D>,
735     Qcx: QueryContext,
736 {
737     let dep_node = if let QueryMode::Ensure = mode {
738         let (must_run, dep_node) = ensure_must_run::<Q, _>(qcx, &key);
739         if !must_run {
740             return None;
741         }
742         dep_node
743     } else {
744         None
745     };
746
747     let (result, dep_node_index) = try_execute_query::<Q, Qcx>(
748         qcx,
749         Q::query_state(qcx),
750         Q::query_cache(qcx),
751         span,
752         key,
753         dep_node,
754     );
755     if let Some(dep_node_index) = dep_node_index {
756         qcx.dep_context().dep_graph().read_index(dep_node_index)
757     }
758     Some(result)
759 }
760
761 pub fn force_query<Q, Qcx, D>(qcx: Qcx, key: Q::Key, dep_node: DepNode<Qcx::DepKind>)
762 where
763     D: DepKind,
764     Q: QueryConfig<Qcx>,
765     Q::Value: Value<Qcx::DepContext, D>,
766     Qcx: QueryContext,
767 {
768     // We may be concurrently trying both execute and force a query.
769     // Ensure that only one of them runs the query.
770     let cache = Q::query_cache(qcx);
771     if let Some((_, index)) = cache.lookup(&key) {
772         qcx.dep_context().profiler().query_cache_hit(index.into());
773         return;
774     }
775
776     let state = Q::query_state(qcx);
777     debug_assert!(!Q::ANON);
778
779     try_execute_query::<Q, _>(qcx, state, cache, DUMMY_SP, key, Some(dep_node));
780 }