]> git.lizzy.rs Git - rust.git/blob - src/librustc/dep_graph/dep_node.rs
Rollup merge of #59152 - smmalis37:range_contains, r=SimonSapin
[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 crate::mir::interpret::GlobalId;
53 use crate::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX};
54 use crate::hir::map::DefPathHash;
55 use crate::hir::HirId;
56
57 use crate::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 crate::traits;
63 use crate::traits::query::{
64     CanonicalProjectionGoal, CanonicalTyGoal, CanonicalTypeOpAscribeUserTypeGoal,
65     CanonicalTypeOpEqGoal, CanonicalTypeOpSubtypeGoal, CanonicalPredicateGoal,
66     CanonicalTypeOpProvePredicateGoal, CanonicalTypeOpNormalizeGoal,
67 };
68 use crate::ty::{TyCtxt, FnSig, Instance, InstanceDef,
69          ParamEnv, ParamEnvAnd, Predicate, PolyFnSig, PolyTraitRef, Ty};
70 use crate::ty::subst::SubstsRef;
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             /// Creates 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             /// Extracts 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         crate::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 define_dep_nodes!( <'tcx>
427     // We use this for most things when incr. comp. is turned off.
428     [] Null,
429
430     // Represents the `Krate` as a whole (the `hir::Krate` value) (as
431     // distinct from the krate module). This is basically a hash of
432     // the entire krate, so if you read from `Krate` (e.g., by calling
433     // `tcx.hir().krate()`), we will have to assume that any change
434     // means that you need to be recompiled. This is because the
435     // `Krate` value gives you access to all other items. To avoid
436     // this fate, do not call `tcx.hir().krate()`; instead, prefer
437     // wrappers like `tcx.visit_all_items_in_krate()`.  If there is no
438     // suitable wrapper, you can use `tcx.dep_graph.ignore()` to gain
439     // access to the krate, but you must remember to add suitable
440     // edges yourself for the individual items that you read.
441     [input] Krate,
442
443     // Represents the body of a function or method. The def-id is that of the
444     // function/method.
445     [input] HirBody(DefId),
446
447     // Represents the HIR node with the given node-id
448     [input] Hir(DefId),
449
450     // Represents metadata from an extern crate.
451     [input] CrateMetadata(CrateNum),
452
453     // Represents different phases in the compiler.
454     [] RegionScopeTree(DefId),
455     [eval_always] Coherence,
456     [eval_always] CoherenceInherentImplOverlapCheck,
457     [] CoherenceCheckTrait(DefId),
458     [eval_always] PrivacyAccessLevels(CrateNum),
459     [eval_always] CheckPrivateInPublic(CrateNum),
460     [eval_always] Analysis(CrateNum),
461
462     // Represents the MIR for a fn; also used as the task node for
463     // things read/modify that MIR.
464     [] MirConstQualif(DefId),
465     [] MirBuilt(DefId),
466     [] MirConst(DefId),
467     [] MirValidated(DefId),
468     [] MirOptimized(DefId),
469     [] MirShim { instance_def: InstanceDef<'tcx> },
470
471     [] BorrowCheckKrate,
472     [] BorrowCheck(DefId),
473     [] MirBorrowCheck(DefId),
474     [] UnsafetyCheckResult(DefId),
475     [] UnsafeDeriveOnReprPacked(DefId),
476
477     [] CheckModAttrs(DefId),
478     [] CheckModLoops(DefId),
479     [] CheckModUnstableApiUsage(DefId),
480     [] CheckModItemTypes(DefId),
481     [] CheckModPrivacy(DefId),
482     [] CheckModIntrinsics(DefId),
483     [] CheckModLiveness(DefId),
484     [] CheckModImplWf(DefId),
485     [] CollectModItemTypes(DefId),
486
487     [] Reachability,
488     [] MirKeys,
489     [eval_always] CrateVariances,
490
491     // Nodes representing bits of computed IR in the tcx. Each shared
492     // table in the tcx (or elsewhere) maps to one of these
493     // nodes.
494     [] AssociatedItems(DefId),
495     [] TypeOfItem(DefId),
496     [] GenericsOfItem(DefId),
497     [] PredicatesOfItem(DefId),
498     [] ExplicitPredicatesOfItem(DefId),
499     [] PredicatesDefinedOnItem(DefId),
500     [] InferredOutlivesOf(DefId),
501     [] InferredOutlivesCrate(CrateNum),
502     [] SuperPredicatesOfItem(DefId),
503     [] TraitDefOfItem(DefId),
504     [] AdtDefOfItem(DefId),
505     [] ImplTraitRef(DefId),
506     [] ImplPolarity(DefId),
507     [] Issue33140SelfTy(DefId),
508     [] FnSignature(DefId),
509     [] CoerceUnsizedInfo(DefId),
510
511     [] ItemVarianceConstraints(DefId),
512     [] ItemVariances(DefId),
513     [] IsConstFn(DefId),
514     [] IsPromotableConstFn(DefId),
515     [] IsForeignItem(DefId),
516     [] TypeParamPredicates { item_id: DefId, param_id: DefId },
517     [] SizedConstraint(DefId),
518     [] DtorckConstraint(DefId),
519     [] AdtDestructor(DefId),
520     [] AssociatedItemDefIds(DefId),
521     [eval_always] InherentImpls(DefId),
522     [] TypeckBodiesKrate,
523     [] TypeckTables(DefId),
524     [] UsedTraitImports(DefId),
525     [] HasTypeckTables(DefId),
526     [] ConstEval { param_env: ParamEnvAnd<'tcx, GlobalId<'tcx>> },
527     [] ConstEvalRaw { param_env: ParamEnvAnd<'tcx, GlobalId<'tcx>> },
528     [] CheckMatch(DefId),
529     [] SymbolName(DefId),
530     [] InstanceSymbolName { instance: Instance<'tcx> },
531     [] SpecializationGraph(DefId),
532     [] ObjectSafety(DefId),
533     [] FulfillObligation { param_env: ParamEnv<'tcx>, trait_ref: PolyTraitRef<'tcx> },
534     [] VtableMethods { trait_ref: PolyTraitRef<'tcx> },
535
536     [] IsCopy { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
537     [] IsSized { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
538     [] IsFreeze { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
539     [] NeedsDrop { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
540     [] Layout { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
541
542     // The set of impls for a given trait.
543     [] TraitImpls(DefId),
544
545     [input] AllLocalTraitImpls,
546
547     [anon] TraitSelect,
548
549     [] ParamEnv(DefId),
550     [] Environment(DefId),
551     [] DescribeDef(DefId),
552
553     // FIXME(mw): DefSpans are not really inputs since they are derived from
554     // HIR. But at the moment HIR hashing still contains some hacks that allow
555     // to make type debuginfo to be source location independent. Declaring
556     // DefSpan an input makes sure that changes to these are always detected
557     // regardless of HIR hashing.
558     [input] DefSpan(DefId),
559     [] LookupStability(DefId),
560     [] LookupDeprecationEntry(DefId),
561     [] ConstIsRvaluePromotableToStatic(DefId),
562     [] RvaluePromotableMap(DefId),
563     [] ImplParent(DefId),
564     [] TraitOfItem(DefId),
565     [] IsReachableNonGeneric(DefId),
566     [] IsUnreachableLocalDefinition(DefId),
567     [] IsMirAvailable(DefId),
568     [] ItemAttrs(DefId),
569     [] CodegenFnAttrs(DefId),
570     [] FnArgNames(DefId),
571     [] RenderedConst(DefId),
572     [] DylibDepFormats(CrateNum),
573     [] IsPanicRuntime(CrateNum),
574     [] IsCompilerBuiltins(CrateNum),
575     [] HasGlobalAllocator(CrateNum),
576     [] HasPanicHandler(CrateNum),
577     [input] ExternCrate(DefId),
578     [eval_always] LintLevels,
579     [] Specializes { impl1: DefId, impl2: DefId },
580     [input] InScopeTraits(DefIndex),
581     [input] ModuleExports(DefId),
582     [] IsSanitizerRuntime(CrateNum),
583     [] IsProfilerRuntime(CrateNum),
584     [] GetPanicStrategy(CrateNum),
585     [] IsNoBuiltins(CrateNum),
586     [] ImplDefaultness(DefId),
587     [] CheckItemWellFormed(DefId),
588     [] CheckTraitItemWellFormed(DefId),
589     [] CheckImplItemWellFormed(DefId),
590     [] ReachableNonGenerics(CrateNum),
591     [] NativeLibraries(CrateNum),
592     [] EntryFn(CrateNum),
593     [] PluginRegistrarFn(CrateNum),
594     [] ProcMacroDeclsStatic(CrateNum),
595     [input] CrateDisambiguator(CrateNum),
596     [input] CrateHash(CrateNum),
597     [input] OriginalCrateName(CrateNum),
598     [input] ExtraFileName(CrateNum),
599
600     [] ImplementationsOfTrait { krate: CrateNum, trait_id: DefId },
601     [] AllTraitImplementations(CrateNum),
602
603     [] DllimportForeignItems(CrateNum),
604     [] IsDllimportForeignItem(DefId),
605     [] IsStaticallyIncludedForeignItem(DefId),
606     [] NativeLibraryKind(DefId),
607     [input] LinkArgs,
608
609     [] ResolveLifetimes(CrateNum),
610     [] NamedRegion(DefIndex),
611     [] IsLateBound(DefIndex),
612     [] ObjectLifetimeDefaults(DefIndex),
613
614     [] Visibility(DefId),
615     [input] DepKind(CrateNum),
616     [input] CrateName(CrateNum),
617     [] ItemChildren(DefId),
618     [] ExternModStmtCnum(DefId),
619     [eval_always] GetLibFeatures,
620     [] DefinedLibFeatures(CrateNum),
621     [eval_always] GetLangItems,
622     [] DefinedLangItems(CrateNum),
623     [] MissingLangItems(CrateNum),
624     [] VisibleParentMap,
625     [input] MissingExternCrateItem(CrateNum),
626     [input] UsedCrateSource(CrateNum),
627     [input] PostorderCnums,
628
629     // These queries are not expected to have inputs -- as a result, they
630     // are not good candidates for "replay" because they are essentially
631     // pure functions of their input (and hence the expectation is that
632     // no caller would be green **apart** from just these
633     // queries). Making them anonymous avoids hashing the result, which
634     // may save a bit of time.
635     [anon] EraseRegionsTy { ty: Ty<'tcx> },
636
637     [input] Freevars(DefId),
638     [input] MaybeUnusedTraitImport(DefId),
639     [input] MaybeUnusedExternCrates,
640     [input] NamesImportedByGlobUse(DefId),
641     [eval_always] StabilityIndex,
642     [eval_always] AllTraits,
643     [input] AllCrateNums,
644     [] ExportedSymbols(CrateNum),
645     [eval_always] CollectAndPartitionMonoItems,
646     [] IsCodegenedItem(DefId),
647     [] CodegenUnit(InternedString),
648     [] BackendOptimizationLevel(CrateNum),
649     [] CompileCodegenUnit(InternedString),
650     [input] OutputFilenames,
651     [] NormalizeProjectionTy(CanonicalProjectionGoal<'tcx>),
652     [] NormalizeTyAfterErasingRegions(ParamEnvAnd<'tcx, Ty<'tcx>>),
653     [] ImpliedOutlivesBounds(CanonicalTyGoal<'tcx>),
654     [] DropckOutlives(CanonicalTyGoal<'tcx>),
655     [] EvaluateObligation(CanonicalPredicateGoal<'tcx>),
656     [] EvaluateGoal(traits::ChalkCanonicalGoal<'tcx>),
657     [] TypeOpAscribeUserType(CanonicalTypeOpAscribeUserTypeGoal<'tcx>),
658     [] TypeOpEq(CanonicalTypeOpEqGoal<'tcx>),
659     [] TypeOpSubtype(CanonicalTypeOpSubtypeGoal<'tcx>),
660     [] TypeOpProvePredicate(CanonicalTypeOpProvePredicateGoal<'tcx>),
661     [] TypeOpNormalizeTy(CanonicalTypeOpNormalizeGoal<'tcx, Ty<'tcx>>),
662     [] TypeOpNormalizePredicate(CanonicalTypeOpNormalizeGoal<'tcx, Predicate<'tcx>>),
663     [] TypeOpNormalizePolyFnSig(CanonicalTypeOpNormalizeGoal<'tcx, PolyFnSig<'tcx>>),
664     [] TypeOpNormalizeFnSig(CanonicalTypeOpNormalizeGoal<'tcx, FnSig<'tcx>>),
665
666     [] SubstituteNormalizeAndTestPredicates { key: (DefId, SubstsRef<'tcx>) },
667     [] MethodAutoderefSteps(CanonicalTyGoal<'tcx>),
668
669     [input] TargetFeaturesWhitelist,
670
671     [] InstanceDefSizeEstimate { instance_def: InstanceDef<'tcx> },
672
673     [input] Features,
674
675     [] ProgramClausesFor(DefId),
676     [] ProgramClausesForEnv(traits::Environment<'tcx>),
677     [] WasmImportModuleMap(CrateNum),
678     [] ForeignModules(CrateNum),
679
680     [] UpstreamMonomorphizations(CrateNum),
681     [] UpstreamMonomorphizationsFor(DefId),
682 );
683
684 trait DepNodeParams<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> : fmt::Debug {
685     const CAN_RECONSTRUCT_QUERY_KEY: bool;
686
687     /// This method turns the parameters of a DepNodeConstructor into an opaque
688     /// Fingerprint to be used in DepNode.
689     /// Not all DepNodeParams support being turned into a Fingerprint (they
690     /// don't need to if the corresponding DepNode is anonymous).
691     fn to_fingerprint(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> Fingerprint {
692         panic!("Not implemented. Accidentally called on anonymous node?")
693     }
694
695     fn to_debug_str(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> String {
696         format!("{:?}", self)
697     }
698 }
699
700 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a, T> DepNodeParams<'a, 'gcx, 'tcx> for T
701     where T: HashStable<StableHashingContext<'a>> + fmt::Debug
702 {
703     default const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
704
705     default fn to_fingerprint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Fingerprint {
706         let mut hcx = tcx.create_stable_hashing_context();
707         let mut hasher = StableHasher::new();
708
709         self.hash_stable(&mut hcx, &mut hasher);
710
711         hasher.finish()
712     }
713
714     default fn to_debug_str(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> String {
715         format!("{:?}", *self)
716     }
717 }
718
719 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for DefId {
720     const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
721
722     fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
723         tcx.def_path_hash(*self).0
724     }
725
726     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
727         tcx.def_path_str(*self)
728     }
729 }
730
731 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for DefIndex {
732     const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
733
734     fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
735         tcx.hir().definitions().def_path_hash(*self).0
736     }
737
738     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
739         tcx.def_path_str(DefId::local(*self))
740     }
741 }
742
743 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for CrateNum {
744     const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
745
746     fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
747         let def_id = DefId {
748             krate: *self,
749             index: CRATE_DEF_INDEX,
750         };
751         tcx.def_path_hash(def_id).0
752     }
753
754     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
755         tcx.crate_name(*self).as_str().to_string()
756     }
757 }
758
759 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for (DefId, DefId) {
760     const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
761
762     // We actually would not need to specialize the implementation of this
763     // method but it's faster to combine the hashes than to instantiate a full
764     // hashing context and stable-hashing state.
765     fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
766         let (def_id_0, def_id_1) = *self;
767
768         let def_path_hash_0 = tcx.def_path_hash(def_id_0);
769         let def_path_hash_1 = tcx.def_path_hash(def_id_1);
770
771         def_path_hash_0.0.combine(def_path_hash_1.0)
772     }
773
774     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
775         let (def_id_0, def_id_1) = *self;
776
777         format!("({}, {})",
778                 tcx.def_path_debug_str(def_id_0),
779                 tcx.def_path_debug_str(def_id_1))
780     }
781 }
782
783 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for HirId {
784     const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
785
786     // We actually would not need to specialize the implementation of this
787     // method but it's faster to combine the hashes than to instantiate a full
788     // hashing context and stable-hashing state.
789     fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
790         let HirId {
791             owner,
792             local_id,
793         } = *self;
794
795         let def_path_hash = tcx.def_path_hash(DefId::local(owner));
796         let local_id = Fingerprint::from_smaller_hash(local_id.as_u32().into());
797
798         def_path_hash.0.combine(local_id)
799     }
800 }
801
802 /// A "work product" corresponds to a `.o` (or other) file that we
803 /// save in between runs. These IDs do not have a `DefId` but rather
804 /// some independent path or string that persists between runs without
805 /// the need to be mapped or unmapped. (This ensures we can serialize
806 /// them even in the absence of a tcx.)
807 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
808          RustcEncodable, RustcDecodable)]
809 pub struct WorkProductId {
810     hash: Fingerprint
811 }
812
813 impl WorkProductId {
814     pub fn from_cgu_name(cgu_name: &str) -> WorkProductId {
815         let mut hasher = StableHasher::new();
816         cgu_name.len().hash(&mut hasher);
817         cgu_name.hash(&mut hasher);
818         WorkProductId {
819             hash: hasher.finish()
820         }
821     }
822
823     pub fn from_fingerprint(fingerprint: Fingerprint) -> WorkProductId {
824         WorkProductId {
825             hash: fingerprint
826         }
827     }
828 }
829
830 impl_stable_hash_for!(struct crate::dep_graph::WorkProductId {
831     hash
832 });