]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/maps/plumbing.rs
dd8b8a2e5da8268f5e74c73a13a757e853ce41dd
[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 ty::{TyCtxt};
18 use ty::maps::Query; // NB: actually generated by the macros in this file
19 use ty::maps::config::QueryDescription;
20 use ty::item_path;
21
22 use rustc_data_structures::fx::{FxHashMap};
23 use std::cell::{Ref, RefMut};
24 use std::marker::PhantomData;
25 use std::mem;
26 use syntax_pos::Span;
27
28 pub(super) struct QueryMap<'tcx, D: QueryDescription<'tcx>> {
29     phantom: PhantomData<(D, &'tcx ())>,
30     pub(super) map: FxHashMap<D::Key, QueryValue<D::Value>>,
31 }
32
33 pub(super) struct QueryValue<T> {
34     pub(super) value: T,
35     pub(super) index: DepNodeIndex,
36 }
37
38 impl<T> QueryValue<T> {
39     pub(super) fn new(value: T,
40                       dep_node_index: DepNodeIndex)
41                       -> QueryValue<T> {
42         QueryValue {
43             value,
44             index: dep_node_index,
45         }
46     }
47 }
48
49 impl<'tcx, M: QueryDescription<'tcx>> QueryMap<'tcx, M> {
50     pub(super) fn new() -> QueryMap<'tcx, M> {
51         QueryMap {
52             phantom: PhantomData,
53             map: FxHashMap(),
54         }
55     }
56 }
57
58 pub(super) trait GetCacheInternal<'tcx>: QueryDescription<'tcx> + Sized {
59     fn get_cache_internal<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
60                               -> Ref<'a, QueryMap<'tcx, Self>>;
61 }
62
63 pub(super) struct CycleError<'a, 'tcx: 'a> {
64     span: Span,
65     cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
66 }
67
68 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
69     pub(super) fn report_cycle(self, CycleError { span, cycle }: CycleError)
70         -> DiagnosticBuilder<'a>
71     {
72         // Subtle: release the refcell lock before invoking `describe()`
73         // below by dropping `cycle`.
74         let stack = cycle.to_vec();
75         mem::drop(cycle);
76
77         assert!(!stack.is_empty());
78
79         // Disable naming impls with types in this path, since that
80         // sometimes cycles itself, leading to extra cycle errors.
81         // (And cycle errors around impls tend to occur during the
82         // collect/coherence phases anyhow.)
83         item_path::with_forced_impl_filename_line(|| {
84             let span = self.sess.codemap().def_span(span);
85             let mut err =
86                 struct_span_err!(self.sess, span, E0391,
87                                  "unsupported cyclic reference between types/traits detected");
88             err.span_label(span, "cyclic reference");
89
90             err.span_note(self.sess.codemap().def_span(stack[0].0),
91                           &format!("the cycle begins when {}...", stack[0].1.describe(self)));
92
93             for &(span, ref query) in &stack[1..] {
94                 err.span_note(self.sess.codemap().def_span(span),
95                               &format!("...which then requires {}...", query.describe(self)));
96             }
97
98             err.note(&format!("...which then again requires {}, completing the cycle.",
99                               stack[0].1.describe(self)));
100
101             return err
102         })
103     }
104
105     pub(super) fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
106                                     -> Result<R, CycleError<'a, 'gcx>>
107         where F: FnOnce() -> R
108     {
109         {
110             let mut stack = self.maps.query_stack.borrow_mut();
111             if let Some((i, _)) = stack.iter().enumerate().rev()
112                                        .find(|&(_, &(_, ref q))| *q == query) {
113                 return Err(CycleError {
114                     span,
115                     cycle: RefMut::map(stack, |stack| &mut stack[i..])
116                 });
117             }
118             stack.push((span, query));
119         }
120
121         let result = compute();
122
123         self.maps.query_stack.borrow_mut().pop();
124
125         Ok(result)
126     }
127
128     /// Try to read a node index for the node dep_node.
129     /// A node will have an index, when it's already been marked green, or when we can mark it
130     /// green. This function will mark the current task as a reader of the specified node, when
131     /// the a node index can be found for that node.
132     pub(super) fn try_mark_green_and_read(self, dep_node: &DepNode) -> Option<DepNodeIndex> {
133         match self.dep_graph.node_color(dep_node) {
134             Some(DepNodeColor::Green(dep_node_index)) => {
135                 self.dep_graph.read_index(dep_node_index);
136                 Some(dep_node_index)
137             }
138             Some(DepNodeColor::Red) => {
139                 None
140             }
141             None => {
142                 // try_mark_green (called below) will panic when full incremental
143                 // compilation is disabled. If that's the case, we can't try to mark nodes
144                 // as green anyway, so we can safely return None here.
145                 if !self.dep_graph.is_fully_enabled() {
146                     return None;
147                 }
148                 match self.dep_graph.try_mark_green(self.global_tcx(), &dep_node) {
149                     Some(dep_node_index) => {
150                         debug_assert!(self.dep_graph.is_green(dep_node_index));
151                         self.dep_graph.read_index(dep_node_index);
152                         Some(dep_node_index)
153                     }
154                     None => {
155                         None
156                     }
157                 }
158             }
159         }
160     }
161 }
162
163 // If enabled, send a message to the profile-queries thread
164 macro_rules! profq_msg {
165     ($tcx:expr, $msg:expr) => {
166         if cfg!(debug_assertions) {
167             if  $tcx.sess.profile_queries() {
168                 profq_msg($msg)
169             }
170         }
171     }
172 }
173
174 // If enabled, format a key using its debug string, which can be
175 // expensive to compute (in terms of time).
176 macro_rules! profq_key {
177     ($tcx:expr, $key:expr) => {
178         if cfg!(debug_assertions) {
179             if $tcx.sess.profile_queries_and_keys() {
180                 Some(format!("{:?}", $key))
181             } else { None }
182         } else { None }
183     }
184 }
185
186 macro_rules! define_maps {
187     (<$tcx:tt>
188      $($(#[$attr:meta])*
189        [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
190
191         use dep_graph::DepNodeIndex;
192         use std::cell::RefCell;
193
194         define_map_struct! {
195             tcx: $tcx,
196             input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
197         }
198
199         impl<$tcx> Maps<$tcx> {
200             pub fn new(providers: IndexVec<CrateNum, Providers<$tcx>>)
201                        -> Self {
202                 Maps {
203                     providers,
204                     query_stack: RefCell::new(vec![]),
205                     $($name: RefCell::new(QueryMap::new())),*
206                 }
207             }
208         }
209
210         #[allow(bad_style)]
211         #[derive(Copy, Clone, Debug, PartialEq, Eq)]
212         pub enum Query<$tcx> {
213             $($(#[$attr])* $name($K)),*
214         }
215
216         #[allow(bad_style)]
217         #[derive(Clone, Debug, PartialEq, Eq)]
218         pub enum QueryMsg {
219             $($name(Option<String>)),*
220         }
221
222         impl<$tcx> Query<$tcx> {
223             pub fn describe(&self, tcx: TyCtxt) -> String {
224                 let (r, name) = match *self {
225                     $(Query::$name(key) => {
226                         (queries::$name::describe(tcx, key), stringify!($name))
227                     })*
228                 };
229                 if tcx.sess.verbose() {
230                     format!("{} [{}]", r, name)
231                 } else {
232                     r
233                 }
234             }
235         }
236
237         pub mod queries {
238             use std::marker::PhantomData;
239
240             $(#[allow(bad_style)]
241             pub struct $name<$tcx> {
242                 data: PhantomData<&$tcx ()>
243             })*
244         }
245
246         $(impl<$tcx> QueryConfig for queries::$name<$tcx> {
247             type Key = $K;
248             type Value = $V;
249         }
250
251         impl<$tcx> GetCacheInternal<$tcx> for queries::$name<$tcx> {
252             fn get_cache_internal<'a>(tcx: TyCtxt<'a, $tcx, $tcx>)
253                                       -> ::std::cell::Ref<'a, QueryMap<$tcx, Self>> {
254                 tcx.maps.$name.borrow()
255             }
256         }
257
258         impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
259
260             #[allow(unused)]
261             fn to_dep_node(tcx: TyCtxt<'a, $tcx, 'lcx>, key: &$K) -> DepNode {
262                 use dep_graph::DepConstructor::*;
263
264                 DepNode::new(tcx, $node(*key))
265             }
266
267             fn try_get_with(tcx: TyCtxt<'a, $tcx, 'lcx>,
268                             mut span: Span,
269                             key: $K)
270                             -> Result<$V, CycleError<'a, $tcx>>
271             {
272                 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
273                        stringify!($name),
274                        key,
275                        span);
276
277                 profq_msg!(tcx,
278                     ProfileQueriesMsg::QueryBegin(
279                         span.data(),
280                         QueryMsg::$name(profq_key!(tcx, key))
281                     )
282                 );
283
284                 if let Some(value) = tcx.maps.$name.borrow().map.get(&key) {
285                     profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
286                     tcx.dep_graph.read_index(value.index);
287                     return Ok((&value.value).clone());
288                 }
289
290                 // FIXME(eddyb) Get more valid Span's on queries.
291                 // def_span guard is necessary to prevent a recursive loop,
292                 // default_span calls def_span query internally.
293                 if span == DUMMY_SP && stringify!($name) != "def_span" {
294                     span = key.default_span(tcx)
295                 }
296
297                 // Fast path for when incr. comp. is off. `to_dep_node` is
298                 // expensive for some DepKinds.
299                 if !tcx.dep_graph.is_fully_enabled() {
300                     let null_dep_node = DepNode::new_no_params(::dep_graph::DepKind::Null);
301                     return Self::force(tcx, key, span, null_dep_node)
302                                 .map(|(v, _)| v);
303                 }
304
305                 let dep_node = Self::to_dep_node(tcx, &key);
306
307                 if dep_node.kind.is_anon() {
308                     profq_msg!(tcx, ProfileQueriesMsg::ProviderBegin);
309
310                     let res = tcx.cycle_check(span, Query::$name(key), || {
311                         tcx.sess.diagnostic().track_diagnostics(|| {
312                             tcx.dep_graph.with_anon_task(dep_node.kind, || {
313                                 Self::compute_result(tcx.global_tcx(), key)
314                             })
315                         })
316                     })?;
317
318                     profq_msg!(tcx, ProfileQueriesMsg::ProviderEnd);
319                     let ((result, dep_node_index), diagnostics) = res;
320
321                     tcx.dep_graph.read_index(dep_node_index);
322
323                     tcx.on_disk_query_result_cache
324                        .store_diagnostics_for_anon_node(dep_node_index, diagnostics);
325
326                     let value = QueryValue::new(result, dep_node_index);
327
328                     return Ok((&tcx.maps
329                                     .$name
330                                     .borrow_mut()
331                                     .map
332                                     .entry(key)
333                                     .or_insert(value)
334                                     .value).clone());
335                 }
336
337                 if !dep_node.kind.is_input() {
338                     if let Some(dep_node_index) = tcx.try_mark_green_and_read(&dep_node) {
339                         profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
340                         return Self::load_from_disk_and_cache_in_memory(tcx,
341                                                                         key,
342                                                                         span,
343                                                                         dep_node_index,
344                                                                         &dep_node)
345                     }
346                 }
347
348                 match Self::force(tcx, key, span, dep_node) {
349                     Ok((result, dep_node_index)) => {
350                         tcx.dep_graph.read_index(dep_node_index);
351                         Ok(result)
352                     }
353                     Err(e) => Err(e)
354                 }
355             }
356
357             /// Ensure that either this query has all green inputs or been executed.
358             /// Executing query::ensure(D) is considered a read of the dep-node D.
359             ///
360             /// This function is particularly useful when executing passes for their
361             /// side-effects -- e.g., in order to report errors for erroneous programs.
362             ///
363             /// Note: The optimization is only available during incr. comp.
364             pub fn ensure(tcx: TyCtxt<'a, $tcx, 'lcx>, key: $K) -> () {
365                 let dep_node = Self::to_dep_node(tcx, &key);
366
367                 // Ensuring an "input" or anonymous query makes no sense
368                 assert!(!dep_node.kind.is_anon());
369                 assert!(!dep_node.kind.is_input());
370                 if tcx.try_mark_green_and_read(&dep_node).is_none() {
371                     // A None return from `try_mark_green_and_read` means that this is either
372                     // a new dep node or that the dep node has already been marked red.
373                     // Either way, we can't call `dep_graph.read()` as we don't have the
374                     // DepNodeIndex. We must invoke the query itself. The performance cost
375                     // this introduces should be negligible as we'll immediately hit the
376                     // in-memory cache, or another query down the line will.
377                     let _ = tcx.$name(key);
378                 }
379             }
380
381             fn compute_result(tcx: TyCtxt<'a, $tcx, 'lcx>, key: $K) -> $V {
382                 let provider = tcx.maps.providers[key.map_crate()].$name;
383                 provider(tcx.global_tcx(), key)
384             }
385
386             fn load_from_disk_and_cache_in_memory(tcx: TyCtxt<'a, $tcx, 'lcx>,
387                                                   key: $K,
388                                                   span: Span,
389                                                   dep_node_index: DepNodeIndex,
390                                                   dep_node: &DepNode)
391                                                   -> Result<$V, CycleError<'a, $tcx>>
392             {
393                 debug_assert!(tcx.dep_graph.is_green(dep_node_index));
394
395                 // First we try to load the result from the on-disk cache
396                 let result = if Self::cache_on_disk(key) &&
397                                 tcx.sess.opts.debugging_opts.incremental_queries {
398                     let prev_dep_node_index =
399                         tcx.dep_graph.prev_dep_node_index_of(dep_node);
400                     let result = Self::try_load_from_disk(tcx.global_tcx(),
401                                                           prev_dep_node_index);
402
403                     // We always expect to find a cached result for things that
404                     // can be forced from DepNode.
405                     debug_assert!(!dep_node.kind.can_reconstruct_query_key() ||
406                                   result.is_some(),
407                                   "Missing on-disk cache entry for {:?}",
408                                   dep_node);
409                     result
410                 } else {
411                     // Some things are never cached on disk.
412                     None
413                 };
414
415                 let result = if let Some(result) = result {
416                     result
417                 } else {
418                     // We could not load a result from the on-disk cache, so
419                     // recompute.
420                     let (result, _ ) = tcx.cycle_check(span, Query::$name(key), || {
421                         // The diagnostics for this query have already been
422                         // promoted to the current session during
423                         // try_mark_green(), so we can ignore them here.
424                         tcx.sess.diagnostic().track_diagnostics(|| {
425                             // The dep-graph for this computation is already in
426                             // place
427                             tcx.dep_graph.with_ignore(|| {
428                                 Self::compute_result(tcx, key)
429                             })
430                         })
431                     })?;
432                     result
433                 };
434
435                 // If -Zincremental-verify-ich is specified, re-hash results from
436                 // the cache and make sure that they have the expected fingerprint.
437                 if tcx.sess.opts.debugging_opts.incremental_verify_ich {
438                     use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
439                     use ich::Fingerprint;
440
441                     assert!(Some(tcx.dep_graph.fingerprint_of(dep_node_index)) ==
442                             tcx.dep_graph.prev_fingerprint_of(dep_node),
443                             "Fingerprint for green query instance not loaded \
444                              from cache: {:?}", dep_node);
445
446                     debug!("BEGIN verify_ich({:?})", dep_node);
447                     let mut hcx = tcx.create_stable_hashing_context();
448                     let mut hasher = StableHasher::new();
449
450                     result.hash_stable(&mut hcx, &mut hasher);
451
452                     let new_hash: Fingerprint = hasher.finish();
453                     debug!("END verify_ich({:?})", dep_node);
454
455                     let old_hash = tcx.dep_graph.fingerprint_of(dep_node_index);
456
457                     assert!(new_hash == old_hash, "Found unstable fingerprints \
458                         for {:?}", dep_node);
459                 }
460
461                 if tcx.sess.opts.debugging_opts.query_dep_graph {
462                     tcx.dep_graph.mark_loaded_from_cache(dep_node_index, true);
463                 }
464
465                 let value = QueryValue::new(result, dep_node_index);
466
467                 Ok((&tcx.maps
468                          .$name
469                          .borrow_mut()
470                          .map
471                          .entry(key)
472                          .or_insert(value)
473                          .value).clone())
474             }
475
476             fn force(tcx: TyCtxt<'a, $tcx, 'lcx>,
477                      key: $K,
478                      span: Span,
479                      dep_node: DepNode)
480                      -> Result<($V, DepNodeIndex), CycleError<'a, $tcx>> {
481                 debug_assert!(tcx.dep_graph.node_color(&dep_node).is_none());
482
483                 profq_msg!(tcx, ProfileQueriesMsg::ProviderBegin);
484                 let res = tcx.cycle_check(span, Query::$name(key), || {
485                     tcx.sess.diagnostic().track_diagnostics(|| {
486                         if dep_node.kind.is_eval_always() {
487                             tcx.dep_graph.with_eval_always_task(dep_node,
488                                                                 tcx,
489                                                                 key,
490                                                                 Self::compute_result)
491                         } else {
492                             tcx.dep_graph.with_task(dep_node,
493                                                     tcx,
494                                                     key,
495                                                     Self::compute_result)
496                         }
497                     })
498                 })?;
499                 profq_msg!(tcx, ProfileQueriesMsg::ProviderEnd);
500
501                 let ((result, dep_node_index), diagnostics) = res;
502
503                 if tcx.sess.opts.debugging_opts.query_dep_graph {
504                     tcx.dep_graph.mark_loaded_from_cache(dep_node_index, false);
505                 }
506
507                 if dep_node.kind != ::dep_graph::DepKind::Null {
508                     tcx.on_disk_query_result_cache
509                        .store_diagnostics(dep_node_index, diagnostics);
510                 }
511
512                 let value = QueryValue::new(result, dep_node_index);
513
514                 Ok(((&tcx.maps
515                          .$name
516                          .borrow_mut()
517                          .map
518                          .entry(key)
519                          .or_insert(value)
520                          .value).clone(),
521                    dep_node_index))
522             }
523
524             pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
525                            -> Result<$V, DiagnosticBuilder<'a>> {
526                 match Self::try_get_with(tcx, span, key) {
527                     Ok(e) => Ok(e),
528                     Err(e) => Err(tcx.report_cycle(e)),
529                 }
530             }
531         })*
532
533         #[derive(Copy, Clone)]
534         pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
535             pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
536             pub span: Span,
537         }
538
539         impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
540             type Target = TyCtxt<'a, 'gcx, 'tcx>;
541             fn deref(&self) -> &Self::Target {
542                 &self.tcx
543             }
544         }
545
546         impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
547             /// Return a transparent wrapper for `TyCtxt` which uses
548             /// `span` as the location of queries performed through it.
549             pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
550                 TyCtxtAt {
551                     tcx: self,
552                     span
553                 }
554             }
555
556             $($(#[$attr])*
557             pub fn $name(self, key: $K) -> $V {
558                 self.at(DUMMY_SP).$name(key)
559             })*
560         }
561
562         impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
563             $($(#[$attr])*
564             pub fn $name(self, key: $K) -> $V {
565                 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|mut e| {
566                     e.emit();
567                     Value::from_cycle_error(self.global_tcx())
568                 })
569             })*
570         }
571
572         define_provider_struct! {
573             tcx: $tcx,
574             input: ($(([$($modifiers)*] [$name] [$K] [$V]))*)
575         }
576
577         impl<$tcx> Copy for Providers<$tcx> {}
578         impl<$tcx> Clone for Providers<$tcx> {
579             fn clone(&self) -> Self { *self }
580         }
581     }
582 }
583
584 macro_rules! define_map_struct {
585     (tcx: $tcx:tt,
586      input: ($(([$(modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
587         pub struct Maps<$tcx> {
588             providers: IndexVec<CrateNum, Providers<$tcx>>,
589             query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
590             $($(#[$attr])*  $name: RefCell<QueryMap<$tcx, queries::$name<$tcx>>>,)*
591         }
592     };
593 }
594
595 macro_rules! define_provider_struct {
596     (tcx: $tcx:tt,
597      input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
598         pub struct Providers<$tcx> {
599             $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
600         }
601
602         impl<$tcx> Default for Providers<$tcx> {
603             fn default() -> Self {
604                 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
605                     bug!("tcx.maps.{}({:?}) unsupported by its crate",
606                          stringify!($name), key);
607                 })*
608                 Providers { $($name),* }
609             }
610         }
611     };
612 }
613
614
615 /// The red/green evaluation system will try to mark a specific DepNode in the
616 /// dependency graph as green by recursively trying to mark the dependencies of
617 /// that DepNode as green. While doing so, it will sometimes encounter a DepNode
618 /// where we don't know if it is red or green and we therefore actually have
619 /// to recompute its value in order to find out. Since the only piece of
620 /// information that we have at that point is the DepNode we are trying to
621 /// re-evaluate, we need some way to re-run a query from just that. This is what
622 /// `force_from_dep_node()` implements.
623 ///
624 /// In the general case, a DepNode consists of a DepKind and an opaque
625 /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
626 /// is usually constructed by computing a stable hash of the query-key that the
627 /// DepNode corresponds to. Consequently, it is not in general possible to go
628 /// back from hash to query-key (since hash functions are not reversible). For
629 /// this reason `force_from_dep_node()` is expected to fail from time to time
630 /// because we just cannot find out, from the DepNode alone, what the
631 /// corresponding query-key is and therefore cannot re-run the query.
632 ///
633 /// The system deals with this case letting `try_mark_green` fail which forces
634 /// the root query to be re-evaluated.
635 ///
636 /// Now, if force_from_dep_node() would always fail, it would be pretty useless.
637 /// Fortunately, we can use some contextual information that will allow us to
638 /// reconstruct query-keys for certain kinds of DepNodes. In particular, we
639 /// enforce by construction that the GUID/fingerprint of certain DepNodes is a
640 /// valid DefPathHash. Since we also always build a huge table that maps every
641 /// DefPathHash in the current codebase to the corresponding DefId, we have
642 /// everything we need to re-run the query.
643 ///
644 /// Take the `mir_validated` query as an example. Like many other queries, it
645 /// just has a single parameter: the DefId of the item it will compute the
646 /// validated MIR for. Now, when we call `force_from_dep_node()` on a dep-node
647 /// with kind `MirValidated`, we know that the GUID/fingerprint of the dep-node
648 /// is actually a DefPathHash, and can therefore just look up the corresponding
649 /// DefId in `tcx.def_path_hash_to_def_id`.
650 ///
651 /// When you implement a new query, it will likely have a corresponding new
652 /// DepKind, and you'll have to support it here in `force_from_dep_node()`. As
653 /// a rule of thumb, if your query takes a DefId or DefIndex as sole parameter,
654 /// then `force_from_dep_node()` should not fail for it. Otherwise, you can just
655 /// add it to the "We don't have enough information to reconstruct..." group in
656 /// the match below.
657 pub fn force_from_dep_node<'a, 'gcx, 'lcx>(tcx: TyCtxt<'a, 'gcx, 'lcx>,
658                                            dep_node: &DepNode)
659                                            -> bool {
660     use ty::maps::keys::Key;
661     use hir::def_id::LOCAL_CRATE;
662
663     // We must avoid ever having to call force_from_dep_node() for a
664     // DepNode::CodegenUnit:
665     // Since we cannot reconstruct the query key of a DepNode::CodegenUnit, we
666     // would always end up having to evaluate the first caller of the
667     // `codegen_unit` query that *is* reconstructible. This might very well be
668     // the `compile_codegen_unit` query, thus re-translating the whole CGU just
669     // to re-trigger calling the `codegen_unit` query with the right key. At
670     // that point we would already have re-done all the work we are trying to
671     // avoid doing in the first place.
672     // The solution is simple: Just explicitly call the `codegen_unit` query for
673     // each CGU, right after partitioning. This way `try_mark_green` will always
674     // hit the cache instead of having to go through `force_from_dep_node`.
675     // This assertion makes sure, we actually keep applying the solution above.
676     debug_assert!(dep_node.kind != DepKind::CodegenUnit,
677                   "calling force_from_dep_node() on DepKind::CodegenUnit");
678
679     if !dep_node.kind.can_reconstruct_query_key() {
680         return false
681     }
682
683     macro_rules! def_id {
684         () => {
685             if let Some(def_id) = dep_node.extract_def_id(tcx) {
686                 def_id
687             } else {
688                 // return from the whole function
689                 return false
690             }
691         }
692     };
693
694     macro_rules! krate {
695         () => { (def_id!()).krate }
696     };
697
698     macro_rules! force {
699         ($query:ident, $key:expr) => {
700             {
701                 use $crate::util::common::{ProfileQueriesMsg, profq_msg};
702
703                 // FIXME(eddyb) Get more valid Span's on queries.
704                 // def_span guard is necessary to prevent a recursive loop,
705                 // default_span calls def_span query internally.
706                 let span = if stringify!($query) != "def_span" {
707                     $key.default_span(tcx)
708                 } else {
709                     ::syntax_pos::DUMMY_SP
710                 };
711
712                 profq_msg!(tcx,
713                     ProfileQueriesMsg::QueryBegin(
714                         span.data(),
715                         ::ty::maps::QueryMsg::$query(profq_key!(tcx, $key))
716                     )
717                 );
718
719                 match ::ty::maps::queries::$query::force(tcx, $key, span, *dep_node) {
720                     Ok(_) => {},
721                     Err(e) => {
722                         tcx.report_cycle(e).emit();
723                     }
724                 }
725             }
726         }
727     };
728
729     // FIXME(#45015): We should try move this boilerplate code into a macro
730     //                somehow.
731     match dep_node.kind {
732         // These are inputs that are expected to be pre-allocated and that
733         // should therefore always be red or green already
734         DepKind::AllLocalTraitImpls |
735         DepKind::Krate |
736         DepKind::CrateMetadata |
737         DepKind::HirBody |
738         DepKind::Hir |
739
740         // This are anonymous nodes
741         DepKind::TraitSelect |
742
743         // We don't have enough information to reconstruct the query key of
744         // these
745         DepKind::IsCopy |
746         DepKind::IsSized |
747         DepKind::IsFreeze |
748         DepKind::NeedsDrop |
749         DepKind::Layout |
750         DepKind::ConstEval |
751         DepKind::InstanceSymbolName |
752         DepKind::MirShim |
753         DepKind::BorrowCheckKrate |
754         DepKind::Specializes |
755         DepKind::ImplementationsOfTrait |
756         DepKind::TypeParamPredicates |
757         DepKind::CodegenUnit |
758         DepKind::CompileCodegenUnit |
759         DepKind::FulfillObligation |
760         DepKind::VtableMethods |
761         DepKind::EraseRegionsTy |
762         DepKind::NormalizeTy |
763         DepKind::SubstituteNormalizeAndTestPredicates |
764
765         // This one should never occur in this context
766         DepKind::Null => {
767             bug!("force_from_dep_node() - Encountered {:?}", dep_node)
768         }
769
770         // These are not queries
771         DepKind::CoherenceCheckTrait |
772         DepKind::ItemVarianceConstraints => {
773             return false
774         }
775
776         DepKind::RegionScopeTree => { force!(region_scope_tree, def_id!()); }
777
778         DepKind::Coherence => { force!(crate_inherent_impls, LOCAL_CRATE); }
779         DepKind::CoherenceInherentImplOverlapCheck => {
780             force!(crate_inherent_impls_overlap_check, LOCAL_CRATE)
781         },
782         DepKind::PrivacyAccessLevels => { force!(privacy_access_levels, LOCAL_CRATE); }
783         DepKind::MirBuilt => { force!(mir_built, def_id!()); }
784         DepKind::MirConstQualif => { force!(mir_const_qualif, def_id!()); }
785         DepKind::MirConst => { force!(mir_const, def_id!()); }
786         DepKind::MirValidated => { force!(mir_validated, def_id!()); }
787         DepKind::MirOptimized => { force!(optimized_mir, def_id!()); }
788
789         DepKind::BorrowCheck => { force!(borrowck, def_id!()); }
790         DepKind::MirBorrowCheck => { force!(mir_borrowck, def_id!()); }
791         DepKind::UnsafetyCheckResult => { force!(unsafety_check_result, def_id!()); }
792         DepKind::UnsafeDeriveOnReprPacked => { force!(unsafe_derive_on_repr_packed, def_id!()); }
793         DepKind::Reachability => { force!(reachable_set, LOCAL_CRATE); }
794         DepKind::MirKeys => { force!(mir_keys, LOCAL_CRATE); }
795         DepKind::CrateVariances => { force!(crate_variances, LOCAL_CRATE); }
796         DepKind::AssociatedItems => { force!(associated_item, def_id!()); }
797         DepKind::TypeOfItem => { force!(type_of, def_id!()); }
798         DepKind::GenericsOfItem => { force!(generics_of, def_id!()); }
799         DepKind::PredicatesOfItem => { force!(predicates_of, def_id!()); }
800         DepKind::InferredOutlivesOf => { force!(inferred_outlives_of, def_id!()); }
801         DepKind::SuperPredicatesOfItem => { force!(super_predicates_of, def_id!()); }
802         DepKind::TraitDefOfItem => { force!(trait_def, def_id!()); }
803         DepKind::AdtDefOfItem => { force!(adt_def, def_id!()); }
804         DepKind::IsAutoImpl => { force!(is_auto_impl, def_id!()); }
805         DepKind::ImplTraitRef => { force!(impl_trait_ref, def_id!()); }
806         DepKind::ImplPolarity => { force!(impl_polarity, def_id!()); }
807         DepKind::FnSignature => { force!(fn_sig, def_id!()); }
808         DepKind::CoerceUnsizedInfo => { force!(coerce_unsized_info, def_id!()); }
809         DepKind::ItemVariances => { force!(variances_of, def_id!()); }
810         DepKind::IsConstFn => { force!(is_const_fn, def_id!()); }
811         DepKind::IsForeignItem => { force!(is_foreign_item, def_id!()); }
812         DepKind::SizedConstraint => { force!(adt_sized_constraint, def_id!()); }
813         DepKind::DtorckConstraint => { force!(adt_dtorck_constraint, def_id!()); }
814         DepKind::AdtDestructor => { force!(adt_destructor, def_id!()); }
815         DepKind::AssociatedItemDefIds => { force!(associated_item_def_ids, def_id!()); }
816         DepKind::InherentImpls => { force!(inherent_impls, def_id!()); }
817         DepKind::TypeckBodiesKrate => { force!(typeck_item_bodies, LOCAL_CRATE); }
818         DepKind::TypeckTables => { force!(typeck_tables_of, def_id!()); }
819         DepKind::UsedTraitImports => { force!(used_trait_imports, def_id!()); }
820         DepKind::HasTypeckTables => { force!(has_typeck_tables, def_id!()); }
821         DepKind::SymbolName => { force!(def_symbol_name, def_id!()); }
822         DepKind::SpecializationGraph => { force!(specialization_graph_of, def_id!()); }
823         DepKind::ObjectSafety => { force!(is_object_safe, def_id!()); }
824         DepKind::TraitImpls => { force!(trait_impls_of, def_id!()); }
825         DepKind::CheckMatch => { force!(check_match, def_id!()); }
826
827         DepKind::ParamEnv => { force!(param_env, def_id!()); }
828         DepKind::DescribeDef => { force!(describe_def, def_id!()); }
829         DepKind::DefSpan => { force!(def_span, def_id!()); }
830         DepKind::LookupStability => { force!(lookup_stability, def_id!()); }
831         DepKind::LookupDeprecationEntry => {
832             force!(lookup_deprecation_entry, def_id!());
833         }
834         DepKind::ItemBodyNestedBodies => { force!(item_body_nested_bodies, def_id!()); }
835         DepKind::ConstIsRvaluePromotableToStatic => {
836             force!(const_is_rvalue_promotable_to_static, def_id!());
837         }
838         DepKind::RvaluePromotableMap => { force!(rvalue_promotable_map, def_id!()); }
839         DepKind::ImplParent => { force!(impl_parent, def_id!()); }
840         DepKind::TraitOfItem => { force!(trait_of_item, def_id!()); }
841         DepKind::IsExportedSymbol => { force!(is_exported_symbol, def_id!()); }
842         DepKind::IsMirAvailable => { force!(is_mir_available, def_id!()); }
843         DepKind::ItemAttrs => { force!(item_attrs, def_id!()); }
844         DepKind::FnArgNames => { force!(fn_arg_names, def_id!()); }
845         DepKind::DylibDepFormats => { force!(dylib_dependency_formats, krate!()); }
846         DepKind::IsPanicRuntime => { force!(is_panic_runtime, krate!()); }
847         DepKind::IsCompilerBuiltins => { force!(is_compiler_builtins, krate!()); }
848         DepKind::HasGlobalAllocator => { force!(has_global_allocator, krate!()); }
849         DepKind::ExternCrate => { force!(extern_crate, def_id!()); }
850         DepKind::LintLevels => { force!(lint_levels, LOCAL_CRATE); }
851         DepKind::InScopeTraits => { force!(in_scope_traits_map, def_id!().index); }
852         DepKind::ModuleExports => { force!(module_exports, def_id!()); }
853         DepKind::IsSanitizerRuntime => { force!(is_sanitizer_runtime, krate!()); }
854         DepKind::IsProfilerRuntime => { force!(is_profiler_runtime, krate!()); }
855         DepKind::GetPanicStrategy => { force!(panic_strategy, krate!()); }
856         DepKind::IsNoBuiltins => { force!(is_no_builtins, krate!()); }
857         DepKind::ImplDefaultness => { force!(impl_defaultness, def_id!()); }
858         DepKind::ExportedSymbolIds => { force!(exported_symbol_ids, krate!()); }
859         DepKind::NativeLibraries => { force!(native_libraries, krate!()); }
860         DepKind::PluginRegistrarFn => { force!(plugin_registrar_fn, krate!()); }
861         DepKind::DeriveRegistrarFn => { force!(derive_registrar_fn, krate!()); }
862         DepKind::CrateDisambiguator => { force!(crate_disambiguator, krate!()); }
863         DepKind::CrateHash => { force!(crate_hash, krate!()); }
864         DepKind::OriginalCrateName => { force!(original_crate_name, krate!()); }
865
866         DepKind::AllTraitImplementations => {
867             force!(all_trait_implementations, krate!());
868         }
869
870         DepKind::IsDllimportForeignItem => {
871             force!(is_dllimport_foreign_item, def_id!());
872         }
873         DepKind::IsStaticallyIncludedForeignItem => {
874             force!(is_statically_included_foreign_item, def_id!());
875         }
876         DepKind::NativeLibraryKind => { force!(native_library_kind, def_id!()); }
877         DepKind::LinkArgs => { force!(link_args, LOCAL_CRATE); }
878
879         DepKind::ResolveLifetimes => { force!(resolve_lifetimes, krate!()); }
880         DepKind::NamedRegion => { force!(named_region_map, def_id!().index); }
881         DepKind::IsLateBound => { force!(is_late_bound_map, def_id!().index); }
882         DepKind::ObjectLifetimeDefaults => {
883             force!(object_lifetime_defaults_map, def_id!().index);
884         }
885
886         DepKind::Visibility => { force!(visibility, def_id!()); }
887         DepKind::DepKind => { force!(dep_kind, krate!()); }
888         DepKind::CrateName => { force!(crate_name, krate!()); }
889         DepKind::ItemChildren => { force!(item_children, def_id!()); }
890         DepKind::ExternModStmtCnum => { force!(extern_mod_stmt_cnum, def_id!()); }
891         DepKind::GetLangItems => { force!(get_lang_items, LOCAL_CRATE); }
892         DepKind::DefinedLangItems => { force!(defined_lang_items, krate!()); }
893         DepKind::MissingLangItems => { force!(missing_lang_items, krate!()); }
894         DepKind::ExternConstBody => { force!(extern_const_body, def_id!()); }
895         DepKind::VisibleParentMap => { force!(visible_parent_map, LOCAL_CRATE); }
896         DepKind::MissingExternCrateItem => {
897             force!(missing_extern_crate_item, krate!());
898         }
899         DepKind::UsedCrateSource => { force!(used_crate_source, krate!()); }
900         DepKind::PostorderCnums => { force!(postorder_cnums, LOCAL_CRATE); }
901         DepKind::HasCloneClosures => { force!(has_clone_closures, krate!()); }
902         DepKind::HasCopyClosures => { force!(has_copy_closures, krate!()); }
903
904         DepKind::Freevars => { force!(freevars, def_id!()); }
905         DepKind::MaybeUnusedTraitImport => {
906             force!(maybe_unused_trait_import, def_id!());
907         }
908         DepKind::MaybeUnusedExternCrates => { force!(maybe_unused_extern_crates, LOCAL_CRATE); }
909         DepKind::StabilityIndex => { force!(stability_index, LOCAL_CRATE); }
910         DepKind::AllCrateNums => { force!(all_crate_nums, LOCAL_CRATE); }
911         DepKind::ExportedSymbols => { force!(exported_symbols, krate!()); }
912         DepKind::CollectAndPartitionTranslationItems => {
913             force!(collect_and_partition_translation_items, LOCAL_CRATE);
914         }
915         DepKind::ExportName => { force!(export_name, def_id!()); }
916         DepKind::ContainsExternIndicator => {
917             force!(contains_extern_indicator, def_id!());
918         }
919         DepKind::IsTranslatedFunction => { force!(is_translated_function, def_id!()); }
920         DepKind::OutputFilenames => { force!(output_filenames, LOCAL_CRATE); }
921     }
922
923     true
924 }
925
926
927 // FIXME(#45015): Another piece of boilerplate code that could be generated in
928 //                a combined define_dep_nodes!()/define_maps!() macro.
929 macro_rules! impl_load_from_cache {
930     ($($dep_kind:ident => $query_name:ident,)*) => {
931         impl DepNode {
932             // Check whether the query invocation corresponding to the given
933             // DepNode is eligible for on-disk-caching.
934             pub fn cache_on_disk(&self, tcx: TyCtxt) -> bool {
935                 use ty::maps::queries;
936                 use ty::maps::QueryDescription;
937
938                 match self.kind {
939                     $(DepKind::$dep_kind => {
940                         let def_id = self.extract_def_id(tcx).unwrap();
941                         queries::$query_name::cache_on_disk(def_id)
942                     })*
943                     _ => false
944                 }
945             }
946
947             // This is method will execute the query corresponding to the given
948             // DepNode. It is only expected to work for DepNodes where the
949             // above `cache_on_disk` methods returns true.
950             // Also, as a sanity check, it expects that the corresponding query
951             // invocation has been marked as green already.
952             pub fn load_from_on_disk_cache(&self, tcx: TyCtxt) {
953                 match self.kind {
954                     $(DepKind::$dep_kind => {
955                         debug_assert!(tcx.dep_graph
956                                          .node_color(self)
957                                          .map(|c| c.is_green())
958                                          .unwrap_or(false));
959
960                         let def_id = self.extract_def_id(tcx).unwrap();
961                         let _ = tcx.$query_name(def_id);
962                     })*
963                     _ => {
964                         bug!()
965                     }
966                 }
967             }
968         }
969     }
970 }
971
972 impl_load_from_cache!(
973     TypeckTables => typeck_tables_of,
974     MirOptimized => optimized_mir,
975     UnsafetyCheckResult => unsafety_check_result,
976     BorrowCheck => borrowck,
977     MirBorrowCheck => mir_borrowck,
978     MirConstQualif => mir_const_qualif,
979     SymbolName => def_symbol_name,
980     ConstIsRvaluePromotableToStatic => const_is_rvalue_promotable_to_static,
981     ContainsExternIndicator => contains_extern_indicator,
982     CheckMatch => check_match,
983 );