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