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