]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/maps/plumbing.rs
c3f3424600ca9e4be3302e3c8728e0e866df9f85
[rust.git] / src / librustc / ty / maps / plumbing.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The implementation of the query system itself. Defines the macros
12 //! that generate the actual methods on tcx which find and execute the
13 //! provider, manage the caches, and so forth.
14
15 use dep_graph::{DepNodeIndex, DepNode, DepKind, DepNodeColor};
16 use errors::DiagnosticBuilder;
17 use errors::Level;
18 use errors::Diagnostic;
19 use errors::FatalError;
20 use ty::tls;
21 use ty::{TyCtxt};
22 use ty::maps::Query;
23 use ty::maps::config::QueryConfig;
24 use ty::maps::config::QueryDescription;
25 use ty::maps::job::{QueryJob, QueryResult, QueryInfo};
26 use ty::item_path;
27
28 use util::common::{profq_msg, ProfileQueriesMsg, QueryMsg};
29
30 use rustc_data_structures::fx::{FxHashMap};
31 use rustc_data_structures::sync::{Lrc, Lock};
32 use std::mem;
33 use std::ptr;
34 use std::collections::hash_map::Entry;
35 use syntax_pos::Span;
36 use syntax::codemap::DUMMY_SP;
37
38 pub struct QueryMap<'tcx, D: QueryConfig<'tcx> + ?Sized> {
39     pub(super) map: FxHashMap<D::Key, QueryResult<'tcx, QueryValue<D::Value>>>,
40 }
41
42 pub(super) struct QueryValue<T> {
43     pub(super) value: T,
44     pub(super) index: DepNodeIndex,
45 }
46
47 impl<T> QueryValue<T> {
48     pub(super) fn new(value: T,
49                       dep_node_index: DepNodeIndex)
50                       -> QueryValue<T> {
51         QueryValue {
52             value,
53             index: dep_node_index,
54         }
55     }
56 }
57
58 impl<'tcx, M: QueryConfig<'tcx>> QueryMap<'tcx, M> {
59     pub(super) fn new() -> QueryMap<'tcx, M> {
60         QueryMap {
61             map: FxHashMap(),
62         }
63     }
64 }
65
66 // If enabled, send a message to the profile-queries thread
67 macro_rules! profq_msg {
68     ($tcx:expr, $msg:expr) => {
69         if cfg!(debug_assertions) {
70             if $tcx.sess.profile_queries() {
71                 profq_msg($tcx.sess, $msg)
72             }
73         }
74     }
75 }
76
77 // If enabled, format a key using its debug string, which can be
78 // expensive to compute (in terms of time).
79 macro_rules! profq_query_msg {
80     ($query:expr, $tcx:expr, $key:expr) => {{
81         let msg = if cfg!(debug_assertions) {
82             if $tcx.sess.profile_queries_and_keys() {
83                 Some(format!("{:?}", $key))
84             } else { None }
85         } else { None };
86         QueryMsg {
87             query: $query,
88             msg,
89         }
90     }}
91 }
92
93 /// A type representing the responsibility to execute the job in the `job` field.
94 /// This will poison the relevant query if dropped.
95 pub(super) struct JobOwner<'a, 'tcx: 'a, Q: QueryDescription<'tcx> + 'a> {
96     map: &'a Lock<QueryMap<'tcx, Q>>,
97     key: Q::Key,
98     job: Lrc<QueryJob<'tcx>>,
99 }
100
101 impl<'a, 'tcx, Q: QueryDescription<'tcx>> JobOwner<'a, 'tcx, Q> {
102     /// Either gets a JobOwner corresponding the the query, allowing us to
103     /// start executing the query, or it returns with the result of the query.
104     /// If the query is executing elsewhere, this will wait for it.
105     /// If the query panicked, this will silently panic.
106     pub(super) fn try_get(
107         tcx: TyCtxt<'a, 'tcx, '_>,
108         span: Span,
109         key: &Q::Key,
110     ) -> TryGetJob<'a, 'tcx, Q> {
111         let map = Q::query_map(tcx);
112         loop {
113             let mut lock = map.borrow_mut();
114             let job = match lock.map.entry((*key).clone()) {
115                 Entry::Occupied(entry) => {
116                     match *entry.get() {
117                         QueryResult::Started(ref job) => job.clone(),
118                         QueryResult::Complete(ref value) => {
119                             profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
120                             let result = Ok((value.value.clone(), value.index));
121                             return TryGetJob::JobCompleted(result);
122                         },
123                         QueryResult::Poisoned => FatalError.raise(),
124                     }
125                 }
126                 Entry::Vacant(entry) => {
127                     // No job entry for this query. Return a new one to be started later
128                     return tls::with_related_context(tcx, |icx| {
129                         let info = QueryInfo {
130                             span,
131                             query: Q::query(key.clone()),
132                         };
133                         let job = Lrc::new(QueryJob::new(info, icx.query.clone()));
134                         let owner = JobOwner {
135                             map,
136                             job: job.clone(),
137                             key: (*key).clone(),
138                         };
139                         entry.insert(QueryResult::Started(job));
140                         TryGetJob::NotYetStarted(owner)
141                     })
142                 }
143             };
144             mem::drop(lock);
145
146             if let Err(cycle) = job.await(tcx, span) {
147                 return TryGetJob::JobCompleted(Err(cycle));
148             }
149         }
150     }
151
152     /// Completes the query by updating the query map with the `result`,
153     /// signals the waiter and forgets the JobOwner, so it won't poison the query
154     pub(super) fn complete(self, result: &Q::Value, dep_node_index: DepNodeIndex) {
155         // We can move out of `self` here because we `mem::forget` it below
156         let key = unsafe { ptr::read(&self.key) };
157         let job = unsafe { ptr::read(&self.job) };
158         let map = self.map;
159
160         // Forget ourself so our destructor won't poison the query
161         mem::forget(self);
162
163         let value = QueryValue::new(result.clone(), dep_node_index);
164         map.borrow_mut().map.insert(key, QueryResult::Complete(value));
165
166         job.signal_complete();
167     }
168
169     /// Executes a job by changing the ImplicitCtxt to point to the
170     /// new query job while it executes. It returns the diagnostics
171     /// captured during execution and the actual result.
172     pub(super) fn start<'lcx, F, R>(
173         &self,
174         tcx: TyCtxt<'_, 'tcx, 'lcx>,
175         compute: F)
176     -> (R, Vec<Diagnostic>)
177     where
178         F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'lcx>) -> R
179     {
180         // The TyCtxt stored in TLS has the same global interner lifetime
181         // as `tcx`, so we use `with_related_context` to relate the 'gcx lifetimes
182         // when accessing the ImplicitCtxt
183         let r = tls::with_related_context(tcx, move |icx| {
184             // Update the ImplicitCtxt to point to our new query job
185             let icx = tls::ImplicitCtxt {
186                 tcx,
187                 query: Some(self.job.clone()),
188                 layout_depth: icx.layout_depth,
189                 task: icx.task,
190             };
191
192             // Use the ImplicitCtxt while we execute the query
193             tls::enter_context(&icx, |icx| {
194                 compute(icx.tcx)
195             })
196         });
197
198         // Extract the diagnostic from the job
199         let diagnostics = mem::replace(&mut *self.job.diagnostics.lock(), Vec::new());
200
201         (r, diagnostics)
202     }
203 }
204
205 impl<'a, 'tcx, Q: QueryDescription<'tcx>> Drop for JobOwner<'a, 'tcx, Q> {
206     fn drop(&mut self) {
207         // Poison the query so jobs waiting on it panic
208         self.map.borrow_mut().map.insert(self.key.clone(), QueryResult::Poisoned);
209         // Also signal the completion of the job, so waiters
210         // will continue execution
211         self.job.signal_complete();
212     }
213 }
214
215 #[derive(Clone)]
216 pub(super) struct CycleError<'tcx> {
217     /// The query and related span which uses the cycle
218     pub(super) usage: Option<(Span, Query<'tcx>)>,
219     pub(super) cycle: Vec<QueryInfo<'tcx>>,
220 }
221
222 /// The result of `try_get_lock`
223 pub(super) enum TryGetJob<'a, 'tcx: 'a, D: QueryDescription<'tcx> + 'a> {
224     /// The query is not yet started. Contains a guard to the map eventually used to start it.
225     NotYetStarted(JobOwner<'a, 'tcx, D>),
226
227     /// The query was already completed.
228     /// Returns the result of the query and its dep node index
229     /// if it succeeded or a cycle error if it failed
230     JobCompleted(Result<(D::Value, DepNodeIndex), CycleError<'tcx>>),
231 }
232
233 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
234     pub(super) fn report_cycle(self, CycleError { usage, cycle: stack }: CycleError<'gcx>)
235         -> DiagnosticBuilder<'a>
236     {
237         assert!(!stack.is_empty());
238
239         let fix_span = |span: Span, query: &Query<'gcx>| {
240             self.sess.codemap().def_span(query.default_span(self, span))
241         };
242
243         // Disable naming impls with types in this path, since that
244         // sometimes cycles itself, leading to extra cycle errors.
245         // (And cycle errors around impls tend to occur during the
246         // collect/coherence phases anyhow.)
247         item_path::with_forced_impl_filename_line(|| {
248             let span = fix_span(stack[1 % stack.len()].span, &stack[0].query);
249             let mut err = struct_span_err!(self.sess,
250                                            span,
251                                            E0391,
252                                            "cycle detected when {}",
253                                            stack[0].query.describe(self));
254
255             for i in 1..stack.len() {
256                 let query = &stack[i].query;
257                 let span = fix_span(stack[(i + 1) % stack.len()].span, query);
258                 err.span_note(span, &format!("...which requires {}...", query.describe(self)));
259             }
260
261             err.note(&format!("...which again requires {}, completing the cycle",
262                               stack[0].query.describe(self)));
263
264             if let Some((span, query)) = usage {
265                 err.span_note(fix_span(span, &query),
266                               &format!("cycle used when {}", query.describe(self)));
267             }
268
269             return err
270         })
271     }
272
273     pub fn try_print_query_stack() {
274         eprintln!("query stack during panic:");
275
276         tls::with_context_opt(|icx| {
277             if let Some(icx) = icx {
278                 let mut current_query = icx.query.clone();
279                 let mut i = 0;
280
281                 while let Some(query) = current_query {
282                     let mut db = DiagnosticBuilder::new(icx.tcx.sess.diagnostic(),
283                         Level::FailureNote,
284                         &format!("#{} [{}] {}",
285                                  i,
286                                  query.info.query.name(),
287                                  query.info.query.describe(icx.tcx)));
288                     db.set_span(icx.tcx.sess.codemap().def_span(query.info.span));
289                     icx.tcx.sess.diagnostic().force_print_db(db);
290
291                     current_query = query.parent.clone();
292                     i += 1;
293                 }
294             }
295         });
296
297         eprintln!("end of query stack");
298     }
299
300     /// Try to read a node index for the node dep_node.
301     /// A node will have an index, when it's already been marked green, or when we can mark it
302     /// green. This function will mark the current task as a reader of the specified node, when
303     /// the a node index can be found for that node.
304     pub(super) fn try_mark_green_and_read(self, dep_node: &DepNode) -> Option<DepNodeIndex> {
305         match self.dep_graph.node_color(dep_node) {
306             Some(DepNodeColor::Green(dep_node_index)) => {
307                 self.dep_graph.read_index(dep_node_index);
308                 Some(dep_node_index)
309             }
310             Some(DepNodeColor::Red) => {
311                 None
312             }
313             None => {
314                 // try_mark_green (called below) will panic when full incremental
315                 // compilation is disabled. If that's the case, we can't try to mark nodes
316                 // as green anyway, so we can safely return None here.
317                 if !self.dep_graph.is_fully_enabled() {
318                     return None;
319                 }
320                 match self.dep_graph.try_mark_green(self.global_tcx(), &dep_node) {
321                     Some(dep_node_index) => {
322                         debug_assert!(self.dep_graph.is_green(&dep_node));
323                         self.dep_graph.read_index(dep_node_index);
324                         Some(dep_node_index)
325                     }
326                     None => {
327                         None
328                     }
329                 }
330             }
331         }
332     }
333
334     fn try_get_with<Q: QueryDescription<'gcx>>(
335         self,
336         span: Span,
337         key: Q::Key)
338     -> Result<Q::Value, CycleError<'gcx>>
339     {
340         debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
341                Q::NAME,
342                key,
343                span);
344
345         profq_msg!(self,
346             ProfileQueriesMsg::QueryBegin(
347                 span.data(),
348                 profq_query_msg!(Q::NAME, self, key),
349             )
350         );
351
352         let job = match JobOwner::try_get(self, span, &key) {
353             TryGetJob::NotYetStarted(job) => job,
354             TryGetJob::JobCompleted(result) => {
355                 return result.map(|(v, index)| {
356                     self.dep_graph.read_index(index);
357                     v
358                 })
359             }
360         };
361
362         // Fast path for when incr. comp. is off. `to_dep_node` is
363         // expensive for some DepKinds.
364         if !self.dep_graph.is_fully_enabled() {
365             let null_dep_node = DepNode::new_no_params(::dep_graph::DepKind::Null);
366             return self.force_query_with_job::<Q>(key, job, null_dep_node).map(|(v, _)| v);
367         }
368
369         let dep_node = Q::to_dep_node(self, &key);
370
371         if dep_node.kind.is_anon() {
372             profq_msg!(self, ProfileQueriesMsg::ProviderBegin);
373
374             let res = job.start(self, |tcx| {
375                 tcx.dep_graph.with_anon_task(dep_node.kind, || {
376                     Q::compute(tcx.global_tcx(), key)
377                 })
378             });
379
380             profq_msg!(self, ProfileQueriesMsg::ProviderEnd);
381             let ((result, dep_node_index), diagnostics) = res;
382
383             self.dep_graph.read_index(dep_node_index);
384
385             self.on_disk_query_result_cache
386                 .store_diagnostics_for_anon_node(dep_node_index, diagnostics);
387
388             job.complete(&result, dep_node_index);
389
390             return Ok(result);
391         }
392
393         if !dep_node.kind.is_input() {
394             if let Some(dep_node_index) = self.try_mark_green_and_read(&dep_node) {
395                 profq_msg!(self, ProfileQueriesMsg::CacheHit);
396                 return self.load_from_disk_and_cache_in_memory::<Q>(key,
397                                                                     job,
398                                                                     dep_node_index,
399                                                                     &dep_node)
400             }
401         }
402
403         match self.force_query_with_job::<Q>(key, job, dep_node) {
404             Ok((result, dep_node_index)) => {
405                 self.dep_graph.read_index(dep_node_index);
406                 Ok(result)
407             }
408             Err(e) => Err(e)
409         }
410     }
411
412     fn load_from_disk_and_cache_in_memory<Q: QueryDescription<'gcx>>(
413         self,
414         key: Q::Key,
415         job: JobOwner<'a, 'gcx, Q>,
416         dep_node_index: DepNodeIndex,
417         dep_node: &DepNode
418     ) -> Result<Q::Value, CycleError<'gcx>>
419     {
420         // Note this function can be called concurrently from the same query
421         // We must ensure that this is handled correctly
422
423         debug_assert!(self.dep_graph.is_green(dep_node));
424
425         // First we try to load the result from the on-disk cache
426         let result = if Q::cache_on_disk(key.clone()) &&
427                         self.sess.opts.debugging_opts.incremental_queries {
428             let prev_dep_node_index =
429                 self.dep_graph.prev_dep_node_index_of(dep_node);
430             let result = Q::try_load_from_disk(self.global_tcx(),
431                                                     prev_dep_node_index);
432
433             // We always expect to find a cached result for things that
434             // can be forced from DepNode.
435             debug_assert!(!dep_node.kind.can_reconstruct_query_key() ||
436                             result.is_some(),
437                             "Missing on-disk cache entry for {:?}",
438                             dep_node);
439             result
440         } else {
441             // Some things are never cached on disk.
442             None
443         };
444
445         let result = if let Some(result) = result {
446             result
447         } else {
448             // We could not load a result from the on-disk cache, so
449             // recompute.
450
451             // The diagnostics for this query have already been
452             // promoted to the current session during
453             // try_mark_green(), so we can ignore them here.
454             let (result, _) = job.start(self, |tcx| {
455                 // The dep-graph for this computation is already in
456                 // place
457                 tcx.dep_graph.with_ignore(|| {
458                     Q::compute(tcx, key)
459                 })
460             });
461             result
462         };
463
464         // If -Zincremental-verify-ich is specified, re-hash results from
465         // the cache and make sure that they have the expected fingerprint.
466         if self.sess.opts.debugging_opts.incremental_verify_ich {
467             use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
468             use ich::Fingerprint;
469
470             assert!(Some(self.dep_graph.fingerprint_of(dep_node_index)) ==
471                     self.dep_graph.prev_fingerprint_of(dep_node),
472                     "Fingerprint for green query instance not loaded \
473                         from cache: {:?}", dep_node);
474
475             debug!("BEGIN verify_ich({:?})", dep_node);
476             let mut hcx = self.create_stable_hashing_context();
477             let mut hasher = StableHasher::new();
478
479             result.hash_stable(&mut hcx, &mut hasher);
480
481             let new_hash: Fingerprint = hasher.finish();
482             debug!("END verify_ich({:?})", dep_node);
483
484             let old_hash = self.dep_graph.fingerprint_of(dep_node_index);
485
486             assert!(new_hash == old_hash, "Found unstable fingerprints \
487                 for {:?}", dep_node);
488         }
489
490         if self.sess.opts.debugging_opts.query_dep_graph {
491             self.dep_graph.mark_loaded_from_cache(dep_node_index, true);
492         }
493
494         job.complete(&result, dep_node_index);
495
496         Ok(result)
497     }
498
499     fn force_query_with_job<Q: QueryDescription<'gcx>>(
500         self,
501         key: Q::Key,
502         job: JobOwner<'_, 'gcx, Q>,
503         dep_node: DepNode)
504     -> Result<(Q::Value, DepNodeIndex), CycleError<'gcx>> {
505         // If the following assertion triggers, it can have two reasons:
506         // 1. Something is wrong with DepNode creation, either here or
507         //    in DepGraph::try_mark_green()
508         // 2. Two distinct query keys get mapped to the same DepNode
509         //    (see for example #48923)
510         assert!(!self.dep_graph.dep_node_exists(&dep_node),
511                 "Forcing query with already existing DepNode.\n\
512                     - query-key: {:?}\n\
513                     - dep-node: {:?}",
514                 key, dep_node);
515
516         profq_msg!(self, ProfileQueriesMsg::ProviderBegin);
517         let res = job.start(self, |tcx| {
518             if dep_node.kind.is_eval_always() {
519                 tcx.dep_graph.with_eval_always_task(dep_node,
520                                                     tcx,
521                                                     key,
522                                                     Q::compute)
523             } else {
524                 tcx.dep_graph.with_task(dep_node,
525                                         tcx,
526                                         key,
527                                         Q::compute)
528             }
529         });
530         profq_msg!(self, ProfileQueriesMsg::ProviderEnd);
531
532         let ((result, dep_node_index), diagnostics) = res;
533
534         if self.sess.opts.debugging_opts.query_dep_graph {
535             self.dep_graph.mark_loaded_from_cache(dep_node_index, false);
536         }
537
538         if dep_node.kind != ::dep_graph::DepKind::Null {
539             self.on_disk_query_result_cache
540                 .store_diagnostics(dep_node_index, diagnostics);
541         }
542
543         job.complete(&result, dep_node_index);
544
545         Ok((result, dep_node_index))
546     }
547
548     /// Ensure that either this query has all green inputs or been executed.
549     /// Executing query::ensure(D) is considered a read of the dep-node D.
550     ///
551     /// This function is particularly useful when executing passes for their
552     /// side-effects -- e.g., in order to report errors for erroneous programs.
553     ///
554     /// Note: The optimization is only available during incr. comp.
555     pub fn ensure_query<Q: QueryDescription<'gcx>>(self, key: Q::Key) -> () {
556         let dep_node = Q::to_dep_node(self, &key);
557
558         // Ensuring an "input" or anonymous query makes no sense
559         assert!(!dep_node.kind.is_anon());
560         assert!(!dep_node.kind.is_input());
561         if self.try_mark_green_and_read(&dep_node).is_none() {
562             // A None return from `try_mark_green_and_read` means that this is either
563             // a new dep node or that the dep node has already been marked red.
564             // Either way, we can't call `dep_graph.read()` as we don't have the
565             // DepNodeIndex. We must invoke the query itself. The performance cost
566             // this introduces should be negligible as we'll immediately hit the
567             // in-memory cache, or another query down the line will.
568             let _ = self.get_query::<Q>(DUMMY_SP, key);
569         }
570     }
571
572     #[allow(dead_code)]
573     fn force_query<Q: QueryDescription<'gcx>>(
574         self,
575         key: Q::Key,
576         span: Span,
577         dep_node: DepNode
578     ) -> Result<(Q::Value, DepNodeIndex), CycleError<'gcx>> {
579         // We may be concurrently trying both execute and force a query
580         // Ensure that only one of them runs the query
581         let job = match JobOwner::try_get(self, span, &key) {
582             TryGetJob::NotYetStarted(job) => job,
583             TryGetJob::JobCompleted(result) => return result,
584         };
585         self.force_query_with_job::<Q>(key, job, dep_node)
586     }
587
588     pub fn try_get_query<Q: QueryDescription<'gcx>>(
589         self,
590         span: Span,
591         key: Q::Key
592     ) -> Result<Q::Value, DiagnosticBuilder<'a>> {
593         match self.try_get_with::<Q>(span, key) {
594             Ok(e) => Ok(e),
595             Err(e) => Err(self.report_cycle(e)),
596         }
597     }
598
599     pub fn get_query<Q: QueryDescription<'gcx>>(self, span: Span, key: Q::Key) -> Q::Value {
600         self.try_get_query::<Q>(span, key).unwrap_or_else(|mut e| {
601             e.emit();
602             Q::handle_cycle_error(self)
603         })
604     }
605 }
606
607 macro_rules! handle_cycle_error {
608     ([][$this: expr]) => {{
609         Value::from_cycle_error($this.global_tcx())
610     }};
611     ([fatal_cycle$(, $modifiers:ident)*][$this:expr]) => {{
612         $this.sess.abort_if_errors();
613         unreachable!();
614     }};
615     ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
616         handle_cycle_error!([$($modifiers),*][$($args)*])
617     };
618 }
619
620 macro_rules! define_maps {
621     (<$tcx:tt>
622      $($(#[$attr:meta])*
623        [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
624
625         use rustc_data_structures::sync::Lock;
626
627         define_map_struct! {
628             tcx: $tcx,
629             input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
630         }
631
632         impl<$tcx> Maps<$tcx> {
633             pub fn new(providers: IndexVec<CrateNum, Providers<$tcx>>)
634                        -> Self {
635                 Maps {
636                     providers,
637                     $($name: Lock::new(QueryMap::new())),*
638                 }
639             }
640         }
641
642         #[allow(bad_style)]
643         #[derive(Copy, Clone, Debug, PartialEq, Eq)]
644         pub enum Query<$tcx> {
645             $($(#[$attr])* $name($K)),*
646         }
647
648         impl<$tcx> Query<$tcx> {
649             pub fn name(&self) -> &'static str {
650                 match *self {
651                     $(Query::$name(_) => stringify!($name),)*
652                 }
653             }
654
655             pub fn describe(&self, tcx: TyCtxt) -> String {
656                 let (r, name) = match *self {
657                     $(Query::$name(key) => {
658                         (queries::$name::describe(tcx, key), stringify!($name))
659                     })*
660                 };
661                 if tcx.sess.verbose() {
662                     format!("{} [{}]", r, name)
663                 } else {
664                     r
665                 }
666             }
667
668             // FIXME(eddyb) Get more valid Span's on queries.
669             pub fn default_span(&self, tcx: TyCtxt<'_, $tcx, '_>, span: Span) -> Span {
670                 if span != DUMMY_SP {
671                     return span;
672                 }
673                 // The def_span query is used to calculate default_span,
674                 // so exit to avoid infinite recursion
675                 match *self {
676                     Query::def_span(..) => return span,
677                     _ => ()
678                 }
679                 match *self {
680                     $(Query::$name(key) => key.default_span(tcx),)*
681                 }
682             }
683         }
684
685         pub mod queries {
686             use std::marker::PhantomData;
687
688             $(#[allow(bad_style)]
689             pub struct $name<$tcx> {
690                 data: PhantomData<&$tcx ()>
691             })*
692         }
693
694         $(impl<$tcx> QueryConfig<$tcx> for queries::$name<$tcx> {
695             type Key = $K;
696             type Value = $V;
697
698             const NAME: &'static str = stringify!($name);
699
700             fn query(key: Self::Key) -> Query<'tcx> {
701                 Query::$name(key)
702             }
703
704             fn query_map<'a>(tcx: TyCtxt<'a, $tcx, '_>) -> &'a Lock<QueryMap<$tcx, Self>> {
705                 &tcx.maps.$name
706             }
707
708             #[allow(unused)]
709             fn to_dep_node(tcx: TyCtxt<'_, $tcx, '_>, key: &Self::Key) -> DepNode {
710                 use dep_graph::DepConstructor::*;
711
712                 DepNode::new(tcx, $node(*key))
713             }
714
715             fn compute(tcx: TyCtxt<'_, 'tcx, '_>, key: Self::Key) -> Self::Value {
716                 let provider = tcx.maps.providers[key.map_crate()].$name;
717                 provider(tcx.global_tcx(), key)
718             }
719
720             fn handle_cycle_error(tcx: TyCtxt<'_, 'tcx, '_>) -> Self::Value {
721                 handle_cycle_error!([$($modifiers)*][tcx])
722             }
723         }
724
725         impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
726             /// Ensure that either this query has all green inputs or been executed.
727             /// Executing query::ensure(D) is considered a read of the dep-node D.
728             ///
729             /// This function is particularly useful when executing passes for their
730             /// side-effects -- e.g., in order to report errors for erroneous programs.
731             ///
732             /// Note: The optimization is only available during incr. comp.
733             pub fn ensure(tcx: TyCtxt<'a, $tcx, 'lcx>, key: $K) -> () {
734                 tcx.ensure_query::<queries::$name>(key);
735             }
736         })*
737
738         #[derive(Copy, Clone)]
739         pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
740             pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
741             pub span: Span,
742         }
743
744         impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
745             type Target = TyCtxt<'a, 'gcx, 'tcx>;
746             fn deref(&self) -> &Self::Target {
747                 &self.tcx
748             }
749         }
750
751         impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
752             /// Return a transparent wrapper for `TyCtxt` which uses
753             /// `span` as the location of queries performed through it.
754             pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
755                 TyCtxtAt {
756                     tcx: self,
757                     span
758                 }
759             }
760
761             $($(#[$attr])*
762             pub fn $name(self, key: $K) -> $V {
763                 self.at(DUMMY_SP).$name(key)
764             })*
765         }
766
767         impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
768             $($(#[$attr])*
769             pub fn $name(self, key: $K) -> $V {
770                 self.tcx.get_query::<queries::$name>(self.span, key)
771             })*
772         }
773
774         define_provider_struct! {
775             tcx: $tcx,
776             input: ($(([$($modifiers)*] [$name] [$K] [$V]))*)
777         }
778
779         impl<$tcx> Copy for Providers<$tcx> {}
780         impl<$tcx> Clone for Providers<$tcx> {
781             fn clone(&self) -> Self { *self }
782         }
783     }
784 }
785
786 macro_rules! define_map_struct {
787     (tcx: $tcx:tt,
788      input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
789         pub struct Maps<$tcx> {
790             providers: IndexVec<CrateNum, Providers<$tcx>>,
791             $($(#[$attr])*  $name: Lock<QueryMap<$tcx, queries::$name<$tcx>>>,)*
792         }
793     };
794 }
795
796 macro_rules! define_provider_struct {
797     (tcx: $tcx:tt,
798      input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
799         pub struct Providers<$tcx> {
800             $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
801         }
802
803         impl<$tcx> Default for Providers<$tcx> {
804             fn default() -> Self {
805                 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
806                     bug!("tcx.maps.{}({:?}) unsupported by its crate",
807                          stringify!($name), key);
808                 })*
809                 Providers { $($name),* }
810             }
811         }
812     };
813 }
814
815
816 /// The red/green evaluation system will try to mark a specific DepNode in the
817 /// dependency graph as green by recursively trying to mark the dependencies of
818 /// that DepNode as green. While doing so, it will sometimes encounter a DepNode
819 /// where we don't know if it is red or green and we therefore actually have
820 /// to recompute its value in order to find out. Since the only piece of
821 /// information that we have at that point is the DepNode we are trying to
822 /// re-evaluate, we need some way to re-run a query from just that. This is what
823 /// `force_from_dep_node()` implements.
824 ///
825 /// In the general case, a DepNode consists of a DepKind and an opaque
826 /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
827 /// is usually constructed by computing a stable hash of the query-key that the
828 /// DepNode corresponds to. Consequently, it is not in general possible to go
829 /// back from hash to query-key (since hash functions are not reversible). For
830 /// this reason `force_from_dep_node()` is expected to fail from time to time
831 /// because we just cannot find out, from the DepNode alone, what the
832 /// corresponding query-key is and therefore cannot re-run the query.
833 ///
834 /// The system deals with this case letting `try_mark_green` fail which forces
835 /// the root query to be re-evaluated.
836 ///
837 /// Now, if force_from_dep_node() would always fail, it would be pretty useless.
838 /// Fortunately, we can use some contextual information that will allow us to
839 /// reconstruct query-keys for certain kinds of DepNodes. In particular, we
840 /// enforce by construction that the GUID/fingerprint of certain DepNodes is a
841 /// valid DefPathHash. Since we also always build a huge table that maps every
842 /// DefPathHash in the current codebase to the corresponding DefId, we have
843 /// everything we need to re-run the query.
844 ///
845 /// Take the `mir_validated` query as an example. Like many other queries, it
846 /// just has a single parameter: the DefId of the item it will compute the
847 /// validated MIR for. Now, when we call `force_from_dep_node()` on a dep-node
848 /// with kind `MirValidated`, we know that the GUID/fingerprint of the dep-node
849 /// is actually a DefPathHash, and can therefore just look up the corresponding
850 /// DefId in `tcx.def_path_hash_to_def_id`.
851 ///
852 /// When you implement a new query, it will likely have a corresponding new
853 /// DepKind, and you'll have to support it here in `force_from_dep_node()`. As
854 /// a rule of thumb, if your query takes a DefId or DefIndex as sole parameter,
855 /// then `force_from_dep_node()` should not fail for it. Otherwise, you can just
856 /// add it to the "We don't have enough information to reconstruct..." group in
857 /// the match below.
858 pub fn force_from_dep_node<'a, 'gcx, 'lcx>(tcx: TyCtxt<'a, 'gcx, 'lcx>,
859                                            dep_node: &DepNode)
860                                            -> bool {
861     use hir::def_id::LOCAL_CRATE;
862
863     // We must avoid ever having to call force_from_dep_node() for a
864     // DepNode::CodegenUnit:
865     // Since we cannot reconstruct the query key of a DepNode::CodegenUnit, we
866     // would always end up having to evaluate the first caller of the
867     // `codegen_unit` query that *is* reconstructible. This might very well be
868     // the `compile_codegen_unit` query, thus re-translating the whole CGU just
869     // to re-trigger calling the `codegen_unit` query with the right key. At
870     // that point we would already have re-done all the work we are trying to
871     // avoid doing in the first place.
872     // The solution is simple: Just explicitly call the `codegen_unit` query for
873     // each CGU, right after partitioning. This way `try_mark_green` will always
874     // hit the cache instead of having to go through `force_from_dep_node`.
875     // This assertion makes sure, we actually keep applying the solution above.
876     debug_assert!(dep_node.kind != DepKind::CodegenUnit,
877                   "calling force_from_dep_node() on DepKind::CodegenUnit");
878
879     if !dep_node.kind.can_reconstruct_query_key() {
880         return false
881     }
882
883     macro_rules! def_id {
884         () => {
885             if let Some(def_id) = dep_node.extract_def_id(tcx) {
886                 def_id
887             } else {
888                 // return from the whole function
889                 return false
890             }
891         }
892     };
893
894     macro_rules! krate {
895         () => { (def_id!()).krate }
896     };
897
898     macro_rules! force {
899         ($query:ident, $key:expr) => {
900             {
901                 use $crate::util::common::{ProfileQueriesMsg, profq_msg};
902
903                 profq_msg!(tcx,
904                     ProfileQueriesMsg::QueryBegin(
905                         DUMMY_SP.data(),
906                         profq_query_msg!(::ty::maps::queries::$query::NAME, tcx, $key),
907                     )
908                 );
909
910                 match tcx.force_query::<::ty::maps::queries::$query>($key, DUMMY_SP, *dep_node) {
911                     Ok(_) => {},
912                     Err(e) => {
913                         tcx.report_cycle(e).emit();
914                     }
915                 }
916             }
917         }
918     };
919
920     // FIXME(#45015): We should try move this boilerplate code into a macro
921     //                somehow.
922     match dep_node.kind {
923         // These are inputs that are expected to be pre-allocated and that
924         // should therefore always be red or green already
925         DepKind::AllLocalTraitImpls |
926         DepKind::Krate |
927         DepKind::CrateMetadata |
928         DepKind::HirBody |
929         DepKind::Hir |
930
931         // This are anonymous nodes
932         DepKind::TraitSelect |
933
934         // We don't have enough information to reconstruct the query key of
935         // these
936         DepKind::IsCopy |
937         DepKind::IsSized |
938         DepKind::IsFreeze |
939         DepKind::NeedsDrop |
940         DepKind::Layout |
941         DepKind::ConstEval |
942         DepKind::InstanceSymbolName |
943         DepKind::MirShim |
944         DepKind::BorrowCheckKrate |
945         DepKind::Specializes |
946         DepKind::ImplementationsOfTrait |
947         DepKind::TypeParamPredicates |
948         DepKind::CodegenUnit |
949         DepKind::CompileCodegenUnit |
950         DepKind::FulfillObligation |
951         DepKind::VtableMethods |
952         DepKind::EraseRegionsTy |
953         DepKind::NormalizeProjectionTy |
954         DepKind::NormalizeTyAfterErasingRegions |
955         DepKind::DropckOutlives |
956         DepKind::EvaluateObligation |
957         DepKind::SubstituteNormalizeAndTestPredicates |
958         DepKind::InstanceDefSizeEstimate |
959         DepKind::ProgramClausesForEnv |
960
961         // This one should never occur in this context
962         DepKind::Null => {
963             bug!("force_from_dep_node() - Encountered {:?}", dep_node)
964         }
965
966         // These are not queries
967         DepKind::CoherenceCheckTrait |
968         DepKind::ItemVarianceConstraints => {
969             return false
970         }
971
972         DepKind::RegionScopeTree => { force!(region_scope_tree, def_id!()); }
973
974         DepKind::Coherence => { force!(crate_inherent_impls, LOCAL_CRATE); }
975         DepKind::CoherenceInherentImplOverlapCheck => {
976             force!(crate_inherent_impls_overlap_check, LOCAL_CRATE)
977         },
978         DepKind::PrivacyAccessLevels => { force!(privacy_access_levels, LOCAL_CRATE); }
979         DepKind::MirBuilt => { force!(mir_built, def_id!()); }
980         DepKind::MirConstQualif => { force!(mir_const_qualif, def_id!()); }
981         DepKind::MirConst => { force!(mir_const, def_id!()); }
982         DepKind::MirValidated => { force!(mir_validated, def_id!()); }
983         DepKind::MirOptimized => { force!(optimized_mir, def_id!()); }
984
985         DepKind::BorrowCheck => { force!(borrowck, def_id!()); }
986         DepKind::MirBorrowCheck => { force!(mir_borrowck, def_id!()); }
987         DepKind::UnsafetyCheckResult => { force!(unsafety_check_result, def_id!()); }
988         DepKind::UnsafeDeriveOnReprPacked => { force!(unsafe_derive_on_repr_packed, def_id!()); }
989         DepKind::Reachability => { force!(reachable_set, LOCAL_CRATE); }
990         DepKind::MirKeys => { force!(mir_keys, LOCAL_CRATE); }
991         DepKind::CrateVariances => { force!(crate_variances, LOCAL_CRATE); }
992         DepKind::AssociatedItems => { force!(associated_item, def_id!()); }
993         DepKind::TypeOfItem => { force!(type_of, def_id!()); }
994         DepKind::GenericsOfItem => { force!(generics_of, def_id!()); }
995         DepKind::PredicatesOfItem => { force!(predicates_of, def_id!()); }
996         DepKind::InferredOutlivesOf => { force!(inferred_outlives_of, def_id!()); }
997         DepKind::InferredOutlivesCrate => { force!(inferred_outlives_crate, LOCAL_CRATE); }
998         DepKind::SuperPredicatesOfItem => { force!(super_predicates_of, def_id!()); }
999         DepKind::TraitDefOfItem => { force!(trait_def, def_id!()); }
1000         DepKind::AdtDefOfItem => { force!(adt_def, def_id!()); }
1001         DepKind::ImplTraitRef => { force!(impl_trait_ref, def_id!()); }
1002         DepKind::ImplPolarity => { force!(impl_polarity, def_id!()); }
1003         DepKind::FnSignature => { force!(fn_sig, def_id!()); }
1004         DepKind::CoerceUnsizedInfo => { force!(coerce_unsized_info, def_id!()); }
1005         DepKind::ItemVariances => { force!(variances_of, def_id!()); }
1006         DepKind::IsConstFn => { force!(is_const_fn, def_id!()); }
1007         DepKind::IsForeignItem => { force!(is_foreign_item, def_id!()); }
1008         DepKind::SizedConstraint => { force!(adt_sized_constraint, def_id!()); }
1009         DepKind::DtorckConstraint => { force!(adt_dtorck_constraint, def_id!()); }
1010         DepKind::AdtDestructor => { force!(adt_destructor, def_id!()); }
1011         DepKind::AssociatedItemDefIds => { force!(associated_item_def_ids, def_id!()); }
1012         DepKind::InherentImpls => { force!(inherent_impls, def_id!()); }
1013         DepKind::TypeckBodiesKrate => { force!(typeck_item_bodies, LOCAL_CRATE); }
1014         DepKind::TypeckTables => { force!(typeck_tables_of, def_id!()); }
1015         DepKind::UsedTraitImports => { force!(used_trait_imports, def_id!()); }
1016         DepKind::HasTypeckTables => { force!(has_typeck_tables, def_id!()); }
1017         DepKind::SymbolName => { force!(def_symbol_name, def_id!()); }
1018         DepKind::SpecializationGraph => { force!(specialization_graph_of, def_id!()); }
1019         DepKind::ObjectSafety => { force!(is_object_safe, def_id!()); }
1020         DepKind::TraitImpls => { force!(trait_impls_of, def_id!()); }
1021         DepKind::CheckMatch => { force!(check_match, def_id!()); }
1022
1023         DepKind::ParamEnv => { force!(param_env, def_id!()); }
1024         DepKind::DescribeDef => { force!(describe_def, def_id!()); }
1025         DepKind::DefSpan => { force!(def_span, def_id!()); }
1026         DepKind::LookupStability => { force!(lookup_stability, def_id!()); }
1027         DepKind::LookupDeprecationEntry => {
1028             force!(lookup_deprecation_entry, def_id!());
1029         }
1030         DepKind::ConstIsRvaluePromotableToStatic => {
1031             force!(const_is_rvalue_promotable_to_static, def_id!());
1032         }
1033         DepKind::RvaluePromotableMap => { force!(rvalue_promotable_map, def_id!()); }
1034         DepKind::ImplParent => { force!(impl_parent, def_id!()); }
1035         DepKind::TraitOfItem => { force!(trait_of_item, def_id!()); }
1036         DepKind::IsReachableNonGeneric => { force!(is_reachable_non_generic, def_id!()); }
1037         DepKind::IsUnreachableLocalDefinition => {
1038             force!(is_unreachable_local_definition, def_id!());
1039         }
1040         DepKind::IsMirAvailable => { force!(is_mir_available, def_id!()); }
1041         DepKind::ItemAttrs => { force!(item_attrs, def_id!()); }
1042         DepKind::TransFnAttrs => { force!(trans_fn_attrs, def_id!()); }
1043         DepKind::FnArgNames => { force!(fn_arg_names, def_id!()); }
1044         DepKind::RenderedConst => { force!(rendered_const, def_id!()); }
1045         DepKind::DylibDepFormats => { force!(dylib_dependency_formats, krate!()); }
1046         DepKind::IsPanicRuntime => { force!(is_panic_runtime, krate!()); }
1047         DepKind::IsCompilerBuiltins => { force!(is_compiler_builtins, krate!()); }
1048         DepKind::HasGlobalAllocator => { force!(has_global_allocator, krate!()); }
1049         DepKind::ExternCrate => { force!(extern_crate, def_id!()); }
1050         DepKind::LintLevels => { force!(lint_levels, LOCAL_CRATE); }
1051         DepKind::InScopeTraits => { force!(in_scope_traits_map, def_id!().index); }
1052         DepKind::ModuleExports => { force!(module_exports, def_id!()); }
1053         DepKind::IsSanitizerRuntime => { force!(is_sanitizer_runtime, krate!()); }
1054         DepKind::IsProfilerRuntime => { force!(is_profiler_runtime, krate!()); }
1055         DepKind::GetPanicStrategy => { force!(panic_strategy, krate!()); }
1056         DepKind::IsNoBuiltins => { force!(is_no_builtins, krate!()); }
1057         DepKind::ImplDefaultness => { force!(impl_defaultness, def_id!()); }
1058         DepKind::CheckItemWellFormed => { force!(check_item_well_formed, def_id!()); }
1059         DepKind::CheckTraitItemWellFormed => { force!(check_trait_item_well_formed, def_id!()); }
1060         DepKind::CheckImplItemWellFormed => { force!(check_impl_item_well_formed, def_id!()); }
1061         DepKind::ReachableNonGenerics => { force!(reachable_non_generics, krate!()); }
1062         DepKind::NativeLibraries => { force!(native_libraries, krate!()); }
1063         DepKind::PluginRegistrarFn => { force!(plugin_registrar_fn, krate!()); }
1064         DepKind::DeriveRegistrarFn => { force!(derive_registrar_fn, krate!()); }
1065         DepKind::CrateDisambiguator => { force!(crate_disambiguator, krate!()); }
1066         DepKind::CrateHash => { force!(crate_hash, krate!()); }
1067         DepKind::OriginalCrateName => { force!(original_crate_name, krate!()); }
1068         DepKind::ExtraFileName => { force!(extra_filename, krate!()); }
1069
1070         DepKind::AllTraitImplementations => {
1071             force!(all_trait_implementations, krate!());
1072         }
1073
1074         DepKind::DllimportForeignItems => {
1075             force!(dllimport_foreign_items, krate!());
1076         }
1077         DepKind::IsDllimportForeignItem => {
1078             force!(is_dllimport_foreign_item, def_id!());
1079         }
1080         DepKind::IsStaticallyIncludedForeignItem => {
1081             force!(is_statically_included_foreign_item, def_id!());
1082         }
1083         DepKind::NativeLibraryKind => { force!(native_library_kind, def_id!()); }
1084         DepKind::LinkArgs => { force!(link_args, LOCAL_CRATE); }
1085
1086         DepKind::ResolveLifetimes => { force!(resolve_lifetimes, krate!()); }
1087         DepKind::NamedRegion => { force!(named_region_map, def_id!().index); }
1088         DepKind::IsLateBound => { force!(is_late_bound_map, def_id!().index); }
1089         DepKind::ObjectLifetimeDefaults => {
1090             force!(object_lifetime_defaults_map, def_id!().index);
1091         }
1092
1093         DepKind::Visibility => { force!(visibility, def_id!()); }
1094         DepKind::DepKind => { force!(dep_kind, krate!()); }
1095         DepKind::CrateName => { force!(crate_name, krate!()); }
1096         DepKind::ItemChildren => { force!(item_children, def_id!()); }
1097         DepKind::ExternModStmtCnum => { force!(extern_mod_stmt_cnum, def_id!()); }
1098         DepKind::GetLangItems => { force!(get_lang_items, LOCAL_CRATE); }
1099         DepKind::DefinedLangItems => { force!(defined_lang_items, krate!()); }
1100         DepKind::MissingLangItems => { force!(missing_lang_items, krate!()); }
1101         DepKind::VisibleParentMap => { force!(visible_parent_map, LOCAL_CRATE); }
1102         DepKind::MissingExternCrateItem => {
1103             force!(missing_extern_crate_item, krate!());
1104         }
1105         DepKind::UsedCrateSource => { force!(used_crate_source, krate!()); }
1106         DepKind::PostorderCnums => { force!(postorder_cnums, LOCAL_CRATE); }
1107
1108         DepKind::Freevars => { force!(freevars, def_id!()); }
1109         DepKind::MaybeUnusedTraitImport => {
1110             force!(maybe_unused_trait_import, def_id!());
1111         }
1112         DepKind::MaybeUnusedExternCrates => { force!(maybe_unused_extern_crates, LOCAL_CRATE); }
1113         DepKind::StabilityIndex => { force!(stability_index, LOCAL_CRATE); }
1114         DepKind::AllTraits => { force!(all_traits, LOCAL_CRATE); }
1115         DepKind::AllCrateNums => { force!(all_crate_nums, LOCAL_CRATE); }
1116         DepKind::ExportedSymbols => { force!(exported_symbols, krate!()); }
1117         DepKind::CollectAndPartitionTranslationItems => {
1118             force!(collect_and_partition_translation_items, LOCAL_CRATE);
1119         }
1120         DepKind::IsTranslatedItem => { force!(is_translated_item, def_id!()); }
1121         DepKind::OutputFilenames => { force!(output_filenames, LOCAL_CRATE); }
1122
1123         DepKind::TargetFeaturesWhitelist => { force!(target_features_whitelist, LOCAL_CRATE); }
1124
1125         DepKind::Features => { force!(features_query, LOCAL_CRATE); }
1126
1127         DepKind::ProgramClausesFor => { force!(program_clauses_for, def_id!()); }
1128         DepKind::WasmCustomSections => { force!(wasm_custom_sections, krate!()); }
1129         DepKind::WasmImportModuleMap => { force!(wasm_import_module_map, krate!()); }
1130         DepKind::ForeignModules => { force!(foreign_modules, krate!()); }
1131
1132         DepKind::UpstreamMonomorphizations => {
1133             force!(upstream_monomorphizations, krate!());
1134         }
1135         DepKind::UpstreamMonomorphizationsFor => {
1136             force!(upstream_monomorphizations_for, def_id!());
1137         }
1138     }
1139
1140     true
1141 }
1142
1143
1144 // FIXME(#45015): Another piece of boilerplate code that could be generated in
1145 //                a combined define_dep_nodes!()/define_maps!() macro.
1146 macro_rules! impl_load_from_cache {
1147     ($($dep_kind:ident => $query_name:ident,)*) => {
1148         impl DepNode {
1149             // Check whether the query invocation corresponding to the given
1150             // DepNode is eligible for on-disk-caching.
1151             pub fn cache_on_disk(&self, tcx: TyCtxt) -> bool {
1152                 use ty::maps::queries;
1153                 use ty::maps::QueryDescription;
1154
1155                 match self.kind {
1156                     $(DepKind::$dep_kind => {
1157                         let def_id = self.extract_def_id(tcx).unwrap();
1158                         queries::$query_name::cache_on_disk(def_id)
1159                     })*
1160                     _ => false
1161                 }
1162             }
1163
1164             // This is method will execute the query corresponding to the given
1165             // DepNode. It is only expected to work for DepNodes where the
1166             // above `cache_on_disk` methods returns true.
1167             // Also, as a sanity check, it expects that the corresponding query
1168             // invocation has been marked as green already.
1169             pub fn load_from_on_disk_cache(&self, tcx: TyCtxt) {
1170                 match self.kind {
1171                     $(DepKind::$dep_kind => {
1172                         debug_assert!(tcx.dep_graph
1173                                          .node_color(self)
1174                                          .map(|c| c.is_green())
1175                                          .unwrap_or(false));
1176
1177                         let def_id = self.extract_def_id(tcx).unwrap();
1178                         let _ = tcx.$query_name(def_id);
1179                     })*
1180                     _ => {
1181                         bug!()
1182                     }
1183                 }
1184             }
1185         }
1186     }
1187 }
1188
1189 impl_load_from_cache!(
1190     TypeckTables => typeck_tables_of,
1191     MirOptimized => optimized_mir,
1192     UnsafetyCheckResult => unsafety_check_result,
1193     BorrowCheck => borrowck,
1194     MirBorrowCheck => mir_borrowck,
1195     MirConstQualif => mir_const_qualif,
1196     SymbolName => def_symbol_name,
1197     ConstIsRvaluePromotableToStatic => const_is_rvalue_promotable_to_static,
1198     CheckMatch => check_match,
1199     TypeOfItem => type_of,
1200     GenericsOfItem => generics_of,
1201     PredicatesOfItem => predicates_of,
1202     UsedTraitImports => used_trait_imports,
1203     TransFnAttrs => trans_fn_attrs,
1204     SpecializationGraph => specialization_graph_of,
1205 );