]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/query/plumbing.rs
Rollup merge of #68767 - kubo39:patch-macos, r=shepmaster
[rust.git] / src / librustc / ty / 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, DepNodeIndex, SerializedDepNodeIndex};
6 use crate::ty::query::config::{QueryConfig, QueryDescription};
7 use crate::ty::query::job::{QueryInfo, QueryJob, QueryJobId, QueryShardJobId};
8 use crate::ty::query::Query;
9 use crate::ty::tls;
10 use crate::ty::{self, TyCtxt};
11
12 #[cfg(not(parallel_compiler))]
13 use rustc_data_structures::cold_path;
14 use rustc_data_structures::fx::{FxHashMap, FxHasher};
15 #[cfg(parallel_compiler)]
16 use rustc_data_structures::profiling::TimingGuard;
17 use rustc_data_structures::sharded::Sharded;
18 use rustc_data_structures::sync::Lock;
19 use rustc_data_structures::thin_vec::ThinVec;
20 use rustc_errors::{struct_span_err, Diagnostic, DiagnosticBuilder, FatalError, Handler, Level};
21 use rustc_span::source_map::DUMMY_SP;
22 use rustc_span::Span;
23 use std::collections::hash_map::Entry;
24 use std::hash::{Hash, Hasher};
25 use std::mem;
26 use std::num::NonZeroU32;
27 use std::ptr;
28
29 pub struct QueryCache<'tcx, D: QueryConfig<'tcx> + ?Sized> {
30     pub(super) results: FxHashMap<D::Key, QueryValue<D::Value>>,
31     pub(super) active: FxHashMap<D::Key, QueryResult<'tcx>>,
32
33     /// Used to generate unique ids for active jobs.
34     pub(super) jobs: u32,
35
36     #[cfg(debug_assertions)]
37     pub(super) cache_hits: usize,
38 }
39
40 pub(super) struct QueryValue<T> {
41     pub(super) value: T,
42     pub(super) index: DepNodeIndex,
43 }
44
45 impl<T> QueryValue<T> {
46     pub(super) fn new(value: T, dep_node_index: DepNodeIndex) -> QueryValue<T> {
47         QueryValue { value, index: dep_node_index }
48     }
49 }
50
51 /// Indicates the state of a query for a given key in a query map.
52 pub(super) enum QueryResult<'tcx> {
53     /// An already executing query. The query job can be used to await for its completion.
54     Started(QueryJob<'tcx>),
55
56     /// The query panicked. Queries trying to wait on this will raise a fatal error which will
57     /// silently panic.
58     Poisoned,
59 }
60
61 impl<'tcx, M: QueryConfig<'tcx>> Default for QueryCache<'tcx, M> {
62     fn default() -> QueryCache<'tcx, M> {
63         QueryCache {
64             results: FxHashMap::default(),
65             active: FxHashMap::default(),
66             jobs: 0,
67             #[cfg(debug_assertions)]
68             cache_hits: 0,
69         }
70     }
71 }
72
73 /// A type representing the responsibility to execute the job in the `job` field.
74 /// This will poison the relevant query if dropped.
75 pub(super) struct JobOwner<'a, 'tcx, Q: QueryDescription<'tcx>> {
76     cache: &'a Sharded<QueryCache<'tcx, Q>>,
77     key: Q::Key,
78     id: QueryJobId,
79 }
80
81 impl<'a, 'tcx, Q: QueryDescription<'tcx>> JobOwner<'a, 'tcx, Q> {
82     /// Either gets a `JobOwner` corresponding the query, allowing us to
83     /// start executing the query, or returns with the result of the query.
84     /// If the query is executing elsewhere, this will wait for it.
85     /// If the query panicked, this will silently panic.
86     ///
87     /// This function is inlined because that results in a noticeable speed-up
88     /// for some compile-time benchmarks.
89     #[inline(always)]
90     pub(super) fn try_get(tcx: TyCtxt<'tcx>, span: Span, key: &Q::Key) -> TryGetJob<'a, 'tcx, Q> {
91         // Handling the `query_blocked_prof_timer` is a bit weird because of the
92         // control flow in this function: Blocking is implemented by
93         // awaiting a running job and, once that is done, entering the loop below
94         // again from the top. In that second iteration we will hit the
95         // cache which provides us with the information we need for
96         // finishing the "query-blocked" event.
97         //
98         // We thus allocate `query_blocked_prof_timer` outside the loop,
99         // initialize it during the first iteration and finish it during the
100         // second iteration.
101         #[cfg(parallel_compiler)]
102         let mut query_blocked_prof_timer: Option<TimingGuard<'_>> = None;
103
104         let cache = Q::query_cache(tcx);
105         loop {
106             // We compute the key's hash once and then use it for both the
107             // shard lookup and the hashmap lookup. This relies on the fact
108             // that both of them use `FxHasher`.
109             let mut state = FxHasher::default();
110             key.hash(&mut state);
111             let key_hash = state.finish();
112
113             let shard = cache.get_shard_index_by_hash(key_hash);
114             let mut lock_guard = cache.get_shard_by_index(shard).lock();
115             let lock = &mut *lock_guard;
116
117             if let Some((_, value)) =
118                 lock.results.raw_entry().from_key_hashed_nocheck(key_hash, key)
119             {
120                 if unlikely!(tcx.prof.enabled()) {
121                     tcx.prof.query_cache_hit(value.index.into());
122
123                     #[cfg(parallel_compiler)]
124                     {
125                         if let Some(prof_timer) = query_blocked_prof_timer.take() {
126                             prof_timer.finish_with_query_invocation_id(value.index.into());
127                         }
128                     }
129                 }
130
131                 let result = (value.value.clone(), value.index);
132                 #[cfg(debug_assertions)]
133                 {
134                     lock.cache_hits += 1;
135                 }
136                 return TryGetJob::JobCompleted(result);
137             }
138
139             let latch = match lock.active.entry((*key).clone()) {
140                 Entry::Occupied(mut entry) => {
141                     match entry.get_mut() {
142                         QueryResult::Started(job) => {
143                             // For parallel queries, we'll block and wait until the query running
144                             // in another thread has completed. Record how long we wait in the
145                             // self-profiler.
146                             #[cfg(parallel_compiler)]
147                             {
148                                 query_blocked_prof_timer = Some(tcx.prof.query_blocked());
149                             }
150
151                             // Create the id of the job we're waiting for
152                             let id = QueryJobId::new(job.id, shard, Q::dep_kind());
153
154                             job.latch(id)
155                         }
156                         QueryResult::Poisoned => FatalError.raise(),
157                     }
158                 }
159                 Entry::Vacant(entry) => {
160                     // No job entry for this query. Return a new one to be started later.
161
162                     // Generate an id unique within this shard.
163                     let id = lock.jobs.checked_add(1).unwrap();
164                     lock.jobs = id;
165                     let id = QueryShardJobId(NonZeroU32::new(id).unwrap());
166
167                     let global_id = QueryJobId::new(id, shard, Q::dep_kind());
168
169                     let job =
170                         tls::with_related_context(tcx, |icx| QueryJob::new(id, span, icx.query));
171
172                     entry.insert(QueryResult::Started(job));
173
174                     let owner = JobOwner { cache, id: global_id, key: (*key).clone() };
175                     return TryGetJob::NotYetStarted(owner);
176                 }
177             };
178             mem::drop(lock_guard);
179
180             // If we are single-threaded we know that we have cycle error,
181             // so we just return the error.
182             #[cfg(not(parallel_compiler))]
183             return TryGetJob::Cycle(cold_path(|| {
184                 Q::handle_cycle_error(tcx, latch.find_cycle_in_stack(tcx, span))
185             }));
186
187             // With parallel queries we might just have to wait on some other
188             // thread.
189             #[cfg(parallel_compiler)]
190             {
191                 let result = latch.wait_on(tcx, span);
192
193                 if let Err(cycle) = result {
194                     return TryGetJob::Cycle(Q::handle_cycle_error(tcx, cycle));
195                 }
196             }
197         }
198     }
199
200     /// Completes the query by updating the query cache with the `result`,
201     /// signals the waiter and forgets the JobOwner, so it won't poison the query
202     #[inline(always)]
203     pub(super) fn complete(self, result: &Q::Value, dep_node_index: DepNodeIndex) {
204         // We can move out of `self` here because we `mem::forget` it below
205         let key = unsafe { ptr::read(&self.key) };
206         let cache = self.cache;
207
208         // Forget ourself so our destructor won't poison the query
209         mem::forget(self);
210
211         let value = QueryValue::new(result.clone(), dep_node_index);
212         let job = {
213             let mut lock = cache.get_shard_by_value(&key).lock();
214             let job = match lock.active.remove(&key).unwrap() {
215                 QueryResult::Started(job) => job,
216                 QueryResult::Poisoned => panic!(),
217             };
218             lock.results.insert(key, value);
219             job
220         };
221
222         job.signal_complete();
223     }
224 }
225
226 #[inline(always)]
227 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
228 where
229     F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R,
230 {
231     let diagnostics = Lock::new(ThinVec::new());
232     let result = f(Some(&diagnostics));
233     (result, diagnostics.into_inner())
234 }
235
236 impl<'a, 'tcx, Q: QueryDescription<'tcx>> Drop for JobOwner<'a, 'tcx, Q> {
237     #[inline(never)]
238     #[cold]
239     fn drop(&mut self) {
240         // Poison the query so jobs waiting on it panic.
241         let shard = self.cache.get_shard_by_value(&self.key);
242         let job = {
243             let mut shard = shard.lock();
244             let job = match shard.active.remove(&self.key).unwrap() {
245                 QueryResult::Started(job) => job,
246                 QueryResult::Poisoned => panic!(),
247             };
248             shard.active.insert(self.key.clone(), QueryResult::Poisoned);
249             job
250         };
251         // Also signal the completion of the job, so waiters
252         // will continue execution.
253         job.signal_complete();
254     }
255 }
256
257 #[derive(Clone)]
258 pub struct CycleError<'tcx> {
259     /// The query and related span that uses the cycle.
260     pub(super) usage: Option<(Span, Query<'tcx>)>,
261     pub(super) cycle: Vec<QueryInfo<'tcx>>,
262 }
263
264 /// The result of `try_get_lock`.
265 pub(super) enum TryGetJob<'a, 'tcx, D: QueryDescription<'tcx>> {
266     /// The query is not yet started. Contains a guard to the cache eventually used to start it.
267     NotYetStarted(JobOwner<'a, 'tcx, D>),
268
269     /// The query was already completed.
270     /// Returns the result of the query and its dep-node index
271     /// if it succeeded or a cycle error if it failed.
272     JobCompleted((D::Value, DepNodeIndex)),
273
274     /// Trying to execute the query resulted in a cycle.
275     Cycle(D::Value),
276 }
277
278 impl<'tcx> TyCtxt<'tcx> {
279     /// Executes a job by changing the `ImplicitCtxt` to point to the
280     /// new query job while it executes. It returns the diagnostics
281     /// captured during execution and the actual result.
282     #[inline(always)]
283     pub(super) fn start_query<F, R>(
284         self,
285         token: QueryJobId,
286         diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
287         compute: F,
288     ) -> R
289     where
290         F: FnOnce(TyCtxt<'tcx>) -> R,
291     {
292         // The `TyCtxt` stored in TLS has the same global interner lifetime
293         // as `self`, so we use `with_related_context` to relate the 'tcx lifetimes
294         // when accessing the `ImplicitCtxt`.
295         tls::with_related_context(self, move |current_icx| {
296             // Update the `ImplicitCtxt` to point to our new query job.
297             let new_icx = tls::ImplicitCtxt {
298                 tcx: self,
299                 query: Some(token),
300                 diagnostics,
301                 layout_depth: current_icx.layout_depth,
302                 task_deps: current_icx.task_deps,
303             };
304
305             // Use the `ImplicitCtxt` while we execute the query.
306             tls::enter_context(&new_icx, |_| compute(self))
307         })
308     }
309
310     #[inline(never)]
311     #[cold]
312     pub(super) fn report_cycle(
313         self,
314         CycleError { usage, cycle: stack }: CycleError<'tcx>,
315     ) -> DiagnosticBuilder<'tcx> {
316         assert!(!stack.is_empty());
317
318         let fix_span = |span: Span, query: &Query<'tcx>| {
319             self.sess.source_map().def_span(query.default_span(self, span))
320         };
321
322         // Disable naming impls with types in this path, since that
323         // sometimes cycles itself, leading to extra cycle errors.
324         // (And cycle errors around impls tend to occur during the
325         // collect/coherence phases anyhow.)
326         ty::print::with_forced_impl_filename_line(|| {
327             let span = fix_span(stack[1 % stack.len()].span, &stack[0].query);
328             let mut err = struct_span_err!(
329                 self.sess,
330                 span,
331                 E0391,
332                 "cycle detected when {}",
333                 stack[0].query.describe(self)
334             );
335
336             for i in 1..stack.len() {
337                 let query = &stack[i].query;
338                 let span = fix_span(stack[(i + 1) % stack.len()].span, query);
339                 err.span_note(span, &format!("...which requires {}...", query.describe(self)));
340             }
341
342             err.note(&format!(
343                 "...which again requires {}, completing the cycle",
344                 stack[0].query.describe(self)
345             ));
346
347             if let Some((span, query)) = usage {
348                 err.span_note(
349                     fix_span(span, &query),
350                     &format!("cycle used when {}", query.describe(self)),
351                 );
352             }
353
354             err
355         })
356     }
357
358     pub fn try_print_query_stack(handler: &Handler) {
359         eprintln!("query stack during panic:");
360
361         // Be careful reyling on global state here: this code is called from
362         // a panic hook, which means that the global `Handler` may be in a weird
363         // state if it was responsible for triggering the panic.
364         tls::with_context_opt(|icx| {
365             if let Some(icx) = icx {
366                 let query_map = icx.tcx.queries.try_collect_active_jobs();
367
368                 let mut current_query = icx.query;
369                 let mut i = 0;
370
371                 while let Some(query) = current_query {
372                     let query_info =
373                         if let Some(info) = query_map.as_ref().and_then(|map| map.get(&query)) {
374                             info
375                         } else {
376                             break;
377                         };
378                     let mut diag = Diagnostic::new(
379                         Level::FailureNote,
380                         &format!(
381                             "#{} [{}] {}",
382                             i,
383                             query_info.info.query.name(),
384                             query_info.info.query.describe(icx.tcx)
385                         ),
386                     );
387                     diag.span = icx.tcx.sess.source_map().def_span(query_info.info.span).into();
388                     handler.force_print_diagnostic(diag);
389
390                     current_query = query_info.job.parent;
391                     i += 1;
392                 }
393             }
394         });
395
396         eprintln!("end of query stack");
397     }
398
399     #[inline(never)]
400     pub(super) fn get_query<Q: QueryDescription<'tcx>>(self, span: Span, key: Q::Key) -> Q::Value {
401         debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME, key, span);
402
403         let job = match JobOwner::try_get(self, span, &key) {
404             TryGetJob::NotYetStarted(job) => job,
405             TryGetJob::Cycle(result) => return result,
406             TryGetJob::JobCompleted((v, index)) => {
407                 self.dep_graph.read_index(index);
408                 return v;
409             }
410         };
411
412         // Fast path for when incr. comp. is off. `to_dep_node` is
413         // expensive for some `DepKind`s.
414         if !self.dep_graph.is_fully_enabled() {
415             let null_dep_node = DepNode::new_no_params(crate::dep_graph::DepKind::Null);
416             return self.force_query_with_job::<Q>(key, job, null_dep_node).0;
417         }
418
419         if Q::ANON {
420             let prof_timer = self.prof.query_provider();
421
422             let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
423                 self.start_query(job.id, diagnostics, |tcx| {
424                     tcx.dep_graph.with_anon_task(Q::dep_kind(), || Q::compute(tcx, key))
425                 })
426             });
427
428             prof_timer.finish_with_query_invocation_id(dep_node_index.into());
429
430             self.dep_graph.read_index(dep_node_index);
431
432             if unlikely!(!diagnostics.is_empty()) {
433                 self.queries
434                     .on_disk_cache
435                     .store_diagnostics_for_anon_node(dep_node_index, diagnostics);
436             }
437
438             job.complete(&result, dep_node_index);
439
440             return result;
441         }
442
443         let dep_node = Q::to_dep_node(self, &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 = self.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                         tcx.load_from_disk_and_cache_in_memory::<Q>(
454                             key.clone(),
455                             prev_dep_node_index,
456                             dep_node_index,
457                             &dep_node,
458                         ),
459                         dep_node_index,
460                     )
461                 })
462             });
463             if let Some((result, dep_node_index)) = loaded {
464                 job.complete(&result, dep_node_index);
465                 return result;
466             }
467         }
468
469         let (result, dep_node_index) = self.force_query_with_job::<Q>(key, job, dep_node);
470         self.dep_graph.read_index(dep_node_index);
471         result
472     }
473
474     fn load_from_disk_and_cache_in_memory<Q: QueryDescription<'tcx>>(
475         self,
476         key: Q::Key,
477         prev_dep_node_index: SerializedDepNodeIndex,
478         dep_node_index: DepNodeIndex,
479         dep_node: &DepNode,
480     ) -> Q::Value {
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!(self.dep_graph.is_green(dep_node));
485
486         // First we try to load the result from the on-disk cache.
487         let result = if Q::cache_on_disk(self, key.clone(), None)
488             && self.sess.opts.debugging_opts.incremental_queries
489         {
490             let prof_timer = self.prof.incr_cache_loading();
491             let result = Q::try_load_from_disk(self, prev_dep_node_index);
492             prof_timer.finish_with_query_invocation_id(dep_node_index.into());
493
494             // We always expect to find a cached result for things that
495             // can be forced from `DepNode`.
496             debug_assert!(
497                 !dep_node.kind.can_reconstruct_query_key() || result.is_some(),
498                 "missing on-disk cache entry for {:?}",
499                 dep_node
500             );
501             result
502         } else {
503             // Some things are never cached on disk.
504             None
505         };
506
507         let result = if let Some(result) = result {
508             result
509         } else {
510             // We could not load a result from the on-disk cache, so
511             // recompute.
512             let prof_timer = self.prof.query_provider();
513
514             // The dep-graph for this computation is already in-place.
515             let result = self.dep_graph.with_ignore(|| Q::compute(self, key));
516
517             prof_timer.finish_with_query_invocation_id(dep_node_index.into());
518
519             result
520         };
521
522         // If `-Zincremental-verify-ich` is specified, re-hash results from
523         // the cache and make sure that they have the expected fingerprint.
524         if unlikely!(self.sess.opts.debugging_opts.incremental_verify_ich) {
525             self.incremental_verify_ich::<Q>(&result, dep_node, dep_node_index);
526         }
527
528         result
529     }
530
531     #[inline(never)]
532     #[cold]
533     fn incremental_verify_ich<Q: QueryDescription<'tcx>>(
534         self,
535         result: &Q::Value,
536         dep_node: &DepNode,
537         dep_node_index: DepNodeIndex,
538     ) {
539         use crate::ich::Fingerprint;
540
541         assert!(
542             Some(self.dep_graph.fingerprint_of(dep_node_index))
543                 == self.dep_graph.prev_fingerprint_of(dep_node),
544             "fingerprint for green query instance not loaded from cache: {:?}",
545             dep_node,
546         );
547
548         debug!("BEGIN verify_ich({:?})", dep_node);
549         let mut hcx = self.create_stable_hashing_context();
550
551         let new_hash = Q::hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
552         debug!("END verify_ich({:?})", dep_node);
553
554         let old_hash = self.dep_graph.fingerprint_of(dep_node_index);
555
556         assert!(new_hash == old_hash, "found unstable fingerprints for {:?}", dep_node,);
557     }
558
559     #[inline(always)]
560     fn force_query_with_job<Q: QueryDescription<'tcx>>(
561         self,
562         key: Q::Key,
563         job: JobOwner<'_, 'tcx, Q>,
564         dep_node: DepNode,
565     ) -> (Q::Value, DepNodeIndex) {
566         // If the following assertion triggers, it can have two reasons:
567         // 1. Something is wrong with DepNode creation, either here or
568         //    in `DepGraph::try_mark_green()`.
569         // 2. Two distinct query keys get mapped to the same `DepNode`
570         //    (see for example #48923).
571         assert!(
572             !self.dep_graph.dep_node_exists(&dep_node),
573             "forcing query with already existing `DepNode`\n\
574                  - query-key: {:?}\n\
575                  - dep-node: {:?}",
576             key,
577             dep_node
578         );
579
580         let prof_timer = self.prof.query_provider();
581
582         let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
583             self.start_query(job.id, diagnostics, |tcx| {
584                 if Q::EVAL_ALWAYS {
585                     tcx.dep_graph.with_eval_always_task(
586                         dep_node,
587                         tcx,
588                         key,
589                         Q::compute,
590                         Q::hash_result,
591                     )
592                 } else {
593                     tcx.dep_graph.with_task(dep_node, tcx, key, Q::compute, Q::hash_result)
594                 }
595             })
596         });
597
598         prof_timer.finish_with_query_invocation_id(dep_node_index.into());
599
600         if unlikely!(!diagnostics.is_empty()) {
601             if dep_node.kind != crate::dep_graph::DepKind::Null {
602                 self.queries.on_disk_cache.store_diagnostics(dep_node_index, diagnostics);
603             }
604         }
605
606         job.complete(&result, dep_node_index);
607
608         (result, dep_node_index)
609     }
610
611     /// Ensure that either this query has all green inputs or been executed.
612     /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
613     ///
614     /// This function is particularly useful when executing passes for their
615     /// side-effects -- e.g., in order to report errors for erroneous programs.
616     ///
617     /// Note: The optimization is only available during incr. comp.
618     pub(super) fn ensure_query<Q: QueryDescription<'tcx>>(self, key: Q::Key) -> () {
619         if Q::EVAL_ALWAYS {
620             let _ = self.get_query::<Q>(DUMMY_SP, key);
621             return;
622         }
623
624         // Ensuring an anonymous query makes no sense
625         assert!(!Q::ANON);
626
627         let dep_node = Q::to_dep_node(self, &key);
628
629         match self.dep_graph.try_mark_green_and_read(self, &dep_node) {
630             None => {
631                 // A None return from `try_mark_green_and_read` means that this is either
632                 // a new dep node or that the dep node has already been marked red.
633                 // Either way, we can't call `dep_graph.read()` as we don't have the
634                 // DepNodeIndex. We must invoke the query itself. The performance cost
635                 // this introduces should be negligible as we'll immediately hit the
636                 // in-memory cache, or another query down the line will.
637                 let _ = self.get_query::<Q>(DUMMY_SP, key);
638             }
639             Some((_, dep_node_index)) => {
640                 self.prof.query_cache_hit(dep_node_index.into());
641             }
642         }
643     }
644
645     #[allow(dead_code)]
646     fn force_query<Q: QueryDescription<'tcx>>(self, key: Q::Key, span: Span, dep_node: DepNode) {
647         // We may be concurrently trying both execute and force a query.
648         // Ensure that only one of them runs the query.
649         let job = match JobOwner::try_get(self, span, &key) {
650             TryGetJob::NotYetStarted(job) => job,
651             TryGetJob::Cycle(_) | TryGetJob::JobCompleted(_) => return,
652         };
653         self.force_query_with_job::<Q>(key, job, dep_node);
654     }
655 }
656
657 macro_rules! handle_cycle_error {
658     ([][$tcx: expr, $error:expr]) => {{
659         $tcx.report_cycle($error).emit();
660         Value::from_cycle_error($tcx)
661     }};
662     ([fatal_cycle$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
663         $tcx.report_cycle($error).emit();
664         $tcx.sess.abort_if_errors();
665         unreachable!()
666     }};
667     ([cycle_delay_bug$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
668         $tcx.report_cycle($error).delay_as_bug();
669         Value::from_cycle_error($tcx)
670     }};
671     ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
672         handle_cycle_error!([$($modifiers),*][$($args)*])
673     };
674 }
675
676 macro_rules! is_anon {
677     ([]) => {{
678         false
679     }};
680     ([anon$(, $modifiers:ident)*]) => {{
681         true
682     }};
683     ([$other:ident$(, $modifiers:ident)*]) => {
684         is_anon!([$($modifiers),*])
685     };
686 }
687
688 macro_rules! is_eval_always {
689     ([]) => {{
690         false
691     }};
692     ([eval_always$(, $modifiers:ident)*]) => {{
693         true
694     }};
695     ([$other:ident$(, $modifiers:ident)*]) => {
696         is_eval_always!([$($modifiers),*])
697     };
698 }
699
700 macro_rules! hash_result {
701     ([][$hcx:expr, $result:expr]) => {{
702         dep_graph::hash_result($hcx, &$result)
703     }};
704     ([no_hash$(, $modifiers:ident)*][$hcx:expr, $result:expr]) => {{
705         None
706     }};
707     ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
708         hash_result!([$($modifiers),*][$($args)*])
709     };
710 }
711
712 macro_rules! define_queries {
713     (<$tcx:tt> $($category:tt {
714         $($(#[$attr:meta])* [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*
715     },)*) => {
716         define_queries_inner! { <$tcx>
717             $($( $(#[$attr])* category<$category> [$($modifiers)*] fn $name: $node($K) -> $V,)*)*
718         }
719     }
720 }
721
722 macro_rules! define_queries_inner {
723     (<$tcx:tt>
724      $($(#[$attr:meta])* category<$category:tt>
725         [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
726
727         use std::mem;
728         use rustc_data_structures::sharded::Sharded;
729         use crate::{
730             rustc_data_structures::stable_hasher::HashStable,
731             rustc_data_structures::stable_hasher::StableHasher,
732             ich::StableHashingContext
733         };
734         use rustc_data_structures::profiling::ProfileCategory;
735
736         define_queries_struct! {
737             tcx: $tcx,
738             input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
739         }
740
741         impl<$tcx> Queries<$tcx> {
742             pub fn new(
743                 providers: IndexVec<CrateNum, Providers<$tcx>>,
744                 fallback_extern_providers: Providers<$tcx>,
745                 on_disk_cache: OnDiskCache<'tcx>,
746             ) -> Self {
747                 Queries {
748                     providers,
749                     fallback_extern_providers: Box::new(fallback_extern_providers),
750                     on_disk_cache,
751                     $($name: Default::default()),*
752                 }
753             }
754
755             pub fn try_collect_active_jobs(
756                 &self
757             ) -> Option<FxHashMap<QueryJobId, QueryJobInfo<'tcx>>> {
758                 let mut jobs = FxHashMap::default();
759
760                 $(
761                     // We use try_lock_shards here since we are called from the
762                     // deadlock handler, and this shouldn't be locked.
763                     let shards = self.$name.try_lock_shards()?;
764                     let shards = shards.iter().enumerate();
765                     jobs.extend(shards.flat_map(|(shard_id, shard)| {
766                         shard.active.iter().filter_map(move |(k, v)| {
767                             if let QueryResult::Started(ref job) = *v {
768                                 let id = QueryJobId {
769                                     job: job.id,
770                                     shard:  u16::try_from(shard_id).unwrap(),
771                                     kind:
772                                         <queries::$name<'tcx> as QueryAccessors<'tcx>>::dep_kind(),
773                                 };
774                                 let info = QueryInfo {
775                                     span: job.span,
776                                     query: queries::$name::query(k.clone())
777                                 };
778                                 Some((id, QueryJobInfo { info,  job: job.clone() }))
779                             } else {
780                                 None
781                             }
782                         })
783                     }));
784                 )*
785
786                 Some(jobs)
787             }
788
789             pub fn print_stats(&self) {
790                 let mut queries = Vec::new();
791
792                 #[derive(Clone)]
793                 struct QueryStats {
794                     name: &'static str,
795                     cache_hits: usize,
796                     key_size: usize,
797                     key_type: &'static str,
798                     value_size: usize,
799                     value_type: &'static str,
800                     entry_count: usize,
801                 }
802
803                 fn stats<'tcx, Q: QueryConfig<'tcx>>(
804                     name: &'static str,
805                     map: &Sharded<QueryCache<'tcx, Q>>,
806                 ) -> QueryStats {
807                     let map = map.lock_shards();
808                     QueryStats {
809                         name,
810                         #[cfg(debug_assertions)]
811                         cache_hits: map.iter().map(|shard| shard.cache_hits).sum(),
812                         #[cfg(not(debug_assertions))]
813                         cache_hits: 0,
814                         key_size: mem::size_of::<Q::Key>(),
815                         key_type: type_name::<Q::Key>(),
816                         value_size: mem::size_of::<Q::Value>(),
817                         value_type: type_name::<Q::Value>(),
818                         entry_count: map.iter().map(|shard| shard.results.len()).sum(),
819                     }
820                 }
821
822                 $(
823                     queries.push(stats::<queries::$name<'_>>(
824                         stringify!($name),
825                         &self.$name,
826                     ));
827                 )*
828
829                 if cfg!(debug_assertions) {
830                     let hits: usize = queries.iter().map(|s| s.cache_hits).sum();
831                     let results: usize = queries.iter().map(|s| s.entry_count).sum();
832                     println!("\nQuery cache hit rate: {}", hits as f64 / (hits + results) as f64);
833                 }
834
835                 let mut query_key_sizes = queries.clone();
836                 query_key_sizes.sort_by_key(|q| q.key_size);
837                 println!("\nLarge query keys:");
838                 for q in query_key_sizes.iter().rev()
839                                         .filter(|q| q.key_size > 8) {
840                     println!(
841                         "   {} - {} x {} - {}",
842                         q.name,
843                         q.key_size,
844                         q.entry_count,
845                         q.key_type
846                     );
847                 }
848
849                 let mut query_value_sizes = queries.clone();
850                 query_value_sizes.sort_by_key(|q| q.value_size);
851                 println!("\nLarge query values:");
852                 for q in query_value_sizes.iter().rev()
853                                           .filter(|q| q.value_size > 8) {
854                     println!(
855                         "   {} - {} x {} - {}",
856                         q.name,
857                         q.value_size,
858                         q.entry_count,
859                         q.value_type
860                     );
861                 }
862
863                 if cfg!(debug_assertions) {
864                     let mut query_cache_hits = queries.clone();
865                     query_cache_hits.sort_by_key(|q| q.cache_hits);
866                     println!("\nQuery cache hits:");
867                     for q in query_cache_hits.iter().rev() {
868                         println!(
869                             "   {} - {} ({}%)",
870                             q.name,
871                             q.cache_hits,
872                             q.cache_hits as f64 / (q.cache_hits + q.entry_count) as f64
873                         );
874                     }
875                 }
876
877                 let mut query_value_count = queries.clone();
878                 query_value_count.sort_by_key(|q| q.entry_count);
879                 println!("\nQuery value count:");
880                 for q in query_value_count.iter().rev() {
881                     println!("   {} - {}", q.name, q.entry_count);
882                 }
883             }
884         }
885
886         #[allow(nonstandard_style)]
887         #[derive(Clone, Debug)]
888         pub enum Query<$tcx> {
889             $($(#[$attr])* $name($K)),*
890         }
891
892         impl<$tcx> Query<$tcx> {
893             pub fn name(&self) -> &'static str {
894                 match *self {
895                     $(Query::$name(_) => stringify!($name),)*
896                 }
897             }
898
899             pub fn describe(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
900                 let (r, name) = match *self {
901                     $(Query::$name(key) => {
902                         (queries::$name::describe(tcx, key), stringify!($name))
903                     })*
904                 };
905                 if tcx.sess.verbose() {
906                     format!("{} [{}]", r, name).into()
907                 } else {
908                     r
909                 }
910             }
911
912             // FIXME(eddyb) Get more valid `Span`s on queries.
913             pub fn default_span(&self, tcx: TyCtxt<$tcx>, span: Span) -> Span {
914                 if !span.is_dummy() {
915                     return span;
916                 }
917                 // The `def_span` query is used to calculate `default_span`,
918                 // so exit to avoid infinite recursion.
919                 if let Query::def_span(..) = *self {
920                     return span
921                 }
922                 match *self {
923                     $(Query::$name(key) => key.default_span(tcx),)*
924                 }
925             }
926         }
927
928         impl<'a, $tcx> HashStable<StableHashingContext<'a>> for Query<$tcx> {
929             fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
930                 mem::discriminant(self).hash_stable(hcx, hasher);
931                 match *self {
932                     $(Query::$name(key) => key.hash_stable(hcx, hasher),)*
933                 }
934             }
935         }
936
937         pub mod queries {
938             use std::marker::PhantomData;
939
940             $(#[allow(nonstandard_style)]
941             pub struct $name<$tcx> {
942                 data: PhantomData<&$tcx ()>
943             })*
944         }
945
946         // This module and the functions in it exist only to provide a
947         // predictable symbol name prefix for query providers. This is helpful
948         // for analyzing queries in profilers.
949         pub(super) mod __query_compute {
950             $(#[inline(never)]
951             pub fn $name<F: FnOnce() -> R, R>(f: F) -> R {
952                 f()
953             })*
954         }
955
956         $(impl<$tcx> QueryConfig<$tcx> for queries::$name<$tcx> {
957             type Key = $K;
958             type Value = $V;
959
960             const NAME: &'static str = stringify!($name);
961             const CATEGORY: ProfileCategory = $category;
962         }
963
964         impl<$tcx> QueryAccessors<$tcx> for queries::$name<$tcx> {
965             const ANON: bool = is_anon!([$($modifiers)*]);
966             const EVAL_ALWAYS: bool = is_eval_always!([$($modifiers)*]);
967
968             #[inline(always)]
969             fn query(key: Self::Key) -> Query<'tcx> {
970                 Query::$name(key)
971             }
972
973             #[inline(always)]
974             fn query_cache<'a>(tcx: TyCtxt<$tcx>) -> &'a Sharded<QueryCache<$tcx, Self>> {
975                 &tcx.queries.$name
976             }
977
978             #[allow(unused)]
979             #[inline(always)]
980             fn to_dep_node(tcx: TyCtxt<$tcx>, key: &Self::Key) -> DepNode {
981                 use crate::dep_graph::DepConstructor::*;
982
983                 DepNode::new(tcx, $node(*key))
984             }
985
986             #[inline(always)]
987             fn dep_kind() -> dep_graph::DepKind {
988                 dep_graph::DepKind::$node
989             }
990
991             #[inline]
992             fn compute(tcx: TyCtxt<'tcx>, key: Self::Key) -> Self::Value {
993                 __query_compute::$name(move || {
994                     let provider = tcx.queries.providers.get(key.query_crate())
995                         // HACK(eddyb) it's possible crates may be loaded after
996                         // the query engine is created, and because crate loading
997                         // is not yet integrated with the query engine, such crates
998                         // would be missing appropriate entries in `providers`.
999                         .unwrap_or(&tcx.queries.fallback_extern_providers)
1000                         .$name;
1001                     provider(tcx, key)
1002                 })
1003             }
1004
1005             fn hash_result(
1006                 _hcx: &mut StableHashingContext<'_>,
1007                 _result: &Self::Value
1008             ) -> Option<Fingerprint> {
1009                 hash_result!([$($modifiers)*][_hcx, _result])
1010             }
1011
1012             fn handle_cycle_error(
1013                 tcx: TyCtxt<'tcx>,
1014                 error: CycleError<'tcx>
1015             ) -> Self::Value {
1016                 handle_cycle_error!([$($modifiers)*][tcx, error])
1017             }
1018         })*
1019
1020         #[derive(Copy, Clone)]
1021         pub struct TyCtxtEnsure<'tcx> {
1022             pub tcx: TyCtxt<'tcx>,
1023         }
1024
1025         impl TyCtxtEnsure<$tcx> {
1026             $($(#[$attr])*
1027             #[inline(always)]
1028             pub fn $name(self, key: $K) {
1029                 self.tcx.ensure_query::<queries::$name<'_>>(key)
1030             })*
1031         }
1032
1033         #[derive(Copy, Clone)]
1034         pub struct TyCtxtAt<'tcx> {
1035             pub tcx: TyCtxt<'tcx>,
1036             pub span: Span,
1037         }
1038
1039         impl Deref for TyCtxtAt<'tcx> {
1040             type Target = TyCtxt<'tcx>;
1041             #[inline(always)]
1042             fn deref(&self) -> &Self::Target {
1043                 &self.tcx
1044             }
1045         }
1046
1047         impl TyCtxt<$tcx> {
1048             /// Returns a transparent wrapper for `TyCtxt`, which ensures queries
1049             /// are executed instead of just returing their results.
1050             #[inline(always)]
1051             pub fn ensure(self) -> TyCtxtEnsure<$tcx> {
1052                 TyCtxtEnsure {
1053                     tcx: self,
1054                 }
1055             }
1056
1057             /// Returns a transparent wrapper for `TyCtxt` which uses
1058             /// `span` as the location of queries performed through it.
1059             #[inline(always)]
1060             pub fn at(self, span: Span) -> TyCtxtAt<$tcx> {
1061                 TyCtxtAt {
1062                     tcx: self,
1063                     span
1064                 }
1065             }
1066
1067             $($(#[$attr])*
1068             #[inline(always)]
1069             pub fn $name(self, key: $K) -> $V {
1070                 self.at(DUMMY_SP).$name(key)
1071             })*
1072
1073             /// All self-profiling events generated by the query engine use
1074             /// virtual `StringId`s for their `event_id`. This method makes all
1075             /// those virtual `StringId`s point to actual strings.
1076             ///
1077             /// If we are recording only summary data, the ids will point to
1078             /// just the query names. If we are recording query keys too, we
1079             /// allocate the corresponding strings here.
1080             pub fn alloc_self_profile_query_strings(self) {
1081                 use crate::ty::query::profiling_support::{
1082                     alloc_self_profile_query_strings_for_query_cache,
1083                     QueryKeyStringCache,
1084                 };
1085
1086                 if !self.prof.enabled() {
1087                     return;
1088                 }
1089
1090                 let mut string_cache = QueryKeyStringCache::new();
1091
1092                 $({
1093                     alloc_self_profile_query_strings_for_query_cache(
1094                         self,
1095                         stringify!($name),
1096                         &self.queries.$name,
1097                         &mut string_cache,
1098                     );
1099                 })*
1100             }
1101         }
1102
1103         impl TyCtxtAt<$tcx> {
1104             $($(#[$attr])*
1105             #[inline(always)]
1106             pub fn $name(self, key: $K) -> $V {
1107                 self.tcx.get_query::<queries::$name<'_>>(self.span, key)
1108             })*
1109         }
1110
1111         define_provider_struct! {
1112             tcx: $tcx,
1113             input: ($(([$($modifiers)*] [$name] [$K] [$V]))*)
1114         }
1115
1116         impl<$tcx> Copy for Providers<$tcx> {}
1117         impl<$tcx> Clone for Providers<$tcx> {
1118             fn clone(&self) -> Self { *self }
1119         }
1120     }
1121 }
1122
1123 macro_rules! define_queries_struct {
1124     (tcx: $tcx:tt,
1125      input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
1126         pub struct Queries<$tcx> {
1127             /// This provides access to the incrimental comilation on-disk cache for query results.
1128             /// Do not access this directly. It is only meant to be used by
1129             /// `DepGraph::try_mark_green()` and the query infrastructure.
1130             pub(crate) on_disk_cache: OnDiskCache<'tcx>,
1131
1132             providers: IndexVec<CrateNum, Providers<$tcx>>,
1133             fallback_extern_providers: Box<Providers<$tcx>>,
1134
1135             $($(#[$attr])*  $name: Sharded<QueryCache<$tcx, queries::$name<$tcx>>>,)*
1136         }
1137     };
1138 }
1139
1140 macro_rules! define_provider_struct {
1141     (tcx: $tcx:tt,
1142      input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
1143         pub struct Providers<$tcx> {
1144             $(pub $name: fn(TyCtxt<$tcx>, $K) -> $R,)*
1145         }
1146
1147         impl<$tcx> Default for Providers<$tcx> {
1148             fn default() -> Self {
1149                 $(fn $name<$tcx>(_: TyCtxt<$tcx>, key: $K) -> $R {
1150                     bug!("`tcx.{}({:?})` unsupported by its crate",
1151                          stringify!($name), key);
1152                 })*
1153                 Providers { $($name),* }
1154             }
1155         }
1156     };
1157 }
1158
1159 /// The red/green evaluation system will try to mark a specific DepNode in the
1160 /// dependency graph as green by recursively trying to mark the dependencies of
1161 /// that `DepNode` as green. While doing so, it will sometimes encounter a `DepNode`
1162 /// where we don't know if it is red or green and we therefore actually have
1163 /// to recompute its value in order to find out. Since the only piece of
1164 /// information that we have at that point is the `DepNode` we are trying to
1165 /// re-evaluate, we need some way to re-run a query from just that. This is what
1166 /// `force_from_dep_node()` implements.
1167 ///
1168 /// In the general case, a `DepNode` consists of a `DepKind` and an opaque
1169 /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
1170 /// is usually constructed by computing a stable hash of the query-key that the
1171 /// `DepNode` corresponds to. Consequently, it is not in general possible to go
1172 /// back from hash to query-key (since hash functions are not reversible). For
1173 /// this reason `force_from_dep_node()` is expected to fail from time to time
1174 /// because we just cannot find out, from the `DepNode` alone, what the
1175 /// corresponding query-key is and therefore cannot re-run the query.
1176 ///
1177 /// The system deals with this case letting `try_mark_green` fail which forces
1178 /// the root query to be re-evaluated.
1179 ///
1180 /// Now, if `force_from_dep_node()` would always fail, it would be pretty useless.
1181 /// Fortunately, we can use some contextual information that will allow us to
1182 /// reconstruct query-keys for certain kinds of `DepNode`s. In particular, we
1183 /// enforce by construction that the GUID/fingerprint of certain `DepNode`s is a
1184 /// valid `DefPathHash`. Since we also always build a huge table that maps every
1185 /// `DefPathHash` in the current codebase to the corresponding `DefId`, we have
1186 /// everything we need to re-run the query.
1187 ///
1188 /// Take the `mir_validated` query as an example. Like many other queries, it
1189 /// just has a single parameter: the `DefId` of the item it will compute the
1190 /// validated MIR for. Now, when we call `force_from_dep_node()` on a `DepNode`
1191 /// with kind `MirValidated`, we know that the GUID/fingerprint of the `DepNode`
1192 /// is actually a `DefPathHash`, and can therefore just look up the corresponding
1193 /// `DefId` in `tcx.def_path_hash_to_def_id`.
1194 ///
1195 /// When you implement a new query, it will likely have a corresponding new
1196 /// `DepKind`, and you'll have to support it here in `force_from_dep_node()`. As
1197 /// a rule of thumb, if your query takes a `DefId` or `DefIndex` as sole parameter,
1198 /// then `force_from_dep_node()` should not fail for it. Otherwise, you can just
1199 /// add it to the "We don't have enough information to reconstruct..." group in
1200 /// the match below.
1201 pub fn force_from_dep_node(tcx: TyCtxt<'_>, dep_node: &DepNode) -> bool {
1202     use crate::dep_graph::RecoverKey;
1203
1204     // We must avoid ever having to call `force_from_dep_node()` for a
1205     // `DepNode::codegen_unit`:
1206     // Since we cannot reconstruct the query key of a `DepNode::codegen_unit`, we
1207     // would always end up having to evaluate the first caller of the
1208     // `codegen_unit` query that *is* reconstructible. This might very well be
1209     // the `compile_codegen_unit` query, thus re-codegenning the whole CGU just
1210     // to re-trigger calling the `codegen_unit` query with the right key. At
1211     // that point we would already have re-done all the work we are trying to
1212     // avoid doing in the first place.
1213     // The solution is simple: Just explicitly call the `codegen_unit` query for
1214     // each CGU, right after partitioning. This way `try_mark_green` will always
1215     // hit the cache instead of having to go through `force_from_dep_node`.
1216     // This assertion makes sure, we actually keep applying the solution above.
1217     debug_assert!(
1218         dep_node.kind != DepKind::codegen_unit,
1219         "calling force_from_dep_node() on DepKind::codegen_unit"
1220     );
1221
1222     if !dep_node.kind.can_reconstruct_query_key() {
1223         return false;
1224     }
1225
1226     rustc_dep_node_force!([dep_node, tcx]
1227         // These are inputs that are expected to be pre-allocated and that
1228         // should therefore always be red or green already.
1229         DepKind::AllLocalTraitImpls |
1230         DepKind::CrateMetadata |
1231         DepKind::HirBody |
1232         DepKind::Hir |
1233
1234         // These are anonymous nodes.
1235         DepKind::TraitSelect |
1236
1237         // We don't have enough information to reconstruct the query key of
1238         // these.
1239         DepKind::CompileCodegenUnit => {
1240             bug!("force_from_dep_node: encountered {:?}", dep_node)
1241         }
1242
1243         DepKind::Analysis => {
1244             let def_id = if let Some(def_id) = dep_node.extract_def_id(tcx) {
1245                 def_id
1246             } else {
1247                 // Return from the whole function.
1248                 return false
1249             };
1250             tcx.force_query::<crate::ty::query::queries::analysis<'_>>(
1251                 def_id.krate,
1252                 DUMMY_SP,
1253                 *dep_node
1254             );
1255         }
1256     );
1257
1258     true
1259 }