]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/query/plumbing.rs
Rollup merge of #61518 - czipperz:const-fn-doc-disallow-loops, r=Centril
[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::{DepNodeIndex, DepNode, DepKind, SerializedDepNodeIndex};
6 use crate::ty::tls;
7 use crate::ty::{self, TyCtxt};
8 use crate::ty::query::Query;
9 use crate::ty::query::config::{QueryConfig, QueryDescription};
10 use crate::ty::query::job::{QueryJob, QueryResult, QueryInfo};
11
12 use crate::util::common::{profq_msg, ProfileQueriesMsg, QueryMsg};
13
14 use errors::DiagnosticBuilder;
15 use errors::Level;
16 use errors::Diagnostic;
17 use errors::FatalError;
18 use rustc_data_structures::fx::{FxHashMap};
19 use rustc_data_structures::sync::{Lrc, Lock};
20 use rustc_data_structures::thin_vec::ThinVec;
21 #[cfg(not(parallel_compiler))]
22 use rustc_data_structures::cold_path;
23 use std::mem;
24 use std::ptr;
25 use std::collections::hash_map::Entry;
26 use syntax_pos::Span;
27 use syntax::source_map::DUMMY_SP;
28
29 pub struct QueryCache<'tcx, D: QueryConfig<'tcx> + ?Sized> {
30     pub(super) results: FxHashMap<D::Key, QueryValue<D::Value>>,
31     pub(super) active: FxHashMap<D::Key, QueryResult<'tcx>>,
32     #[cfg(debug_assertions)]
33     pub(super) cache_hits: usize,
34 }
35
36 pub(super) struct QueryValue<T> {
37     pub(super) value: T,
38     pub(super) index: DepNodeIndex,
39 }
40
41 impl<T> QueryValue<T> {
42     pub(super) fn new(value: T,
43                       dep_node_index: DepNodeIndex)
44                       -> QueryValue<T> {
45         QueryValue {
46             value,
47             index: dep_node_index,
48         }
49     }
50 }
51
52 impl<'tcx, M: QueryConfig<'tcx>> Default for QueryCache<'tcx, M> {
53     fn default() -> QueryCache<'tcx, M> {
54         QueryCache {
55             results: FxHashMap::default(),
56             active: FxHashMap::default(),
57             #[cfg(debug_assertions)]
58             cache_hits: 0,
59         }
60     }
61 }
62
63 // If enabled, send a message to the profile-queries thread
64 macro_rules! profq_msg {
65     ($tcx:expr, $msg:expr) => {
66         if cfg!(debug_assertions) {
67             if $tcx.sess.profile_queries() {
68                 profq_msg($tcx.sess, $msg)
69             }
70         }
71     }
72 }
73
74 // If enabled, format a key using its debug string, which can be
75 // expensive to compute (in terms of time).
76 macro_rules! profq_query_msg {
77     ($query:expr, $tcx:expr, $key:expr) => {{
78         let msg = if cfg!(debug_assertions) {
79             if $tcx.sess.profile_queries_and_keys() {
80                 Some(format!("{:?}", $key))
81             } else { None }
82         } else { None };
83         QueryMsg {
84             query: $query,
85             msg,
86         }
87     }}
88 }
89
90 /// A type representing the responsibility to execute the job in the `job` field.
91 /// This will poison the relevant query if dropped.
92 pub(super) struct JobOwner<'a, 'tcx: 'a, Q: QueryDescription<'tcx> + 'a> {
93     cache: &'a Lock<QueryCache<'tcx, Q>>,
94     key: Q::Key,
95     job: Lrc<QueryJob<'tcx>>,
96 }
97
98 impl<'a, 'tcx, Q: QueryDescription<'tcx>> JobOwner<'a, 'tcx, Q> {
99     /// Either gets a `JobOwner` corresponding the query, allowing us to
100     /// start executing the query, or it returns with the result of the query.
101     /// If the query is executing elsewhere, this will wait for it.
102     /// If the query panicked, this will silently panic.
103     ///
104     /// This function is inlined because that results in a noticeable speed-up
105     /// for some compile-time benchmarks.
106     #[inline(always)]
107     pub(super) fn try_get(
108         tcx: TyCtxt<'a, 'tcx, '_>,
109         span: Span,
110         key: &Q::Key,
111     ) -> TryGetJob<'a, 'tcx, Q> {
112         let cache = Q::query_cache(tcx);
113         loop {
114             let mut lock = cache.borrow_mut();
115             if let Some(value) = lock.results.get(key) {
116                 profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
117                 tcx.sess.profiler(|p| p.record_query_hit(Q::NAME));
118                 let result = (value.value.clone(), value.index);
119                 #[cfg(debug_assertions)]
120                 {
121                     lock.cache_hits += 1;
122                 }
123                 return TryGetJob::JobCompleted(result);
124             }
125             let job = match lock.active.entry((*key).clone()) {
126                 Entry::Occupied(entry) => {
127                     match *entry.get() {
128                         QueryResult::Started(ref job) => {
129                             // For parallel queries, we'll block and wait until the query running
130                             // in another thread has completed. Record how long we wait in the
131                             // self-profiler.
132                             #[cfg(parallel_compiler)]
133                             tcx.sess.profiler(|p| p.query_blocked_start(Q::NAME));
134
135                             job.clone()
136                         },
137                         QueryResult::Poisoned => FatalError.raise(),
138                     }
139                 }
140                 Entry::Vacant(entry) => {
141                     // No job entry for this query. Return a new one to be started later.
142                     return tls::with_related_context(tcx, |icx| {
143                         // Create the `parent` variable before `info`. This allows LLVM
144                         // to elide the move of `info`
145                         let parent = icx.query.clone();
146                         let info = QueryInfo {
147                             span,
148                             query: Q::query(key.clone()),
149                         };
150                         let job = Lrc::new(QueryJob::new(info, parent));
151                         let owner = JobOwner {
152                             cache,
153                             job: job.clone(),
154                             key: (*key).clone(),
155                         };
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                 tcx.sess.profiler(|p| p.query_blocked_end(Q::NAME));
176
177                 if let Err(cycle) = result {
178                     return TryGetJob::Cycle(Q::handle_cycle_error(tcx, cycle));
179                 }
180             }
181         }
182     }
183
184     /// Completes the query by updating the query cache with the `result`,
185     /// signals the waiter and forgets the JobOwner, so it won't poison the query
186     #[inline(always)]
187     pub(super) fn complete(self, result: &Q::Value, dep_node_index: DepNodeIndex) {
188         // We can move out of `self` here because we `mem::forget` it below
189         let key = unsafe { ptr::read(&self.key) };
190         let job = unsafe { ptr::read(&self.job) };
191         let cache = self.cache;
192
193         // Forget ourself so our destructor won't poison the query
194         mem::forget(self);
195
196         let value = QueryValue::new(result.clone(), dep_node_index);
197         {
198             let mut lock = cache.borrow_mut();
199             lock.active.remove(&key);
200             lock.results.insert(key, value);
201         }
202
203         job.signal_complete();
204     }
205 }
206
207 #[inline(always)]
208 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
209 where
210     F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R
211 {
212     let diagnostics = Lock::new(ThinVec::new());
213     let result = f(Some(&diagnostics));
214     (result, diagnostics.into_inner())
215 }
216
217 impl<'a, 'tcx, Q: QueryDescription<'tcx>> Drop for JobOwner<'a, 'tcx, Q> {
218     #[inline(never)]
219     #[cold]
220     fn drop(&mut self) {
221         // Poison the query so jobs waiting on it panic
222         self.cache.borrow_mut().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 which 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: 'a, D: QueryDescription<'tcx> + 'a> {
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<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, '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<'gcx>>,
258         diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
259         compute: F)
260     -> R
261     where
262         F: for<'b, 'lcx> FnOnce(TyCtxt<'b, 'gcx, 'lcx>) -> 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 'gcx 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.global_tcx(),
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, |_| {
279                 compute(self.global_tcx())
280             })
281         })
282     }
283
284     #[inline(never)]
285     #[cold]
286     pub(super) fn report_cycle(
287         self,
288         CycleError { usage, cycle: stack }: CycleError<'gcx>
289     ) -> DiagnosticBuilder<'a>
290     {
291         assert!(!stack.is_empty());
292
293         let fix_span = |span: Span, query: &Query<'gcx>| {
294             self.sess.source_map().def_span(query.default_span(self, span))
295         };
296
297         // Disable naming impls with types in this path, since that
298         // sometimes cycles itself, leading to extra cycle errors.
299         // (And cycle errors around impls tend to occur during the
300         // collect/coherence phases anyhow.)
301         ty::print::with_forced_impl_filename_line(|| {
302             let span = fix_span(stack[1 % stack.len()].span, &stack[0].query);
303             let mut err = struct_span_err!(self.sess,
304                                            span,
305                                            E0391,
306                                            "cycle detected when {}",
307                                            stack[0].query.describe(self));
308
309             for i in 1..stack.len() {
310                 let query = &stack[i].query;
311                 let span = fix_span(stack[(i + 1) % stack.len()].span, query);
312                 err.span_note(span, &format!("...which requires {}...", query.describe(self)));
313             }
314
315             err.note(&format!("...which again requires {}, completing the cycle",
316                               stack[0].query.describe(self)));
317
318             if let Some((span, query)) = usage {
319                 err.span_note(fix_span(span, &query),
320                               &format!("cycle used when {}", query.describe(self)));
321             }
322
323             err
324         })
325     }
326
327     pub fn try_print_query_stack() {
328         eprintln!("query stack during panic:");
329
330         tls::with_context_opt(|icx| {
331             if let Some(icx) = icx {
332                 let mut current_query = icx.query.clone();
333                 let mut i = 0;
334
335                 while let Some(query) = current_query {
336                     let mut db = DiagnosticBuilder::new(icx.tcx.sess.diagnostic(),
337                         Level::FailureNote,
338                         &format!("#{} [{}] {}",
339                                  i,
340                                  query.info.query.name(),
341                                  query.info.query.describe(icx.tcx)));
342                     db.set_span(icx.tcx.sess.source_map().def_span(query.info.span));
343                     icx.tcx.sess.diagnostic().force_print_db(db);
344
345                     current_query = query.parent.clone();
346                     i += 1;
347                 }
348             }
349         });
350
351         eprintln!("end of query stack");
352     }
353
354     #[inline(never)]
355     pub(super) fn get_query<Q: QueryDescription<'gcx>>(
356         self,
357         span: Span,
358         key: Q::Key)
359     -> Q::Value {
360         debug!("ty::query::get_query<{}>(key={:?}, span={:?})",
361                Q::NAME.as_str(),
362                key,
363                span);
364
365         profq_msg!(self,
366             ProfileQueriesMsg::QueryBegin(
367                 span.data(),
368                 profq_query_msg!(Q::NAME.as_str(), self, key),
369             )
370         );
371
372         let job = match JobOwner::try_get(self, span, &key) {
373             TryGetJob::NotYetStarted(job) => job,
374             TryGetJob::Cycle(result) => return result,
375             TryGetJob::JobCompleted((v, index)) => {
376                 self.dep_graph.read_index(index);
377                 return v
378             }
379         };
380
381         // Fast path for when incr. comp. is off. `to_dep_node` is
382         // expensive for some DepKinds.
383         if !self.dep_graph.is_fully_enabled() {
384             let null_dep_node = DepNode::new_no_params(crate::dep_graph::DepKind::Null);
385             return self.force_query_with_job::<Q>(key, job, null_dep_node).0;
386         }
387
388         let dep_node = Q::to_dep_node(self, &key);
389
390         if dep_node.kind.is_anon() {
391             profq_msg!(self, ProfileQueriesMsg::ProviderBegin);
392             self.sess.profiler(|p| p.start_query(Q::NAME));
393
394             let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
395                 self.start_query(job.job.clone(), diagnostics, |tcx| {
396                     tcx.dep_graph.with_anon_task(dep_node.kind, || {
397                         Q::compute(tcx.global_tcx(), key)
398                     })
399                 })
400             });
401
402             self.sess.profiler(|p| p.end_query(Q::NAME));
403             profq_msg!(self, ProfileQueriesMsg::ProviderEnd);
404
405             self.dep_graph.read_index(dep_node_index);
406
407             if unlikely!(!diagnostics.is_empty()) {
408                 self.queries.on_disk_cache
409                     .store_diagnostics_for_anon_node(dep_node_index, diagnostics);
410             }
411
412             job.complete(&result, dep_node_index);
413
414             return result;
415         }
416
417         if !dep_node.kind.is_eval_always() {
418             // The diagnostics for this query will be
419             // promoted to the current session during
420             // try_mark_green(), so we can ignore them here.
421             let loaded = self.start_query(job.job.clone(), None, |tcx| {
422                 let marked = tcx.dep_graph.try_mark_green_and_read(tcx, &dep_node);
423                 marked.map(|(prev_dep_node_index, dep_node_index)| {
424                     (tcx.load_from_disk_and_cache_in_memory::<Q>(
425                         key.clone(),
426                         prev_dep_node_index,
427                         dep_node_index,
428                         &dep_node
429                     ), dep_node_index)
430                 })
431             });
432             if let Some((result, dep_node_index)) = loaded {
433                 job.complete(&result, dep_node_index);
434                 return result;
435             }
436         }
437
438         let (result, dep_node_index) = self.force_query_with_job::<Q>(key, job, dep_node);
439         self.dep_graph.read_index(dep_node_index);
440         result
441     }
442
443     fn load_from_disk_and_cache_in_memory<Q: QueryDescription<'gcx>>(
444         self,
445         key: Q::Key,
446         prev_dep_node_index: SerializedDepNodeIndex,
447         dep_node_index: DepNodeIndex,
448         dep_node: &DepNode
449     ) -> Q::Value
450     {
451         // Note this function can be called concurrently from the same query
452         // We must ensure that this is handled correctly
453
454         debug_assert!(self.dep_graph.is_green(dep_node));
455
456         // First we try to load the result from the on-disk cache
457         let result = if Q::cache_on_disk(self.global_tcx(), key.clone()) &&
458                         self.sess.opts.debugging_opts.incremental_queries {
459             self.sess.profiler(|p| p.incremental_load_result_start(Q::NAME));
460             let result = Q::try_load_from_disk(self.global_tcx(), prev_dep_node_index);
461             self.sess.profiler(|p| p.incremental_load_result_end(Q::NAME));
462
463             // We always expect to find a cached result for things that
464             // can be forced from DepNode.
465             debug_assert!(!dep_node.kind.can_reconstruct_query_key() ||
466                           result.is_some(),
467                           "Missing on-disk cache entry for {:?}",
468                           dep_node);
469             result
470         } else {
471             // Some things are never cached on disk.
472             None
473         };
474
475         let result = if let Some(result) = result {
476             profq_msg!(self, ProfileQueriesMsg::CacheHit);
477             self.sess.profiler(|p| p.record_query_hit(Q::NAME));
478
479             result
480         } else {
481             // We could not load a result from the on-disk cache, so
482             // recompute.
483
484             self.sess.profiler(|p| p.start_query(Q::NAME));
485
486             // The dep-graph for this computation is already in
487             // place
488             let result = self.dep_graph.with_ignore(|| {
489                 Q::compute(self, key)
490             });
491
492             self.sess.profiler(|p| p.end_query(Q::NAME));
493             result
494         };
495
496         // If -Zincremental-verify-ich is specified, re-hash results from
497         // the cache and make sure that they have the expected fingerprint.
498         if unlikely!(self.sess.opts.debugging_opts.incremental_verify_ich) {
499             self.incremental_verify_ich::<Q>(&result, dep_node, dep_node_index);
500         }
501
502         if unlikely!(self.sess.opts.debugging_opts.query_dep_graph) {
503             self.dep_graph.mark_loaded_from_cache(dep_node_index, true);
504         }
505
506         result
507     }
508
509     #[inline(never)]
510     #[cold]
511     fn incremental_verify_ich<Q: QueryDescription<'gcx>>(
512         self,
513         result: &Q::Value,
514         dep_node: &DepNode,
515         dep_node_index: DepNodeIndex,
516     ) {
517         use crate::ich::Fingerprint;
518
519         assert!(Some(self.dep_graph.fingerprint_of(dep_node_index)) ==
520                 self.dep_graph.prev_fingerprint_of(dep_node),
521                 "Fingerprint for green query instance not loaded \
522                     from cache: {:?}", dep_node);
523
524         debug!("BEGIN verify_ich({:?})", dep_node);
525         let mut hcx = self.create_stable_hashing_context();
526
527         let new_hash = Q::hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
528         debug!("END verify_ich({:?})", dep_node);
529
530         let old_hash = self.dep_graph.fingerprint_of(dep_node_index);
531
532         assert!(new_hash == old_hash, "Found unstable fingerprints \
533             for {:?}", dep_node);
534     }
535
536     #[inline(always)]
537     fn force_query_with_job<Q: QueryDescription<'gcx>>(
538         self,
539         key: Q::Key,
540         job: JobOwner<'_, 'gcx, Q>,
541         dep_node: DepNode)
542     -> (Q::Value, DepNodeIndex) {
543         // If the following assertion triggers, it can have two reasons:
544         // 1. Something is wrong with DepNode creation, either here or
545         //    in DepGraph::try_mark_green()
546         // 2. Two distinct query keys get mapped to the same DepNode
547         //    (see for example #48923)
548         assert!(!self.dep_graph.dep_node_exists(&dep_node),
549                 "Forcing query with already existing DepNode.\n\
550                  - query-key: {:?}\n\
551                  - dep-node: {:?}",
552                 key, dep_node);
553
554         profq_msg!(self, ProfileQueriesMsg::ProviderBegin);
555         self.sess.profiler(|p| p.start_query(Q::NAME));
556
557         let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
558             self.start_query(job.job.clone(), diagnostics, |tcx| {
559                 if dep_node.kind.is_eval_always() {
560                     tcx.dep_graph.with_eval_always_task(dep_node,
561                                                         tcx,
562                                                         key,
563                                                         Q::compute,
564                                                         Q::hash_result)
565                 } else {
566                     tcx.dep_graph.with_task(dep_node,
567                                             tcx,
568                                             key,
569                                             Q::compute,
570                                             Q::hash_result)
571                 }
572             })
573         });
574
575         self.sess.profiler(|p| p.end_query(Q::NAME));
576         profq_msg!(self, ProfileQueriesMsg::ProviderEnd);
577
578         if unlikely!(self.sess.opts.debugging_opts.query_dep_graph) {
579             self.dep_graph.mark_loaded_from_cache(dep_node_index, false);
580         }
581
582         if dep_node.kind != crate::dep_graph::DepKind::Null {
583             if unlikely!(!diagnostics.is_empty()) {
584                 self.queries.on_disk_cache
585                     .store_diagnostics(dep_node_index, diagnostics);
586             }
587         }
588
589         job.complete(&result, dep_node_index);
590
591         (result, dep_node_index)
592     }
593
594     /// Ensure that either this query has all green inputs or been executed.
595     /// Executing query::ensure(D) is considered a read of the dep-node D.
596     ///
597     /// This function is particularly useful when executing passes for their
598     /// side-effects -- e.g., in order to report errors for erroneous programs.
599     ///
600     /// Note: The optimization is only available during incr. comp.
601     pub(super) fn ensure_query<Q: QueryDescription<'gcx>>(self, key: Q::Key) -> () {
602         let dep_node = Q::to_dep_node(self, &key);
603
604         if dep_node.kind.is_eval_always() {
605             let _ = self.get_query::<Q>(DUMMY_SP, key);
606             return;
607         }
608
609         // Ensuring an anonymous query makes no sense
610         assert!(!dep_node.kind.is_anon());
611         if self.dep_graph.try_mark_green_and_read(self, &dep_node).is_none() {
612             // A None return from `try_mark_green_and_read` means that this is either
613             // a new dep node or that the dep node has already been marked red.
614             // Either way, we can't call `dep_graph.read()` as we don't have the
615             // DepNodeIndex. We must invoke the query itself. The performance cost
616             // this introduces should be negligible as we'll immediately hit the
617             // in-memory cache, or another query down the line will.
618
619             let _ = self.get_query::<Q>(DUMMY_SP, key);
620         } else {
621             profq_msg!(self, ProfileQueriesMsg::CacheHit);
622             self.sess.profiler(|p| p.record_query_hit(Q::NAME));
623         }
624     }
625
626     #[allow(dead_code)]
627     fn force_query<Q: QueryDescription<'gcx>>(
628         self,
629         key: Q::Key,
630         span: Span,
631         dep_node: DepNode
632     ) {
633         profq_msg!(
634             self,
635             ProfileQueriesMsg::QueryBegin(span.data(),
636                                           profq_query_msg!(Q::NAME.as_str(), self, key))
637         );
638
639         // We may be concurrently trying both execute and force a query.
640         // Ensure that only one of them runs the query.
641         let job = match JobOwner::try_get(self, span, &key) {
642             TryGetJob::NotYetStarted(job) => job,
643             TryGetJob::Cycle(_) |
644             TryGetJob::JobCompleted(_) => {
645                 return
646             }
647         };
648         self.force_query_with_job::<Q>(key, job, dep_node);
649     }
650 }
651
652 macro_rules! handle_cycle_error {
653     ([][$tcx: expr, $error:expr]) => {{
654         $tcx.report_cycle($error).emit();
655         Value::from_cycle_error($tcx.global_tcx())
656     }};
657     ([fatal_cycle$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
658         $tcx.report_cycle($error).emit();
659         $tcx.sess.abort_if_errors();
660         unreachable!()
661     }};
662     ([cycle_delay_bug$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
663         $tcx.report_cycle($error).delay_as_bug();
664         Value::from_cycle_error($tcx.global_tcx())
665     }};
666     ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
667         handle_cycle_error!([$($modifiers),*][$($args)*])
668     };
669 }
670
671 macro_rules! hash_result {
672     ([][$hcx:expr, $result:expr]) => {{
673         dep_graph::hash_result($hcx, &$result)
674     }};
675     ([no_hash$(, $modifiers:ident)*][$hcx:expr, $result:expr]) => {{
676         None
677     }};
678     ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
679         hash_result!([$($modifiers),*][$($args)*])
680     };
681 }
682
683 macro_rules! define_queries {
684     (<$tcx:tt> $($category:tt {
685         $($(#[$attr:meta])* [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*
686     },)*) => {
687         define_queries_inner! { <$tcx>
688             $($( $(#[$attr])* category<$category> [$($modifiers)*] fn $name: $node($K) -> $V,)*)*
689         }
690     }
691 }
692
693 macro_rules! define_queries_inner {
694     (<$tcx:tt>
695      $($(#[$attr:meta])* category<$category:tt>
696         [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
697
698         use std::mem;
699         #[cfg(parallel_compiler)]
700         use ty::query::job::QueryResult;
701         use rustc_data_structures::sync::Lock;
702         use crate::{
703             rustc_data_structures::stable_hasher::HashStable,
704             rustc_data_structures::stable_hasher::StableHasherResult,
705             rustc_data_structures::stable_hasher::StableHasher,
706             ich::StableHashingContext
707         };
708         use crate::util::profiling::ProfileCategory;
709
710         define_queries_struct! {
711             tcx: $tcx,
712             input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
713         }
714
715         impl<$tcx> Queries<$tcx> {
716             pub fn new(
717                 providers: IndexVec<CrateNum, Providers<$tcx>>,
718                 fallback_extern_providers: Providers<$tcx>,
719                 on_disk_cache: OnDiskCache<'tcx>,
720             ) -> Self {
721                 Queries {
722                     providers,
723                     fallback_extern_providers: Box::new(fallback_extern_providers),
724                     on_disk_cache,
725                     $($name: Default::default()),*
726                 }
727             }
728
729             #[cfg(parallel_compiler)]
730             pub fn collect_active_jobs(&self) -> Vec<Lrc<QueryJob<$tcx>>> {
731                 let mut jobs = Vec::new();
732
733                 // We use try_lock here since we are only called from the
734                 // deadlock handler, and this shouldn't be locked.
735                 $(
736                     jobs.extend(
737                         self.$name.try_lock().unwrap().active.values().filter_map(|v|
738                             if let QueryResult::Started(ref job) = *v {
739                                 Some(job.clone())
740                             } else {
741                                 None
742                             }
743                         )
744                     );
745                 )*
746
747                 jobs
748             }
749
750             pub fn print_stats(&self) {
751                 let mut queries = Vec::new();
752
753                 #[derive(Clone)]
754                 struct QueryStats {
755                     name: &'static str,
756                     cache_hits: usize,
757                     key_size: usize,
758                     key_type: &'static str,
759                     value_size: usize,
760                     value_type: &'static str,
761                     entry_count: usize,
762                 }
763
764                 fn stats<'tcx, Q: QueryConfig<'tcx>>(
765                     name: &'static str,
766                     map: &QueryCache<'tcx, Q>
767                 ) -> QueryStats {
768                     QueryStats {
769                         name,
770                         #[cfg(debug_assertions)]
771                         cache_hits: map.cache_hits,
772                         #[cfg(not(debug_assertions))]
773                         cache_hits: 0,
774                         key_size: mem::size_of::<Q::Key>(),
775                         key_type: unsafe { type_name::<Q::Key>() },
776                         value_size: mem::size_of::<Q::Value>(),
777                         value_type: unsafe { type_name::<Q::Value>() },
778                         entry_count: map.results.len(),
779                     }
780                 }
781
782                 $(
783                     queries.push(stats::<queries::$name<'_>>(
784                         stringify!($name),
785                         &*self.$name.lock()
786                     ));
787                 )*
788
789                 if cfg!(debug_assertions) {
790                     let hits: usize = queries.iter().map(|s| s.cache_hits).sum();
791                     let results: usize = queries.iter().map(|s| s.entry_count).sum();
792                     println!("\nQuery cache hit rate: {}", hits as f64 / (hits + results) as f64);
793                 }
794
795                 let mut query_key_sizes = queries.clone();
796                 query_key_sizes.sort_by_key(|q| q.key_size);
797                 println!("\nLarge query keys:");
798                 for q in query_key_sizes.iter().rev()
799                                         .filter(|q| q.key_size > 8) {
800                     println!(
801                         "   {} - {} x {} - {}",
802                         q.name,
803                         q.key_size,
804                         q.entry_count,
805                         q.key_type
806                     );
807                 }
808
809                 let mut query_value_sizes = queries.clone();
810                 query_value_sizes.sort_by_key(|q| q.value_size);
811                 println!("\nLarge query values:");
812                 for q in query_value_sizes.iter().rev()
813                                           .filter(|q| q.value_size > 8) {
814                     println!(
815                         "   {} - {} x {} - {}",
816                         q.name,
817                         q.value_size,
818                         q.entry_count,
819                         q.value_type
820                     );
821                 }
822
823                 if cfg!(debug_assertions) {
824                     let mut query_cache_hits = queries.clone();
825                     query_cache_hits.sort_by_key(|q| q.cache_hits);
826                     println!("\nQuery cache hits:");
827                     for q in query_cache_hits.iter().rev() {
828                         println!(
829                             "   {} - {} ({}%)",
830                             q.name,
831                             q.cache_hits,
832                             q.cache_hits as f64 / (q.cache_hits + q.entry_count) as f64
833                         );
834                     }
835                 }
836
837                 let mut query_value_count = queries.clone();
838                 query_value_count.sort_by_key(|q| q.entry_count);
839                 println!("\nQuery value count:");
840                 for q in query_value_count.iter().rev() {
841                     println!("   {} - {}", q.name, q.entry_count);
842                 }
843             }
844         }
845
846         #[allow(nonstandard_style)]
847         #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
848         pub enum QueryName {
849             $($name),*
850         }
851
852         impl QueryName {
853             pub fn register_with_profiler(profiler: &crate::util::profiling::SelfProfiler) {
854                 $(profiler.register_query_name(QueryName::$name);)*
855             }
856
857             pub fn as_str(&self) -> &'static str {
858                 match self {
859                     $(QueryName::$name => stringify!($name),)*
860                 }
861             }
862         }
863
864         #[allow(nonstandard_style)]
865         #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
866         pub enum Query<$tcx> {
867             $($(#[$attr])* $name($K)),*
868         }
869
870         impl<$tcx> Query<$tcx> {
871             pub fn name(&self) -> &'static str {
872                 match *self {
873                     $(Query::$name(_) => stringify!($name),)*
874                 }
875             }
876
877             pub fn describe(&self, tcx: TyCtxt<'_, '_, '_>) -> Cow<'static, str> {
878                 let (r, name) = match *self {
879                     $(Query::$name(key) => {
880                         (queries::$name::describe(tcx, key), stringify!($name))
881                     })*
882                 };
883                 if tcx.sess.verbose() {
884                     format!("{} [{}]", r, name).into()
885                 } else {
886                     r
887                 }
888             }
889
890             // FIXME(eddyb) Get more valid Span's on queries.
891             pub fn default_span(&self, tcx: TyCtxt<'_, $tcx, '_>, span: Span) -> Span {
892                 if !span.is_dummy() {
893                     return span;
894                 }
895                 // The def_span query is used to calculate default_span,
896                 // so exit to avoid infinite recursion
897                 if let Query::def_span(..) = *self {
898                     return span
899                 }
900                 match *self {
901                     $(Query::$name(key) => key.default_span(tcx),)*
902                 }
903             }
904
905             pub fn query_name(&self) -> QueryName {
906                 match self {
907                     $(Query::$name(_) => QueryName::$name,)*
908                 }
909             }
910         }
911
912         impl<'a, $tcx> HashStable<StableHashingContext<'a>> for Query<$tcx> {
913             fn hash_stable<W: StableHasherResult>(&self,
914                                                 hcx: &mut StableHashingContext<'a>,
915                                                 hasher: &mut StableHasher<W>) {
916                 mem::discriminant(self).hash_stable(hcx, hasher);
917                 match *self {
918                     $(Query::$name(key) => key.hash_stable(hcx, hasher),)*
919                 }
920             }
921         }
922
923         pub mod queries {
924             use std::marker::PhantomData;
925
926             $(#[allow(nonstandard_style)]
927             pub struct $name<$tcx> {
928                 data: PhantomData<&$tcx ()>
929             })*
930         }
931
932         // This module and the functions in it exist only to provide a
933         // predictable symbol name prefix for query providers. This is helpful
934         // for analyzing queries in profilers.
935         pub(super) mod __query_compute {
936             $(#[inline(never)]
937             pub fn $name<F: FnOnce() -> R, R>(f: F) -> R {
938                 f()
939             })*
940         }
941
942         $(impl<$tcx> QueryConfig<$tcx> for queries::$name<$tcx> {
943             type Key = $K;
944             type Value = $V;
945
946             const NAME: QueryName = QueryName::$name;
947             const CATEGORY: ProfileCategory = $category;
948         }
949
950         impl<$tcx> QueryAccessors<$tcx> for queries::$name<$tcx> {
951             #[inline(always)]
952             fn query(key: Self::Key) -> Query<'tcx> {
953                 Query::$name(key)
954             }
955
956             #[inline(always)]
957             fn query_cache<'a>(tcx: TyCtxt<'a, $tcx, '_>) -> &'a Lock<QueryCache<$tcx, Self>> {
958                 &tcx.queries.$name
959             }
960
961             #[allow(unused)]
962             #[inline(always)]
963             fn to_dep_node(tcx: TyCtxt<'_, $tcx, '_>, key: &Self::Key) -> DepNode {
964                 use crate::dep_graph::DepConstructor::*;
965
966                 DepNode::new(tcx, $node(*key))
967             }
968
969             #[inline]
970             fn compute(tcx: TyCtxt<'_, 'tcx, '_>, key: Self::Key) -> Self::Value {
971                 __query_compute::$name(move || {
972                     let provider = tcx.queries.providers.get(key.query_crate())
973                         // HACK(eddyb) it's possible crates may be loaded after
974                         // the query engine is created, and because crate loading
975                         // is not yet integrated with the query engine, such crates
976                         // would be missing appropriate entries in `providers`.
977                         .unwrap_or(&tcx.queries.fallback_extern_providers)
978                         .$name;
979                     provider(tcx.global_tcx(), key)
980                 })
981             }
982
983             fn hash_result(
984                 _hcx: &mut StableHashingContext<'_>,
985                 _result: &Self::Value
986             ) -> Option<Fingerprint> {
987                 hash_result!([$($modifiers)*][_hcx, _result])
988             }
989
990             fn handle_cycle_error(
991                 tcx: TyCtxt<'_, 'tcx, '_>,
992                 error: CycleError<'tcx>
993             ) -> Self::Value {
994                 handle_cycle_error!([$($modifiers)*][tcx, error])
995             }
996         })*
997
998         #[derive(Copy, Clone)]
999         pub struct TyCtxtEnsure<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
1000             pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
1001         }
1002
1003         impl<'a, $tcx, 'lcx> TyCtxtEnsure<'a, $tcx, 'lcx> {
1004             $($(#[$attr])*
1005             #[inline(always)]
1006             pub fn $name(self, key: $K) {
1007                 self.tcx.ensure_query::<queries::$name<'_>>(key)
1008             })*
1009         }
1010
1011         #[derive(Copy, Clone)]
1012         pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
1013             pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
1014             pub span: Span,
1015         }
1016
1017         impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
1018             type Target = TyCtxt<'a, 'gcx, 'tcx>;
1019             #[inline(always)]
1020             fn deref(&self) -> &Self::Target {
1021                 &self.tcx
1022             }
1023         }
1024
1025         impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
1026             /// Returns a transparent wrapper for `TyCtxt`, which ensures queries
1027             /// are executed instead of just returing their results.
1028             #[inline(always)]
1029             pub fn ensure(self) -> TyCtxtEnsure<'a, $tcx, 'lcx> {
1030                 TyCtxtEnsure {
1031                     tcx: self,
1032                 }
1033             }
1034
1035             /// Returns a transparent wrapper for `TyCtxt` which uses
1036             /// `span` as the location of queries performed through it.
1037             #[inline(always)]
1038             pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
1039                 TyCtxtAt {
1040                     tcx: self,
1041                     span
1042                 }
1043             }
1044
1045             $($(#[$attr])*
1046             #[inline(always)]
1047             pub fn $name(self, key: $K) -> $V {
1048                 self.at(DUMMY_SP).$name(key)
1049             })*
1050         }
1051
1052         impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
1053             $($(#[$attr])*
1054             #[inline(always)]
1055             pub fn $name(self, key: $K) -> $V {
1056                 self.tcx.get_query::<queries::$name<'_>>(self.span, key)
1057             })*
1058         }
1059
1060         define_provider_struct! {
1061             tcx: $tcx,
1062             input: ($(([$($modifiers)*] [$name] [$K] [$V]))*)
1063         }
1064
1065         impl<$tcx> Copy for Providers<$tcx> {}
1066         impl<$tcx> Clone for Providers<$tcx> {
1067             fn clone(&self) -> Self { *self }
1068         }
1069     }
1070 }
1071
1072 macro_rules! define_queries_struct {
1073     (tcx: $tcx:tt,
1074      input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
1075         pub struct Queries<$tcx> {
1076             /// This provides access to the incrimental comilation on-disk cache for query results.
1077             /// Do not access this directly. It is only meant to be used by
1078             /// `DepGraph::try_mark_green()` and the query infrastructure.
1079             pub(crate) on_disk_cache: OnDiskCache<'tcx>,
1080
1081             providers: IndexVec<CrateNum, Providers<$tcx>>,
1082             fallback_extern_providers: Box<Providers<$tcx>>,
1083
1084             $($(#[$attr])*  $name: Lock<QueryCache<$tcx, queries::$name<$tcx>>>,)*
1085         }
1086     };
1087 }
1088
1089 macro_rules! define_provider_struct {
1090     (tcx: $tcx:tt,
1091      input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
1092         pub struct Providers<$tcx> {
1093             $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
1094         }
1095
1096         impl<$tcx> Default for Providers<$tcx> {
1097             fn default() -> Self {
1098                 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
1099                     bug!("tcx.{}({:?}) unsupported by its crate",
1100                          stringify!($name), key);
1101                 })*
1102                 Providers { $($name),* }
1103             }
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>(
1152     tcx: TyCtxt<'_, 'tcx, 'tcx>,
1153     dep_node: &DepNode
1154 ) -> bool {
1155     use crate::dep_graph::RecoverKey;
1156
1157     // We must avoid ever having to call force_from_dep_node() for a
1158     // DepNode::codegen_unit:
1159     // Since we cannot reconstruct the query key of a DepNode::codegen_unit, we
1160     // would always end up having to evaluate the first caller of the
1161     // `codegen_unit` query that *is* reconstructible. This might very well be
1162     // the `compile_codegen_unit` query, thus re-codegenning the whole CGU just
1163     // to re-trigger calling the `codegen_unit` query with the right key. At
1164     // that point we would already have re-done all the work we are trying to
1165     // avoid doing in the first place.
1166     // The solution is simple: Just explicitly call the `codegen_unit` query for
1167     // each CGU, right after partitioning. This way `try_mark_green` will always
1168     // hit the cache instead of having to go through `force_from_dep_node`.
1169     // This assertion makes sure, we actually keep applying the solution above.
1170     debug_assert!(dep_node.kind != DepKind::codegen_unit,
1171                   "calling force_from_dep_node() on DepKind::codegen_unit");
1172
1173     if !dep_node.kind.can_reconstruct_query_key() {
1174         return false
1175     }
1176
1177     macro_rules! def_id {
1178         () => {
1179             if let Some(def_id) = dep_node.extract_def_id(tcx) {
1180                 def_id
1181             } else {
1182                 // return from the whole function
1183                 return false
1184             }
1185         }
1186     };
1187
1188     macro_rules! krate {
1189         () => { (def_id!()).krate }
1190     };
1191
1192     macro_rules! force_ex {
1193         ($tcx:expr, $query:ident, $key:expr) => {
1194             {
1195                 $tcx.force_query::<crate::ty::query::queries::$query<'_>>(
1196                     $key,
1197                     DUMMY_SP,
1198                     *dep_node
1199                 );
1200             }
1201         }
1202     };
1203
1204     macro_rules! force {
1205         ($query:ident, $key:expr) => { force_ex!(tcx, $query, $key) }
1206     };
1207
1208     rustc_dep_node_force!([dep_node, tcx]
1209         // These are inputs that are expected to be pre-allocated and that
1210         // should therefore always be red or green already
1211         DepKind::AllLocalTraitImpls |
1212         DepKind::Krate |
1213         DepKind::CrateMetadata |
1214         DepKind::HirBody |
1215         DepKind::Hir |
1216
1217         // This are anonymous nodes
1218         DepKind::TraitSelect |
1219
1220         // We don't have enough information to reconstruct the query key of
1221         // these
1222         DepKind::CompileCodegenUnit => {
1223             bug!("force_from_dep_node() - Encountered {:?}", dep_node)
1224         }
1225
1226         DepKind::Analysis => { force!(analysis, krate!()); }
1227     );
1228
1229     true
1230 }
1231
1232
1233 // FIXME(#45015): Another piece of boilerplate code that could be generated in
1234 //                a combined define_dep_nodes!()/define_queries!() macro.
1235 macro_rules! impl_load_from_cache {
1236     ($($dep_kind:ident => $query_name:ident,)*) => {
1237         impl DepNode {
1238             // Check whether the query invocation corresponding to the given
1239             // DepNode is eligible for on-disk-caching.
1240             pub fn cache_on_disk(&self, tcx: TyCtxt<'_, '_, '_>) -> bool {
1241                 use crate::ty::query::queries;
1242                 use crate::ty::query::QueryDescription;
1243
1244                 match self.kind {
1245                     $(DepKind::$dep_kind => {
1246                         let def_id = self.extract_def_id(tcx).unwrap();
1247                         queries::$query_name::cache_on_disk(tcx.global_tcx(), def_id)
1248                     })*
1249                     _ => false
1250                 }
1251             }
1252
1253             // This is method will execute the query corresponding to the given
1254             // DepNode. It is only expected to work for DepNodes where the
1255             // above `cache_on_disk` methods returns true.
1256             // Also, as a sanity check, it expects that the corresponding query
1257             // invocation has been marked as green already.
1258             pub fn load_from_on_disk_cache(&self, tcx: TyCtxt<'_, '_, '_>) {
1259                 match self.kind {
1260                     $(DepKind::$dep_kind => {
1261                         debug_assert!(tcx.dep_graph
1262                                          .node_color(self)
1263                                          .map(|c| c.is_green())
1264                                          .unwrap_or(false));
1265
1266                         let def_id = self.extract_def_id(tcx).unwrap();
1267                         let _ = tcx.$query_name(def_id);
1268                     })*
1269                     _ => {
1270                         bug!()
1271                     }
1272                 }
1273             }
1274         }
1275     }
1276 }
1277
1278 impl_load_from_cache!(
1279     typeck_tables_of => typeck_tables_of,
1280     optimized_mir => optimized_mir,
1281     unsafety_check_result => unsafety_check_result,
1282     borrowck => borrowck,
1283     mir_borrowck => mir_borrowck,
1284     mir_const_qualif => mir_const_qualif,
1285     const_is_rvalue_promotable_to_static => const_is_rvalue_promotable_to_static,
1286     check_match => check_match,
1287     type_of => type_of,
1288     generics_of => generics_of,
1289     predicates_of => predicates_of,
1290     used_trait_imports => used_trait_imports,
1291     codegen_fn_attrs => codegen_fn_attrs,
1292     specialization_graph_of => specialization_graph_of,
1293 );