]> git.lizzy.rs Git - rust.git/blob - src/librustc/dep_graph/dep_node.rs
e5fd0aa3c9cbd8d8af9d26d7a854d1504048c0d4
[rust.git] / src / librustc / dep_graph / dep_node.rs
1 //! This module defines the `DepNode` type which the compiler uses to represent
2 //! nodes in the dependency graph. A `DepNode` consists of a `DepKind` (which
3 //! specifies the kind of thing it represents, like a piece of HIR, MIR, etc)
4 //! and a `Fingerprint`, a 128 bit hash value the exact meaning of which
5 //! depends on the node's `DepKind`. Together, the kind and the fingerprint
6 //! fully identify a dependency node, even across multiple compilation sessions.
7 //! In other words, the value of the fingerprint does not depend on anything
8 //! that is specific to a given compilation session, like an unpredictable
9 //! interning key (e.g., NodeId, DefId, Symbol) or the numeric value of a
10 //! pointer. The concept behind this could be compared to how git commit hashes
11 //! uniquely identify a given commit and has a few advantages:
12 //!
13 //! * A `DepNode` can simply be serialized to disk and loaded in another session
14 //!   without the need to do any "rebasing (like we have to do for Spans and
15 //!   NodeIds) or "retracing" like we had to do for `DefId` in earlier
16 //!   implementations of the dependency graph.
17 //! * A `Fingerprint` is just a bunch of bits, which allows `DepNode` to
18 //!   implement `Copy`, `Sync`, `Send`, `Freeze`, etc.
19 //! * Since we just have a bit pattern, `DepNode` can be mapped from disk into
20 //!   memory without any post-processing (e.g., "abomination-style" pointer
21 //!   reconstruction).
22 //! * Because a `DepNode` is self-contained, we can instantiate `DepNodes` that
23 //!   refer to things that do not exist anymore. In previous implementations
24 //!   `DepNode` contained a `DefId`. A `DepNode` referring to something that
25 //!   had been removed between the previous and the current compilation session
26 //!   could not be instantiated because the current compilation session
27 //!   contained no `DefId` for thing that had been removed.
28 //!
29 //! `DepNode` definition happens in the `define_dep_nodes!()` macro. This macro
30 //! defines the `DepKind` enum and a corresponding `DepConstructor` enum. The
31 //! `DepConstructor` enum links a `DepKind` to the parameters that are needed at
32 //! runtime in order to construct a valid `DepNode` fingerprint.
33 //!
34 //! Because the macro sees what parameters a given `DepKind` requires, it can
35 //! "infer" some properties for each kind of `DepNode`:
36 //!
37 //! * Whether a `DepNode` of a given kind has any parameters at all. Some
38 //!   `DepNode`s, like `Krate`, represent global concepts with only one value.
39 //! * Whether it is possible, in principle, to reconstruct a query key from a
40 //!   given `DepNode`. Many `DepKind`s only require a single `DefId` parameter,
41 //!   in which case it is possible to map the node's fingerprint back to the
42 //!   `DefId` it was computed from. In other cases, too much information gets
43 //!   lost during fingerprint computation.
44 //!
45 //! The `DepConstructor` enum, together with `DepNode::new()` ensures that only
46 //! valid `DepNode` instances can be constructed. For example, the API does not
47 //! allow for constructing parameterless `DepNode`s with anything other
48 //! than a zeroed out fingerprint. More generally speaking, it relieves the
49 //! user of the `DepNode` API of having to know how to compute the expected
50 //! fingerprint for a given set of node parameters.
51
52 use mir::interpret::GlobalId;
53 use hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX};
54 use hir::map::DefPathHash;
55 use hir::HirId;
56
57 use ich::{Fingerprint, StableHashingContext};
58 use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
59 use std::fmt;
60 use std::hash::Hash;
61 use syntax_pos::symbol::InternedString;
62 use traits;
63 use traits::query::{
64     CanonicalProjectionGoal, CanonicalTyGoal, CanonicalTypeOpAscribeUserTypeGoal,
65     CanonicalTypeOpEqGoal, CanonicalTypeOpSubtypeGoal, CanonicalPredicateGoal,
66     CanonicalTypeOpProvePredicateGoal, CanonicalTypeOpNormalizeGoal,
67 };
68 use ty::{TyCtxt, FnSig, Instance, InstanceDef,
69          ParamEnv, ParamEnvAnd, Predicate, PolyFnSig, PolyTraitRef, Ty};
70 use ty::subst::Substs;
71
72 // erase!() just makes tokens go away. It's used to specify which macro argument
73 // is repeated (i.e., which sub-expression of the macro we are in) but don't need
74 // to actually use any of the arguments.
75 macro_rules! erase {
76     ($x:tt) => ({})
77 }
78
79 macro_rules! replace {
80     ($x:tt with $($y:tt)*) => ($($y)*)
81 }
82
83 macro_rules! is_anon_attr {
84     (anon) => (true);
85     ($attr:ident) => (false);
86 }
87
88 macro_rules! is_input_attr {
89     (input) => (true);
90     ($attr:ident) => (false);
91 }
92
93 macro_rules! is_eval_always_attr {
94     (eval_always) => (true);
95     ($attr:ident) => (false);
96 }
97
98 macro_rules! contains_anon_attr {
99     ($($attr:ident),*) => ({$(is_anon_attr!($attr) | )* false});
100 }
101
102 macro_rules! contains_input_attr {
103     ($($attr:ident),*) => ({$(is_input_attr!($attr) | )* false});
104 }
105
106 macro_rules! contains_eval_always_attr {
107     ($($attr:ident),*) => ({$(is_eval_always_attr!($attr) | )* false});
108 }
109
110 macro_rules! define_dep_nodes {
111     (<$tcx:tt>
112     $(
113         [$($attr:ident),* ]
114         $variant:ident $(( $tuple_arg_ty:ty $(,)* ))*
115                        $({ $($struct_arg_name:ident : $struct_arg_ty:ty),* })*
116       ,)*
117     ) => (
118         #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
119                  RustcEncodable, RustcDecodable)]
120         pub enum DepKind {
121             $($variant),*
122         }
123
124         impl DepKind {
125             #[allow(unreachable_code)]
126             #[inline]
127             pub fn can_reconstruct_query_key<$tcx>(&self) -> bool {
128                 match *self {
129                     $(
130                         DepKind :: $variant => {
131                             if contains_anon_attr!($($attr),*) {
132                                 return false;
133                             }
134
135                             // tuple args
136                             $({
137                                 return <$tuple_arg_ty as DepNodeParams>
138                                     ::CAN_RECONSTRUCT_QUERY_KEY;
139                             })*
140
141                             // struct args
142                             $({
143
144                                 return <( $($struct_arg_ty,)* ) as DepNodeParams>
145                                     ::CAN_RECONSTRUCT_QUERY_KEY;
146                             })*
147
148                             true
149                         }
150                     )*
151                 }
152             }
153
154             // FIXME: Make `is_anon`, `is_input`, `is_eval_always` and `has_params` properties
155             // of queries
156             #[inline(always)]
157             pub fn is_anon(&self) -> bool {
158                 match *self {
159                     $(
160                         DepKind :: $variant => { contains_anon_attr!($($attr),*) }
161                     )*
162                 }
163             }
164
165             #[inline(always)]
166             pub fn is_input(&self) -> bool {
167                 match *self {
168                     $(
169                         DepKind :: $variant => { contains_input_attr!($($attr),*) }
170                     )*
171                 }
172             }
173
174             #[inline(always)]
175             pub fn is_eval_always(&self) -> bool {
176                 match *self {
177                     $(
178                         DepKind :: $variant => { contains_eval_always_attr!($($attr), *) }
179                     )*
180                 }
181             }
182
183             #[allow(unreachable_code)]
184             #[inline(always)]
185             pub fn has_params(&self) -> bool {
186                 match *self {
187                     $(
188                         DepKind :: $variant => {
189                             // tuple args
190                             $({
191                                 erase!($tuple_arg_ty);
192                                 return true;
193                             })*
194
195                             // struct args
196                             $({
197                                 $(erase!($struct_arg_name);)*
198                                 return true;
199                             })*
200
201                             false
202                         }
203                     )*
204                 }
205             }
206         }
207
208         pub enum DepConstructor<$tcx> {
209             $(
210                 $variant $(( $tuple_arg_ty ))*
211                          $({ $($struct_arg_name : $struct_arg_ty),* })*
212             ),*
213         }
214
215         #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash,
216                  RustcEncodable, RustcDecodable)]
217         pub struct DepNode {
218             pub kind: DepKind,
219             pub hash: Fingerprint,
220         }
221
222         impl DepNode {
223             #[allow(unreachable_code, non_snake_case)]
224             #[inline(always)]
225             pub fn new<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
226                                        dep: DepConstructor<'gcx>)
227                                        -> DepNode
228                 where 'gcx: 'a + 'tcx,
229                       'tcx: 'a
230             {
231                 match dep {
232                     $(
233                         DepConstructor :: $variant $(( replace!(($tuple_arg_ty) with arg) ))*
234                                                    $({ $($struct_arg_name),* })*
235                             =>
236                         {
237                             // tuple args
238                             $({
239                                 erase!($tuple_arg_ty);
240                                 let hash = DepNodeParams::to_fingerprint(&arg, tcx);
241                                 let dep_node = DepNode {
242                                     kind: DepKind::$variant,
243                                     hash
244                                 };
245
246                                 if cfg!(debug_assertions) &&
247                                    !dep_node.kind.can_reconstruct_query_key() &&
248                                    (tcx.sess.opts.debugging_opts.incremental_info ||
249                                     tcx.sess.opts.debugging_opts.query_dep_graph)
250                                 {
251                                     tcx.dep_graph.register_dep_node_debug_str(dep_node, || {
252                                         arg.to_debug_str(tcx)
253                                     });
254                                 }
255
256                                 return dep_node;
257                             })*
258
259                             // struct args
260                             $({
261                                 let tupled_args = ( $($struct_arg_name,)* );
262                                 let hash = DepNodeParams::to_fingerprint(&tupled_args,
263                                                                          tcx);
264                                 let dep_node = DepNode {
265                                     kind: DepKind::$variant,
266                                     hash
267                                 };
268
269                                 if cfg!(debug_assertions) &&
270                                    !dep_node.kind.can_reconstruct_query_key() &&
271                                    (tcx.sess.opts.debugging_opts.incremental_info ||
272                                     tcx.sess.opts.debugging_opts.query_dep_graph)
273                                 {
274                                     tcx.dep_graph.register_dep_node_debug_str(dep_node, || {
275                                         tupled_args.to_debug_str(tcx)
276                                     });
277                                 }
278
279                                 return dep_node;
280                             })*
281
282                             DepNode {
283                                 kind: DepKind::$variant,
284                                 hash: Fingerprint::ZERO,
285                             }
286                         }
287                     )*
288                 }
289             }
290
291             /// Construct a DepNode from the given DepKind and DefPathHash. This
292             /// method will assert that the given DepKind actually requires a
293             /// single DefId/DefPathHash parameter.
294             #[inline(always)]
295             pub fn from_def_path_hash(kind: DepKind,
296                                       def_path_hash: DefPathHash)
297                                       -> DepNode {
298                 debug_assert!(kind.can_reconstruct_query_key() && kind.has_params());
299                 DepNode {
300                     kind,
301                     hash: def_path_hash.0,
302                 }
303             }
304
305             /// Create a new, parameterless DepNode. This method will assert
306             /// that the DepNode corresponding to the given DepKind actually
307             /// does not require any parameters.
308             #[inline(always)]
309             pub fn new_no_params(kind: DepKind) -> DepNode {
310                 debug_assert!(!kind.has_params());
311                 DepNode {
312                     kind,
313                     hash: Fingerprint::ZERO,
314                 }
315             }
316
317             /// Extract the DefId corresponding to this DepNode. This will work
318             /// if two conditions are met:
319             ///
320             /// 1. The Fingerprint of the DepNode actually is a DefPathHash, and
321             /// 2. the item that the DefPath refers to exists in the current tcx.
322             ///
323             /// Condition (1) is determined by the DepKind variant of the
324             /// DepNode. Condition (2) might not be fulfilled if a DepNode
325             /// refers to something from the previous compilation session that
326             /// has been removed.
327             #[inline]
328             pub fn extract_def_id(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<DefId> {
329                 if self.kind.can_reconstruct_query_key() {
330                     let def_path_hash = DefPathHash(self.hash);
331                     tcx.def_path_hash_to_def_id.as_ref()?
332                         .get(&def_path_hash).cloned()
333                 } else {
334                     None
335                 }
336             }
337
338             /// Used in testing
339             pub fn from_label_string(label: &str,
340                                      def_path_hash: DefPathHash)
341                                      -> Result<DepNode, ()> {
342                 let kind = match label {
343                     $(
344                         stringify!($variant) => DepKind::$variant,
345                     )*
346                     _ => return Err(()),
347                 };
348
349                 if !kind.can_reconstruct_query_key() {
350                     return Err(());
351                 }
352
353                 if kind.has_params() {
354                     Ok(def_path_hash.to_dep_node(kind))
355                 } else {
356                     Ok(DepNode::new_no_params(kind))
357                 }
358             }
359
360             /// Used in testing
361             pub fn has_label_string(label: &str) -> bool {
362                 match label {
363                     $(
364                         stringify!($variant) => true,
365                     )*
366                     _ => false,
367                 }
368             }
369         }
370
371         /// Contains variant => str representations for constructing
372         /// DepNode groups for tests.
373         #[allow(dead_code, non_upper_case_globals)]
374         pub mod label_strs {
375            $(
376                 pub const $variant: &str = stringify!($variant);
377             )*
378         }
379     );
380 }
381
382 impl fmt::Debug for DepNode {
383     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384         write!(f, "{:?}", self.kind)?;
385
386         if !self.kind.has_params() && !self.kind.is_anon() {
387             return Ok(());
388         }
389
390         write!(f, "(")?;
391
392         ::ty::tls::with_opt(|opt_tcx| {
393             if let Some(tcx) = opt_tcx {
394                 if let Some(def_id) = self.extract_def_id(tcx) {
395                     write!(f, "{}", tcx.def_path_debug_str(def_id))?;
396                 } else if let Some(ref s) = tcx.dep_graph.dep_node_debug_str(*self) {
397                     write!(f, "{}", s)?;
398                 } else {
399                     write!(f, "{}", self.hash)?;
400                 }
401             } else {
402                 write!(f, "{}", self.hash)?;
403             }
404             Ok(())
405         })?;
406
407         write!(f, ")")
408     }
409 }
410
411
412 impl DefPathHash {
413     #[inline(always)]
414     pub fn to_dep_node(self, kind: DepKind) -> DepNode {
415         DepNode::from_def_path_hash(kind, self)
416     }
417 }
418
419 impl DefId {
420     #[inline(always)]
421     pub fn to_dep_node(self, tcx: TyCtxt<'_, '_, '_>, kind: DepKind) -> DepNode {
422         DepNode::from_def_path_hash(kind, tcx.def_path_hash(self))
423     }
424 }
425
426 impl DepKind {
427     #[inline]
428     pub fn fingerprint_needed_for_crate_hash(self) -> bool {
429         match self {
430             DepKind::HirBody |
431             DepKind::Krate => true,
432             _ => false,
433         }
434     }
435 }
436
437 define_dep_nodes!( <'tcx>
438     // We use this for most things when incr. comp. is turned off.
439     [] Null,
440
441     // Represents the `Krate` as a whole (the `hir::Krate` value) (as
442     // distinct from the krate module). This is basically a hash of
443     // the entire krate, so if you read from `Krate` (e.g., by calling
444     // `tcx.hir().krate()`), we will have to assume that any change
445     // means that you need to be recompiled. This is because the
446     // `Krate` value gives you access to all other items. To avoid
447     // this fate, do not call `tcx.hir().krate()`; instead, prefer
448     // wrappers like `tcx.visit_all_items_in_krate()`.  If there is no
449     // suitable wrapper, you can use `tcx.dep_graph.ignore()` to gain
450     // access to the krate, but you must remember to add suitable
451     // edges yourself for the individual items that you read.
452     [input] Krate,
453
454     // Represents the body of a function or method. The def-id is that of the
455     // function/method.
456     [input] HirBody(DefId),
457
458     // Represents the HIR node with the given node-id
459     [input] Hir(DefId),
460
461     // Represents metadata from an extern crate.
462     [input] CrateMetadata(CrateNum),
463
464     // Represents different phases in the compiler.
465     [] RegionScopeTree(DefId),
466     [eval_always] Coherence,
467     [eval_always] CoherenceInherentImplOverlapCheck,
468     [] CoherenceCheckTrait(DefId),
469     [eval_always] PrivacyAccessLevels(CrateNum),
470
471     // Represents the MIR for a fn; also used as the task node for
472     // things read/modify that MIR.
473     [] MirConstQualif(DefId),
474     [] MirBuilt(DefId),
475     [] MirConst(DefId),
476     [] MirValidated(DefId),
477     [] MirOptimized(DefId),
478     [] MirShim { instance_def: InstanceDef<'tcx> },
479
480     [] BorrowCheckKrate,
481     [] BorrowCheck(DefId),
482     [] MirBorrowCheck(DefId),
483     [] UnsafetyCheckResult(DefId),
484     [] UnsafeDeriveOnReprPacked(DefId),
485
486     [] Reachability,
487     [] MirKeys,
488     [eval_always] CrateVariances,
489
490     // Nodes representing bits of computed IR in the tcx. Each shared
491     // table in the tcx (or elsewhere) maps to one of these
492     // nodes.
493     [] AssociatedItems(DefId),
494     [] TypeOfItem(DefId),
495     [] GenericsOfItem(DefId),
496     [] PredicatesOfItem(DefId),
497     [] ExplicitPredicatesOfItem(DefId),
498     [] PredicatesDefinedOnItem(DefId),
499     [] InferredOutlivesOf(DefId),
500     [] InferredOutlivesCrate(CrateNum),
501     [] SuperPredicatesOfItem(DefId),
502     [] TraitDefOfItem(DefId),
503     [] AdtDefOfItem(DefId),
504     [] ImplTraitRef(DefId),
505     [] ImplPolarity(DefId),
506     [] FnSignature(DefId),
507     [] CoerceUnsizedInfo(DefId),
508
509     [] ItemVarianceConstraints(DefId),
510     [] ItemVariances(DefId),
511     [] IsConstFn(DefId),
512     [] IsPromotableConstFn(DefId),
513     [] IsForeignItem(DefId),
514     [] TypeParamPredicates { item_id: DefId, param_id: DefId },
515     [] SizedConstraint(DefId),
516     [] DtorckConstraint(DefId),
517     [] AdtDestructor(DefId),
518     [] AssociatedItemDefIds(DefId),
519     [eval_always] InherentImpls(DefId),
520     [] TypeckBodiesKrate,
521     [] TypeckTables(DefId),
522     [] UsedTraitImports(DefId),
523     [] HasTypeckTables(DefId),
524     [] ConstEval { param_env: ParamEnvAnd<'tcx, GlobalId<'tcx>> },
525     [] ConstEvalRaw { param_env: ParamEnvAnd<'tcx, GlobalId<'tcx>> },
526     [] CheckMatch(DefId),
527     [] SymbolName(DefId),
528     [] InstanceSymbolName { instance: Instance<'tcx> },
529     [] SpecializationGraph(DefId),
530     [] ObjectSafety(DefId),
531     [] FulfillObligation { param_env: ParamEnv<'tcx>, trait_ref: PolyTraitRef<'tcx> },
532     [] VtableMethods { trait_ref: PolyTraitRef<'tcx> },
533
534     [] IsCopy { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
535     [] IsSized { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
536     [] IsFreeze { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
537     [] NeedsDrop { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
538     [] Layout { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
539
540     // The set of impls for a given trait.
541     [] TraitImpls(DefId),
542
543     [input] AllLocalTraitImpls,
544
545     [anon] TraitSelect,
546
547     [] ParamEnv(DefId),
548     [] Environment(DefId),
549     [] DescribeDef(DefId),
550
551     // FIXME(mw): DefSpans are not really inputs since they are derived from
552     // HIR. But at the moment HIR hashing still contains some hacks that allow
553     // to make type debuginfo to be source location independent. Declaring
554     // DefSpan an input makes sure that changes to these are always detected
555     // regardless of HIR hashing.
556     [input] DefSpan(DefId),
557     [] LookupStability(DefId),
558     [] LookupDeprecationEntry(DefId),
559     [] ConstIsRvaluePromotableToStatic(DefId),
560     [] RvaluePromotableMap(DefId),
561     [] ImplParent(DefId),
562     [] TraitOfItem(DefId),
563     [] IsReachableNonGeneric(DefId),
564     [] IsUnreachableLocalDefinition(DefId),
565     [] IsMirAvailable(DefId),
566     [] ItemAttrs(DefId),
567     [] CodegenFnAttrs(DefId),
568     [] FnArgNames(DefId),
569     [] RenderedConst(DefId),
570     [] DylibDepFormats(CrateNum),
571     [] IsPanicRuntime(CrateNum),
572     [] IsCompilerBuiltins(CrateNum),
573     [] HasGlobalAllocator(CrateNum),
574     [] HasPanicHandler(CrateNum),
575     [input] ExternCrate(DefId),
576     [eval_always] LintLevels,
577     [] Specializes { impl1: DefId, impl2: DefId },
578     [input] InScopeTraits(DefIndex),
579     [input] ModuleExports(DefId),
580     [] IsSanitizerRuntime(CrateNum),
581     [] IsProfilerRuntime(CrateNum),
582     [] GetPanicStrategy(CrateNum),
583     [] IsNoBuiltins(CrateNum),
584     [] ImplDefaultness(DefId),
585     [] CheckItemWellFormed(DefId),
586     [] CheckTraitItemWellFormed(DefId),
587     [] CheckImplItemWellFormed(DefId),
588     [] ReachableNonGenerics(CrateNum),
589     [] NativeLibraries(CrateNum),
590     [] PluginRegistrarFn(CrateNum),
591     [] ProcMacroDeclsStatic(CrateNum),
592     [input] CrateDisambiguator(CrateNum),
593     [input] CrateHash(CrateNum),
594     [input] OriginalCrateName(CrateNum),
595     [input] ExtraFileName(CrateNum),
596
597     [] ImplementationsOfTrait { krate: CrateNum, trait_id: DefId },
598     [] AllTraitImplementations(CrateNum),
599
600     [] DllimportForeignItems(CrateNum),
601     [] IsDllimportForeignItem(DefId),
602     [] IsStaticallyIncludedForeignItem(DefId),
603     [] NativeLibraryKind(DefId),
604     [input] LinkArgs,
605
606     [] ResolveLifetimes(CrateNum),
607     [] NamedRegion(DefIndex),
608     [] IsLateBound(DefIndex),
609     [] ObjectLifetimeDefaults(DefIndex),
610
611     [] Visibility(DefId),
612     [input] DepKind(CrateNum),
613     [input] CrateName(CrateNum),
614     [] ItemChildren(DefId),
615     [] ExternModStmtCnum(DefId),
616     [eval_always] GetLibFeatures,
617     [] DefinedLibFeatures(CrateNum),
618     [eval_always] GetLangItems,
619     [] DefinedLangItems(CrateNum),
620     [] MissingLangItems(CrateNum),
621     [] VisibleParentMap,
622     [input] MissingExternCrateItem(CrateNum),
623     [input] UsedCrateSource(CrateNum),
624     [input] PostorderCnums,
625
626     // These queries are not expected to have inputs -- as a result, they
627     // are not good candidates for "replay" because they are essentially
628     // pure functions of their input (and hence the expectation is that
629     // no caller would be green **apart** from just these
630     // queries). Making them anonymous avoids hashing the result, which
631     // may save a bit of time.
632     [anon] EraseRegionsTy { ty: Ty<'tcx> },
633
634     [input] Freevars(DefId),
635     [input] MaybeUnusedTraitImport(DefId),
636     [input] MaybeUnusedExternCrates,
637     [eval_always] StabilityIndex,
638     [eval_always] AllTraits,
639     [input] AllCrateNums,
640     [] ExportedSymbols(CrateNum),
641     [eval_always] CollectAndPartitionMonoItems,
642     [] IsCodegenedItem(DefId),
643     [] CodegenUnit(InternedString),
644     [] CompileCodegenUnit(InternedString),
645     [input] OutputFilenames,
646     [] NormalizeProjectionTy(CanonicalProjectionGoal<'tcx>),
647     [] NormalizeTyAfterErasingRegions(ParamEnvAnd<'tcx, Ty<'tcx>>),
648     [] ImpliedOutlivesBounds(CanonicalTyGoal<'tcx>),
649     [] DropckOutlives(CanonicalTyGoal<'tcx>),
650     [] EvaluateObligation(CanonicalPredicateGoal<'tcx>),
651     [] EvaluateGoal(traits::ChalkCanonicalGoal<'tcx>),
652     [] TypeOpAscribeUserType(CanonicalTypeOpAscribeUserTypeGoal<'tcx>),
653     [] TypeOpEq(CanonicalTypeOpEqGoal<'tcx>),
654     [] TypeOpSubtype(CanonicalTypeOpSubtypeGoal<'tcx>),
655     [] TypeOpProvePredicate(CanonicalTypeOpProvePredicateGoal<'tcx>),
656     [] TypeOpNormalizeTy(CanonicalTypeOpNormalizeGoal<'tcx, Ty<'tcx>>),
657     [] TypeOpNormalizePredicate(CanonicalTypeOpNormalizeGoal<'tcx, Predicate<'tcx>>),
658     [] TypeOpNormalizePolyFnSig(CanonicalTypeOpNormalizeGoal<'tcx, PolyFnSig<'tcx>>),
659     [] TypeOpNormalizeFnSig(CanonicalTypeOpNormalizeGoal<'tcx, FnSig<'tcx>>),
660
661     [] SubstituteNormalizeAndTestPredicates { key: (DefId, &'tcx Substs<'tcx>) },
662     [] MethodAutoderefSteps(CanonicalTyGoal<'tcx>),
663
664     [input] TargetFeaturesWhitelist,
665
666     [] InstanceDefSizeEstimate { instance_def: InstanceDef<'tcx> },
667
668     [input] Features,
669
670     [] ProgramClausesFor(DefId),
671     [] ProgramClausesForEnv(traits::Environment<'tcx>),
672     [] WasmImportModuleMap(CrateNum),
673     [] ForeignModules(CrateNum),
674
675     [] UpstreamMonomorphizations(CrateNum),
676     [] UpstreamMonomorphizationsFor(DefId),
677 );
678
679 trait DepNodeParams<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> : fmt::Debug {
680     const CAN_RECONSTRUCT_QUERY_KEY: bool;
681
682     /// This method turns the parameters of a DepNodeConstructor into an opaque
683     /// Fingerprint to be used in DepNode.
684     /// Not all DepNodeParams support being turned into a Fingerprint (they
685     /// don't need to if the corresponding DepNode is anonymous).
686     fn to_fingerprint(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> Fingerprint {
687         panic!("Not implemented. Accidentally called on anonymous node?")
688     }
689
690     fn to_debug_str(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> String {
691         format!("{:?}", self)
692     }
693 }
694
695 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a, T> DepNodeParams<'a, 'gcx, 'tcx> for T
696     where T: HashStable<StableHashingContext<'a>> + fmt::Debug
697 {
698     default const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
699
700     default fn to_fingerprint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Fingerprint {
701         let mut hcx = tcx.create_stable_hashing_context();
702         let mut hasher = StableHasher::new();
703
704         self.hash_stable(&mut hcx, &mut hasher);
705
706         hasher.finish()
707     }
708
709     default fn to_debug_str(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> String {
710         format!("{:?}", *self)
711     }
712 }
713
714 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for DefId {
715     const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
716
717     fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
718         tcx.def_path_hash(*self).0
719     }
720
721     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
722         tcx.item_path_str(*self)
723     }
724 }
725
726 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for DefIndex {
727     const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
728
729     fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
730         tcx.hir().definitions().def_path_hash(*self).0
731     }
732
733     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
734         tcx.item_path_str(DefId::local(*self))
735     }
736 }
737
738 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for CrateNum {
739     const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
740
741     fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
742         let def_id = DefId {
743             krate: *self,
744             index: CRATE_DEF_INDEX,
745         };
746         tcx.def_path_hash(def_id).0
747     }
748
749     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
750         tcx.crate_name(*self).as_str().to_string()
751     }
752 }
753
754 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for (DefId, DefId) {
755     const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
756
757     // We actually would not need to specialize the implementation of this
758     // method but it's faster to combine the hashes than to instantiate a full
759     // hashing context and stable-hashing state.
760     fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
761         let (def_id_0, def_id_1) = *self;
762
763         let def_path_hash_0 = tcx.def_path_hash(def_id_0);
764         let def_path_hash_1 = tcx.def_path_hash(def_id_1);
765
766         def_path_hash_0.0.combine(def_path_hash_1.0)
767     }
768
769     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
770         let (def_id_0, def_id_1) = *self;
771
772         format!("({}, {})",
773                 tcx.def_path_debug_str(def_id_0),
774                 tcx.def_path_debug_str(def_id_1))
775     }
776 }
777
778 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for HirId {
779     const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
780
781     // We actually would not need to specialize the implementation of this
782     // method but it's faster to combine the hashes than to instantiate a full
783     // hashing context and stable-hashing state.
784     fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
785         let HirId {
786             owner,
787             local_id,
788         } = *self;
789
790         let def_path_hash = tcx.def_path_hash(DefId::local(owner));
791         let local_id = Fingerprint::from_smaller_hash(local_id.as_u32().into());
792
793         def_path_hash.0.combine(local_id)
794     }
795 }
796
797 /// A "work product" corresponds to a `.o` (or other) file that we
798 /// save in between runs. These ids do not have a DefId but rather
799 /// some independent path or string that persists between runs without
800 /// the need to be mapped or unmapped. (This ensures we can serialize
801 /// them even in the absence of a tcx.)
802 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
803          RustcEncodable, RustcDecodable)]
804 pub struct WorkProductId {
805     hash: Fingerprint
806 }
807
808 impl WorkProductId {
809     pub fn from_cgu_name(cgu_name: &str) -> WorkProductId {
810         let mut hasher = StableHasher::new();
811         cgu_name.len().hash(&mut hasher);
812         cgu_name.hash(&mut hasher);
813         WorkProductId {
814             hash: hasher.finish()
815         }
816     }
817
818     pub fn from_fingerprint(fingerprint: Fingerprint) -> WorkProductId {
819         WorkProductId {
820             hash: fingerprint
821         }
822     }
823 }
824
825 impl_stable_hash_for!(struct ::dep_graph::WorkProductId {
826     hash
827 });