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