]> git.lizzy.rs Git - rust.git/blob - src/librustc_query_system/query/plumbing.rs
pin docs: add some forward references
[rust.git] / src / librustc_query_system / 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::{DepKind, DepNode};
6 use crate::dep_graph::{DepNodeIndex, SerializedDepNodeIndex};
7 use crate::query::caches::QueryCache;
8 use crate::query::config::{QueryDescription, QueryVtable, QueryVtableExt};
9 use crate::query::job::{QueryInfo, QueryJob, QueryJobId, QueryJobInfo, QueryShardJobId};
10 use crate::query::QueryContext;
11
12 #[cfg(not(parallel_compiler))]
13 use rustc_data_structures::cold_path;
14 use rustc_data_structures::fingerprint::Fingerprint;
15 use rustc_data_structures::fx::{FxHashMap, FxHasher};
16 use rustc_data_structures::sharded::Sharded;
17 use rustc_data_structures::sync::{Lock, LockGuard};
18 use rustc_data_structures::thin_vec::ThinVec;
19 use rustc_errors::{Diagnostic, FatalError};
20 use rustc_span::source_map::DUMMY_SP;
21 use rustc_span::Span;
22 use std::collections::hash_map::Entry;
23 use std::convert::TryFrom;
24 use std::fmt::Debug;
25 use std::hash::{Hash, Hasher};
26 use std::mem;
27 use std::num::NonZeroU32;
28 use std::ptr;
29 #[cfg(debug_assertions)]
30 use std::sync::atomic::{AtomicUsize, Ordering};
31
32 pub(super) struct QueryStateShard<CTX: QueryContext, K, C> {
33     pub(super) cache: C,
34     active: FxHashMap<K, QueryResult<CTX>>,
35
36     /// Used to generate unique ids for active jobs.
37     jobs: u32,
38 }
39
40 impl<CTX: QueryContext, K, C: Default> Default for QueryStateShard<CTX, K, C> {
41     fn default() -> QueryStateShard<CTX, K, C> {
42         QueryStateShard { cache: Default::default(), active: Default::default(), jobs: 0 }
43     }
44 }
45
46 pub struct QueryState<CTX: QueryContext, C: QueryCache> {
47     cache: C,
48     shards: Sharded<QueryStateShard<CTX, C::Key, C::Sharded>>,
49     #[cfg(debug_assertions)]
50     pub cache_hits: AtomicUsize,
51 }
52
53 impl<CTX: QueryContext, C: QueryCache> QueryState<CTX, C> {
54     #[inline]
55     pub(super) fn get_lookup<'tcx>(
56         &'tcx self,
57         key: &C::Key,
58     ) -> QueryLookup<'tcx, CTX, C::Key, C::Sharded> {
59         // We compute the key's hash once and then use it for both the
60         // shard lookup and the hashmap lookup. This relies on the fact
61         // that both of them use `FxHasher`.
62         let mut hasher = FxHasher::default();
63         key.hash(&mut hasher);
64         let key_hash = hasher.finish();
65
66         let shard = self.shards.get_shard_index_by_hash(key_hash);
67         let lock = self.shards.get_shard_by_index(shard).lock();
68         QueryLookup { key_hash, shard, lock }
69     }
70 }
71
72 /// Indicates the state of a query for a given key in a query map.
73 enum QueryResult<CTX: QueryContext> {
74     /// An already executing query. The query job can be used to await for its completion.
75     Started(QueryJob<CTX>),
76
77     /// The query panicked. Queries trying to wait on this will raise a fatal error which will
78     /// silently panic.
79     Poisoned,
80 }
81
82 impl<CTX: QueryContext, C: QueryCache> QueryState<CTX, C> {
83     #[inline(always)]
84     pub fn iter_results<R>(
85         &self,
86         f: impl for<'a> FnOnce(
87             Box<dyn Iterator<Item = (&'a C::Key, &'a C::Value, DepNodeIndex)> + 'a>,
88         ) -> R,
89     ) -> R {
90         self.cache.iter(&self.shards, |shard| &mut shard.cache, f)
91     }
92
93     #[inline(always)]
94     pub fn all_inactive(&self) -> bool {
95         let shards = self.shards.lock_shards();
96         shards.iter().all(|shard| shard.active.is_empty())
97     }
98
99     pub fn try_collect_active_jobs(
100         &self,
101         kind: CTX::DepKind,
102         make_query: fn(C::Key) -> CTX::Query,
103         jobs: &mut FxHashMap<QueryJobId<CTX::DepKind>, QueryJobInfo<CTX>>,
104     ) -> Option<()>
105     where
106         C::Key: Clone,
107     {
108         // We use try_lock_shards here since we are called from the
109         // deadlock handler, and this shouldn't be locked.
110         let shards = self.shards.try_lock_shards()?;
111         let shards = shards.iter().enumerate();
112         jobs.extend(shards.flat_map(|(shard_id, shard)| {
113             shard.active.iter().filter_map(move |(k, v)| {
114                 if let QueryResult::Started(ref job) = *v {
115                     let id =
116                         QueryJobId { job: job.id, shard: u16::try_from(shard_id).unwrap(), kind };
117                     let info = QueryInfo { span: job.span, query: make_query(k.clone()) };
118                     Some((id, QueryJobInfo { info, job: job.clone() }))
119                 } else {
120                     None
121                 }
122             })
123         }));
124
125         Some(())
126     }
127 }
128
129 impl<CTX: QueryContext, C: QueryCache> Default for QueryState<CTX, C> {
130     fn default() -> QueryState<CTX, C> {
131         QueryState {
132             cache: C::default(),
133             shards: Default::default(),
134             #[cfg(debug_assertions)]
135             cache_hits: AtomicUsize::new(0),
136         }
137     }
138 }
139
140 /// Values used when checking a query cache which can be reused on a cache-miss to execute the query.
141 pub struct QueryLookup<'tcx, CTX: QueryContext, K, C> {
142     pub(super) key_hash: u64,
143     shard: usize,
144     pub(super) lock: LockGuard<'tcx, QueryStateShard<CTX, K, C>>,
145 }
146
147 /// A type representing the responsibility to execute the job in the `job` field.
148 /// This will poison the relevant query if dropped.
149 struct JobOwner<'tcx, CTX: QueryContext, C>
150 where
151     C: QueryCache,
152     C::Key: Eq + Hash + Clone + Debug,
153 {
154     state: &'tcx QueryState<CTX, C>,
155     key: C::Key,
156     id: QueryJobId<CTX::DepKind>,
157 }
158
159 impl<'tcx, CTX: QueryContext, C> JobOwner<'tcx, CTX, C>
160 where
161     C: QueryCache,
162     C::Key: Eq + Hash + Clone + Debug,
163 {
164     /// Either gets a `JobOwner` corresponding the query, allowing us to
165     /// start executing the query, or returns with the result of the query.
166     /// This function assumes that `try_get_cached` is already called and returned `lookup`.
167     /// If the query is executing elsewhere, this will wait for it and return the result.
168     /// If the query panicked, this will silently panic.
169     ///
170     /// This function is inlined because that results in a noticeable speed-up
171     /// for some compile-time benchmarks.
172     #[inline(always)]
173     fn try_start<'a, 'b>(
174         tcx: CTX,
175         state: &'b QueryState<CTX, C>,
176         span: Span,
177         key: &C::Key,
178         mut lookup: QueryLookup<'a, CTX, C::Key, C::Sharded>,
179         query: &QueryVtable<CTX, C::Key, C::Value>,
180     ) -> TryGetJob<'b, CTX, C>
181     where
182         CTX: QueryContext,
183     {
184         let lock = &mut *lookup.lock;
185
186         let (latch, mut _query_blocked_prof_timer) = match lock.active.entry((*key).clone()) {
187             Entry::Occupied(mut entry) => {
188                 match entry.get_mut() {
189                     QueryResult::Started(job) => {
190                         // For parallel queries, we'll block and wait until the query running
191                         // in another thread has completed. Record how long we wait in the
192                         // self-profiler.
193                         let _query_blocked_prof_timer = if cfg!(parallel_compiler) {
194                             Some(tcx.profiler().query_blocked())
195                         } else {
196                             None
197                         };
198
199                         // Create the id of the job we're waiting for
200                         let id = QueryJobId::new(job.id, lookup.shard, query.dep_kind);
201
202                         (job.latch(id), _query_blocked_prof_timer)
203                     }
204                     QueryResult::Poisoned => FatalError.raise(),
205                 }
206             }
207             Entry::Vacant(entry) => {
208                 // No job entry for this query. Return a new one to be started later.
209
210                 // Generate an id unique within this shard.
211                 let id = lock.jobs.checked_add(1).unwrap();
212                 lock.jobs = id;
213                 let id = QueryShardJobId(NonZeroU32::new(id).unwrap());
214
215                 let global_id = QueryJobId::new(id, lookup.shard, query.dep_kind);
216
217                 let job = tcx.current_query_job();
218                 let job = QueryJob::new(id, span, job);
219
220                 entry.insert(QueryResult::Started(job));
221
222                 let owner = JobOwner { state, id: global_id, key: (*key).clone() };
223                 return TryGetJob::NotYetStarted(owner);
224             }
225         };
226         mem::drop(lookup.lock);
227
228         // If we are single-threaded we know that we have cycle error,
229         // so we just return the error.
230         #[cfg(not(parallel_compiler))]
231         return TryGetJob::Cycle(cold_path(|| {
232             let value = query.handle_cycle_error(tcx, latch.find_cycle_in_stack(tcx, span));
233             state.cache.store_nocache(value)
234         }));
235
236         // With parallel queries we might just have to wait on some other
237         // thread.
238         #[cfg(parallel_compiler)]
239         {
240             let result = latch.wait_on(tcx, span);
241
242             if let Err(cycle) = result {
243                 let value = query.handle_cycle_error(tcx, cycle);
244                 let value = state.cache.store_nocache(value);
245                 return TryGetJob::Cycle(value);
246             }
247
248             let cached = try_get_cached(
249                 tcx,
250                 state,
251                 (*key).clone(),
252                 |value, index| (value.clone(), index),
253                 |_, _| panic!("value must be in cache after waiting"),
254             );
255
256             if let Some(prof_timer) = _query_blocked_prof_timer.take() {
257                 prof_timer.finish_with_query_invocation_id(cached.1.into());
258             }
259
260             return TryGetJob::JobCompleted(cached);
261         }
262     }
263
264     /// Completes the query by updating the query cache with the `result`,
265     /// signals the waiter and forgets the JobOwner, so it won't poison the query
266     #[inline(always)]
267     fn complete(self, tcx: CTX, result: C::Value, dep_node_index: DepNodeIndex) -> C::Stored {
268         // We can move out of `self` here because we `mem::forget` it below
269         let key = unsafe { ptr::read(&self.key) };
270         let state = self.state;
271
272         // Forget ourself so our destructor won't poison the query
273         mem::forget(self);
274
275         let (job, result) = {
276             let mut lock = state.shards.get_shard_by_value(&key).lock();
277             let job = match lock.active.remove(&key).unwrap() {
278                 QueryResult::Started(job) => job,
279                 QueryResult::Poisoned => panic!(),
280             };
281             let result = state.cache.complete(tcx, &mut lock.cache, key, result, dep_node_index);
282             (job, result)
283         };
284
285         job.signal_complete();
286         result
287     }
288 }
289
290 #[inline(always)]
291 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
292 where
293     F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R,
294 {
295     let diagnostics = Lock::new(ThinVec::new());
296     let result = f(Some(&diagnostics));
297     (result, diagnostics.into_inner())
298 }
299
300 impl<'tcx, CTX: QueryContext, C: QueryCache> Drop for JobOwner<'tcx, CTX, C>
301 where
302     C::Key: Eq + Hash + Clone + Debug,
303 {
304     #[inline(never)]
305     #[cold]
306     fn drop(&mut self) {
307         // Poison the query so jobs waiting on it panic.
308         let state = self.state;
309         let shard = state.shards.get_shard_by_value(&self.key);
310         let job = {
311             let mut shard = shard.lock();
312             let job = match shard.active.remove(&self.key).unwrap() {
313                 QueryResult::Started(job) => job,
314                 QueryResult::Poisoned => panic!(),
315             };
316             shard.active.insert(self.key.clone(), QueryResult::Poisoned);
317             job
318         };
319         // Also signal the completion of the job, so waiters
320         // will continue execution.
321         job.signal_complete();
322     }
323 }
324
325 #[derive(Clone)]
326 pub struct CycleError<Q> {
327     /// The query and related span that uses the cycle.
328     pub usage: Option<(Span, Q)>,
329     pub cycle: Vec<QueryInfo<Q>>,
330 }
331
332 /// The result of `try_start`.
333 enum TryGetJob<'tcx, CTX: QueryContext, C: QueryCache>
334 where
335     C::Key: Eq + Hash + Clone + Debug,
336 {
337     /// The query is not yet started. Contains a guard to the cache eventually used to start it.
338     NotYetStarted(JobOwner<'tcx, CTX, C>),
339
340     /// The query was already completed.
341     /// Returns the result of the query and its dep-node index
342     /// if it succeeded or a cycle error if it failed.
343     #[cfg(parallel_compiler)]
344     JobCompleted((C::Stored, DepNodeIndex)),
345
346     /// Trying to execute the query resulted in a cycle.
347     Cycle(C::Stored),
348 }
349
350 /// Checks if the query is already computed and in the cache.
351 /// It returns the shard index and a lock guard to the shard,
352 /// which will be used if the query is not in the cache and we need
353 /// to compute it.
354 #[inline(always)]
355 fn try_get_cached<CTX, C, R, OnHit, OnMiss>(
356     tcx: CTX,
357     state: &QueryState<CTX, C>,
358     key: C::Key,
359     // `on_hit` can be called while holding a lock to the query cache
360     on_hit: OnHit,
361     on_miss: OnMiss,
362 ) -> R
363 where
364     C: QueryCache,
365     CTX: QueryContext,
366     OnHit: FnOnce(&C::Stored, DepNodeIndex) -> R,
367     OnMiss: FnOnce(C::Key, QueryLookup<'_, CTX, C::Key, C::Sharded>) -> R,
368 {
369     state.cache.lookup(
370         state,
371         key,
372         |value, index| {
373             if unlikely!(tcx.profiler().enabled()) {
374                 tcx.profiler().query_cache_hit(index.into());
375             }
376             #[cfg(debug_assertions)]
377             {
378                 state.cache_hits.fetch_add(1, Ordering::Relaxed);
379             }
380             on_hit(value, index)
381         },
382         on_miss,
383     )
384 }
385
386 #[inline(always)]
387 fn try_execute_query<CTX, C>(
388     tcx: CTX,
389     state: &QueryState<CTX, C>,
390     span: Span,
391     key: C::Key,
392     lookup: QueryLookup<'_, CTX, C::Key, C::Sharded>,
393     query: &QueryVtable<CTX, C::Key, C::Value>,
394 ) -> C::Stored
395 where
396     C: QueryCache,
397     C::Key: Eq + Clone + Debug + crate::dep_graph::DepNodeParams<CTX>,
398     C::Stored: Clone,
399     CTX: QueryContext,
400 {
401     let job = match JobOwner::try_start(tcx, state, span, &key, lookup, query) {
402         TryGetJob::NotYetStarted(job) => job,
403         TryGetJob::Cycle(result) => return result,
404         #[cfg(parallel_compiler)]
405         TryGetJob::JobCompleted((v, index)) => {
406             tcx.dep_graph().read_index(index);
407             return v;
408         }
409     };
410
411     // Fast path for when incr. comp. is off. `to_dep_node` is
412     // expensive for some `DepKind`s.
413     if !tcx.dep_graph().is_fully_enabled() {
414         let null_dep_node = DepNode::new_no_params(DepKind::NULL);
415         return force_query_with_job(tcx, key, job, null_dep_node, query).0;
416     }
417
418     if query.anon {
419         let prof_timer = tcx.profiler().query_provider();
420
421         let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
422             tcx.start_query(job.id, diagnostics, |tcx| {
423                 tcx.dep_graph().with_anon_task(query.dep_kind, || query.compute(tcx, key))
424             })
425         });
426
427         prof_timer.finish_with_query_invocation_id(dep_node_index.into());
428
429         tcx.dep_graph().read_index(dep_node_index);
430
431         if unlikely!(!diagnostics.is_empty()) {
432             tcx.store_diagnostics_for_anon_node(dep_node_index, diagnostics);
433         }
434
435         return job.complete(tcx, result, dep_node_index);
436     }
437
438     let dep_node = query.to_dep_node(tcx, &key);
439
440     if !query.eval_always {
441         // The diagnostics for this query will be
442         // promoted to the current session during
443         // `try_mark_green()`, so we can ignore them here.
444         let loaded = tcx.start_query(job.id, None, |tcx| {
445             let marked = tcx.dep_graph().try_mark_green_and_read(tcx, &dep_node);
446             marked.map(|(prev_dep_node_index, dep_node_index)| {
447                 (
448                     load_from_disk_and_cache_in_memory(
449                         tcx,
450                         key.clone(),
451                         prev_dep_node_index,
452                         dep_node_index,
453                         &dep_node,
454                         query,
455                     ),
456                     dep_node_index,
457                 )
458             })
459         });
460         if let Some((result, dep_node_index)) = loaded {
461             return job.complete(tcx, result, dep_node_index);
462         }
463     }
464
465     let (result, dep_node_index) = force_query_with_job(tcx, key, job, dep_node, query);
466     tcx.dep_graph().read_index(dep_node_index);
467     result
468 }
469
470 fn load_from_disk_and_cache_in_memory<CTX, K, V>(
471     tcx: CTX,
472     key: K,
473     prev_dep_node_index: SerializedDepNodeIndex,
474     dep_node_index: DepNodeIndex,
475     dep_node: &DepNode<CTX::DepKind>,
476     query: &QueryVtable<CTX, K, V>,
477 ) -> V
478 where
479     CTX: QueryContext,
480 {
481     // Note this function can be called concurrently from the same query
482     // We must ensure that this is handled correctly.
483
484     debug_assert!(tcx.dep_graph().is_green(dep_node));
485
486     // First we try to load the result from the on-disk cache.
487     let result = if query.cache_on_disk(tcx, &key, None) {
488         let prof_timer = tcx.profiler().incr_cache_loading();
489         let result = query.try_load_from_disk(tcx, prev_dep_node_index);
490         prof_timer.finish_with_query_invocation_id(dep_node_index.into());
491
492         // We always expect to find a cached result for things that
493         // can be forced from `DepNode`.
494         debug_assert!(
495             !dep_node.kind.can_reconstruct_query_key() || result.is_some(),
496             "missing on-disk cache entry for {:?}",
497             dep_node
498         );
499         result
500     } else {
501         // Some things are never cached on disk.
502         None
503     };
504
505     let result = if let Some(result) = result {
506         result
507     } else {
508         // We could not load a result from the on-disk cache, so
509         // recompute.
510         let prof_timer = tcx.profiler().query_provider();
511
512         // The dep-graph for this computation is already in-place.
513         let result = tcx.dep_graph().with_ignore(|| query.compute(tcx, key));
514
515         prof_timer.finish_with_query_invocation_id(dep_node_index.into());
516
517         result
518     };
519
520     // If `-Zincremental-verify-ich` is specified, re-hash results from
521     // the cache and make sure that they have the expected fingerprint.
522     if unlikely!(tcx.incremental_verify_ich()) {
523         incremental_verify_ich(tcx, &result, dep_node, dep_node_index, query);
524     }
525
526     result
527 }
528
529 #[inline(never)]
530 #[cold]
531 fn incremental_verify_ich<CTX, K, V>(
532     tcx: CTX,
533     result: &V,
534     dep_node: &DepNode<CTX::DepKind>,
535     dep_node_index: DepNodeIndex,
536     query: &QueryVtable<CTX, K, V>,
537 ) where
538     CTX: QueryContext,
539 {
540     assert!(
541         Some(tcx.dep_graph().fingerprint_of(dep_node_index))
542             == tcx.dep_graph().prev_fingerprint_of(dep_node),
543         "fingerprint for green query instance not loaded from cache: {:?}",
544         dep_node,
545     );
546
547     debug!("BEGIN verify_ich({:?})", dep_node);
548     let mut hcx = tcx.create_stable_hashing_context();
549
550     let new_hash = query.hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
551     debug!("END verify_ich({:?})", dep_node);
552
553     let old_hash = tcx.dep_graph().fingerprint_of(dep_node_index);
554
555     assert!(new_hash == old_hash, "found unstable fingerprints for {:?}", dep_node,);
556 }
557
558 #[inline(always)]
559 fn force_query_with_job<C, CTX>(
560     tcx: CTX,
561     key: C::Key,
562     job: JobOwner<'_, CTX, C>,
563     dep_node: DepNode<CTX::DepKind>,
564     query: &QueryVtable<CTX, C::Key, C::Value>,
565 ) -> (C::Stored, DepNodeIndex)
566 where
567     C: QueryCache,
568     C::Key: Eq + Clone + Debug,
569     C::Stored: Clone,
570     CTX: QueryContext,
571 {
572     // If the following assertion triggers, it can have two reasons:
573     // 1. Something is wrong with DepNode creation, either here or
574     //    in `DepGraph::try_mark_green()`.
575     // 2. Two distinct query keys get mapped to the same `DepNode`
576     //    (see for example #48923).
577     assert!(
578         !tcx.dep_graph().dep_node_exists(&dep_node),
579         "forcing query with already existing `DepNode`\n\
580                  - query-key: {:?}\n\
581                  - dep-node: {:?}",
582         key,
583         dep_node
584     );
585
586     let prof_timer = tcx.profiler().query_provider();
587
588     let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
589         tcx.start_query(job.id, diagnostics, |tcx| {
590             if query.eval_always {
591                 tcx.dep_graph().with_eval_always_task(
592                     dep_node,
593                     tcx,
594                     key,
595                     query.compute,
596                     query.hash_result,
597                 )
598             } else {
599                 tcx.dep_graph().with_task(dep_node, tcx, key, query.compute, query.hash_result)
600             }
601         })
602     });
603
604     prof_timer.finish_with_query_invocation_id(dep_node_index.into());
605
606     if unlikely!(!diagnostics.is_empty()) {
607         if dep_node.kind != DepKind::NULL {
608             tcx.store_diagnostics(dep_node_index, diagnostics);
609         }
610     }
611
612     let result = job.complete(tcx, result, dep_node_index);
613
614     (result, dep_node_index)
615 }
616
617 #[inline(never)]
618 fn get_query_impl<CTX, C>(
619     tcx: CTX,
620     state: &QueryState<CTX, C>,
621     span: Span,
622     key: C::Key,
623     query: &QueryVtable<CTX, C::Key, C::Value>,
624 ) -> C::Stored
625 where
626     CTX: QueryContext,
627     C: QueryCache,
628     C::Key: Eq + Clone + crate::dep_graph::DepNodeParams<CTX>,
629     C::Stored: Clone,
630 {
631     try_get_cached(
632         tcx,
633         state,
634         key,
635         |value, index| {
636             tcx.dep_graph().read_index(index);
637             value.clone()
638         },
639         |key, lookup| try_execute_query(tcx, state, span, key, lookup, query),
640     )
641 }
642
643 /// Ensure that either this query has all green inputs or been executed.
644 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
645 ///
646 /// This function is particularly useful when executing passes for their
647 /// side-effects -- e.g., in order to report errors for erroneous programs.
648 ///
649 /// Note: The optimization is only available during incr. comp.
650 #[inline(never)]
651 fn ensure_query_impl<CTX, C>(
652     tcx: CTX,
653     state: &QueryState<CTX, C>,
654     key: C::Key,
655     query: &QueryVtable<CTX, C::Key, C::Value>,
656 ) where
657     C: QueryCache,
658     C::Key: Eq + Clone + crate::dep_graph::DepNodeParams<CTX>,
659     CTX: QueryContext,
660 {
661     if query.eval_always {
662         let _ = get_query_impl(tcx, state, DUMMY_SP, key, query);
663         return;
664     }
665
666     // Ensuring an anonymous query makes no sense
667     assert!(!query.anon);
668
669     let dep_node = query.to_dep_node(tcx, &key);
670
671     match tcx.dep_graph().try_mark_green_and_read(tcx, &dep_node) {
672         None => {
673             // A None return from `try_mark_green_and_read` means that this is either
674             // a new dep node or that the dep node has already been marked red.
675             // Either way, we can't call `dep_graph.read()` as we don't have the
676             // DepNodeIndex. We must invoke the query itself. The performance cost
677             // this introduces should be negligible as we'll immediately hit the
678             // in-memory cache, or another query down the line will.
679             let _ = get_query_impl(tcx, state, DUMMY_SP, key, query);
680         }
681         Some((_, dep_node_index)) => {
682             tcx.profiler().query_cache_hit(dep_node_index.into());
683         }
684     }
685 }
686
687 #[inline(never)]
688 fn force_query_impl<CTX, C>(
689     tcx: CTX,
690     state: &QueryState<CTX, C>,
691     key: C::Key,
692     span: Span,
693     dep_node: DepNode<CTX::DepKind>,
694     query: &QueryVtable<CTX, C::Key, C::Value>,
695 ) where
696     C: QueryCache,
697     C::Key: Eq + Clone + crate::dep_graph::DepNodeParams<CTX>,
698     CTX: QueryContext,
699 {
700     // We may be concurrently trying both execute and force a query.
701     // Ensure that only one of them runs the query.
702
703     try_get_cached(
704         tcx,
705         state,
706         key,
707         |_, _| {
708             // Cache hit, do nothing
709         },
710         |key, lookup| {
711             let job = match JobOwner::try_start(tcx, state, span, &key, lookup, query) {
712                 TryGetJob::NotYetStarted(job) => job,
713                 TryGetJob::Cycle(_) => return,
714                 #[cfg(parallel_compiler)]
715                 TryGetJob::JobCompleted(_) => return,
716             };
717             force_query_with_job(tcx, key, job, dep_node, query);
718         },
719     );
720 }
721
722 #[inline(always)]
723 pub fn get_query<Q, CTX>(tcx: CTX, span: Span, key: Q::Key) -> Q::Stored
724 where
725     Q: QueryDescription<CTX>,
726     Q::Key: crate::dep_graph::DepNodeParams<CTX>,
727     CTX: QueryContext,
728 {
729     debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME, key, span);
730
731     get_query_impl(tcx, Q::query_state(tcx), span, key, &Q::VTABLE)
732 }
733
734 #[inline(always)]
735 pub fn ensure_query<Q, CTX>(tcx: CTX, key: Q::Key)
736 where
737     Q: QueryDescription<CTX>,
738     Q::Key: crate::dep_graph::DepNodeParams<CTX>,
739     CTX: QueryContext,
740 {
741     ensure_query_impl(tcx, Q::query_state(tcx), key, &Q::VTABLE)
742 }
743
744 #[inline(always)]
745 pub fn force_query<Q, CTX>(tcx: CTX, key: Q::Key, span: Span, dep_node: DepNode<CTX::DepKind>)
746 where
747     Q: QueryDescription<CTX>,
748     Q::Key: crate::dep_graph::DepNodeParams<CTX>,
749     CTX: QueryContext,
750 {
751     force_query_impl(tcx, Q::query_state(tcx), key, span, dep_node, &Q::VTABLE)
752 }