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