]> git.lizzy.rs Git - rust.git/blob - src/librustc_incremental/calculate_svh/mod.rs
Auto merge of #41684 - jethrogb:feature/ntstatus, r=alexcrichton
[rust.git] / src / librustc_incremental / calculate_svh / mod.rs
1 // Copyright 2012-2014 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 //! Calculation of the (misnamed) "strict version hash" for crates and
12 //! items. This hash is used to tell when the HIR changed in such a
13 //! way that results from previous compilations may no longer be
14 //! applicable and hence must be recomputed. It should probably be
15 //! renamed to the ICH (incremental compilation hash).
16 //!
17 //! The hashes for all items are computed once at the beginning of
18 //! compilation and stored into a map. In addition, a hash is computed
19 //! of the **entire crate**.
20 //!
21 //! Storing the hashes in a map avoids the need to compute them twice
22 //! (once when loading prior incremental results and once when
23 //! saving), but it is also important for correctness: at least as of
24 //! the time of this writing, the typeck passes rewrites entries in
25 //! the dep-map in-place to accommodate UFCS resolutions. Since name
26 //! resolution is part of the hash, the result is that hashes computed
27 //! at the end of compilation would be different from those computed
28 //! at the beginning.
29
30 use std::cell::RefCell;
31 use std::hash::Hash;
32 use std::sync::Arc;
33 use rustc::dep_graph::DepNode;
34 use rustc::hir;
35 use rustc::hir::def_id::{LOCAL_CRATE, CRATE_DEF_INDEX, DefId};
36 use rustc::hir::itemlikevisit::ItemLikeVisitor;
37 use rustc::ich::{Fingerprint, StableHashingContext};
38 use rustc::ty::TyCtxt;
39 use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
40 use rustc_data_structures::fx::FxHashMap;
41 use rustc::util::common::record_time;
42
43 pub type IchHasher = StableHasher<Fingerprint>;
44
45 pub struct IncrementalHashesMap {
46     hashes: FxHashMap<DepNode<DefId>, Fingerprint>,
47
48     // These are the metadata hashes for the current crate as they were stored
49     // during the last compilation session. They are only loaded if
50     // -Z query-dep-graph was specified and are needed for auto-tests using
51     // the #[rustc_metadata_dirty] and #[rustc_metadata_clean] attributes to
52     // check whether some metadata hash has changed in between two revisions.
53     pub prev_metadata_hashes: RefCell<FxHashMap<DefId, Fingerprint>>,
54 }
55
56 impl IncrementalHashesMap {
57     pub fn new() -> IncrementalHashesMap {
58         IncrementalHashesMap {
59             hashes: FxHashMap(),
60             prev_metadata_hashes: RefCell::new(FxHashMap()),
61         }
62     }
63
64     pub fn get(&self, k: &DepNode<DefId>) -> Option<&Fingerprint> {
65         self.hashes.get(k)
66     }
67
68     pub fn insert(&mut self, k: DepNode<DefId>, v: Fingerprint) -> Option<Fingerprint> {
69         self.hashes.insert(k, v)
70     }
71
72     pub fn iter<'a>(&'a self)
73                     -> ::std::collections::hash_map::Iter<'a, DepNode<DefId>, Fingerprint> {
74         self.hashes.iter()
75     }
76
77     pub fn len(&self) -> usize {
78         self.hashes.len()
79     }
80 }
81
82 impl<'a> ::std::ops::Index<&'a DepNode<DefId>> for IncrementalHashesMap {
83     type Output = Fingerprint;
84
85     fn index(&self, index: &'a DepNode<DefId>) -> &Fingerprint {
86         match self.hashes.get(index) {
87             Some(fingerprint) => fingerprint,
88             None => {
89                 bug!("Could not find ICH for {:?}", index);
90             }
91         }
92     }
93 }
94
95 struct ComputeItemHashesVisitor<'a, 'tcx: 'a> {
96     hcx: StableHashingContext<'a, 'tcx>,
97     hashes: IncrementalHashesMap,
98 }
99
100 impl<'a, 'tcx: 'a> ComputeItemHashesVisitor<'a, 'tcx> {
101     fn compute_and_store_ich_for_item_like<T>(&mut self,
102                                               dep_node: DepNode<DefId>,
103                                               hash_bodies: bool,
104                                               item_like: T)
105         where T: HashStable<StableHashingContext<'a, 'tcx>>
106     {
107         if !hash_bodies && !self.hcx.tcx().sess.opts.build_dep_graph() {
108             // If we just need the hashes in order to compute the SVH, we don't
109             // need have two hashes per item. Just the one containing also the
110             // item's body is sufficient.
111             return
112         }
113
114         let mut hasher = IchHasher::new();
115         self.hcx.while_hashing_hir_bodies(hash_bodies, |hcx| {
116             item_like.hash_stable(hcx, &mut hasher);
117         });
118
119         let bytes_hashed = hasher.bytes_hashed();
120         let item_hash = hasher.finish();
121         debug!("calculate_def_hash: dep_node={:?} hash={:?}", dep_node, item_hash);
122         self.hashes.insert(dep_node, item_hash);
123
124         let tcx = self.hcx.tcx();
125         let bytes_hashed =
126             tcx.sess.perf_stats.incr_comp_bytes_hashed.get() +
127             bytes_hashed;
128         tcx.sess.perf_stats.incr_comp_bytes_hashed.set(bytes_hashed);
129     }
130
131     fn compute_crate_hash(&mut self) {
132         let tcx = self.hcx.tcx();
133         let krate = tcx.hir.krate();
134
135         let mut crate_state = IchHasher::new();
136
137         let crate_disambiguator = tcx.sess.local_crate_disambiguator();
138         "crate_disambiguator".hash(&mut crate_state);
139         crate_disambiguator.as_str().len().hash(&mut crate_state);
140         crate_disambiguator.as_str().hash(&mut crate_state);
141
142         // add each item (in some deterministic order) to the overall
143         // crate hash.
144         {
145             let hcx = &mut self.hcx;
146             let mut item_hashes: Vec<_> =
147                 self.hashes.iter()
148                            .filter_map(|(item_dep_node, &item_hash)| {
149                                 // This `match` determines what kinds of nodes
150                                 // go into the SVH:
151                                 match *item_dep_node {
152                                     DepNode::Hir(_) |
153                                     DepNode::HirBody(_) => {
154                                         // We want to incoporate these into the
155                                         // SVH.
156                                     }
157                                     DepNode::FileMap(..) => {
158                                         // These don't make a semantic
159                                         // difference, filter them out.
160                                         return None
161                                     }
162                                     ref other => {
163                                         bug!("Found unexpected DepNode during \
164                                               SVH computation: {:?}",
165                                              other)
166                                     }
167                                 }
168
169                                 // Convert from a DepNode<DefId> to a
170                                 // DepNode<u64> where the u64 is the hash of
171                                 // the def-id's def-path:
172                                 let item_dep_node =
173                                     item_dep_node.map_def(|&did| Some(hcx.def_path_hash(did)))
174                                                  .unwrap();
175                                 Some((item_dep_node, item_hash))
176                            })
177                            .collect();
178             item_hashes.sort_unstable(); // avoid artificial dependencies on item ordering
179             item_hashes.hash(&mut crate_state);
180         }
181
182         krate.attrs.hash_stable(&mut self.hcx, &mut crate_state);
183
184         let crate_hash = crate_state.finish();
185         self.hashes.insert(DepNode::Krate, crate_hash);
186         debug!("calculate_crate_hash: crate_hash={:?}", crate_hash);
187     }
188
189     fn hash_crate_root_module(&mut self, krate: &'tcx hir::Crate) {
190         let hir::Crate {
191             ref module,
192             // Crate attributes are not copied over to the root `Mod`, so hash
193             // them explicitly here.
194             ref attrs,
195             span,
196
197             // These fields are handled separately:
198             exported_macros: _,
199             items: _,
200             trait_items: _,
201             impl_items: _,
202             bodies: _,
203             trait_impls: _,
204             trait_default_impl: _,
205             body_ids: _,
206         } = *krate;
207
208         let def_id = DefId::local(CRATE_DEF_INDEX);
209         self.compute_and_store_ich_for_item_like(DepNode::Hir(def_id),
210                                                  false,
211                                                  (module, (span, attrs)));
212         self.compute_and_store_ich_for_item_like(DepNode::HirBody(def_id),
213                                                  true,
214                                                  (module, (span, attrs)));
215     }
216 }
217
218 impl<'a, 'tcx: 'a> ItemLikeVisitor<'tcx> for ComputeItemHashesVisitor<'a, 'tcx> {
219     fn visit_item(&mut self, item: &'tcx hir::Item) {
220         let def_id = self.hcx.tcx().hir.local_def_id(item.id);
221         self.compute_and_store_ich_for_item_like(DepNode::Hir(def_id), false, item);
222         self.compute_and_store_ich_for_item_like(DepNode::HirBody(def_id), true, item);
223     }
224
225     fn visit_trait_item(&mut self, item: &'tcx hir::TraitItem) {
226         let def_id = self.hcx.tcx().hir.local_def_id(item.id);
227         self.compute_and_store_ich_for_item_like(DepNode::Hir(def_id), false, item);
228         self.compute_and_store_ich_for_item_like(DepNode::HirBody(def_id), true, item);
229     }
230
231     fn visit_impl_item(&mut self, item: &'tcx hir::ImplItem) {
232         let def_id = self.hcx.tcx().hir.local_def_id(item.id);
233         self.compute_and_store_ich_for_item_like(DepNode::Hir(def_id), false, item);
234         self.compute_and_store_ich_for_item_like(DepNode::HirBody(def_id), true, item);
235     }
236 }
237
238 pub fn compute_incremental_hashes_map<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
239                                                     -> IncrementalHashesMap {
240     let _ignore = tcx.dep_graph.in_ignore();
241     let krate = tcx.hir.krate();
242
243     let mut visitor = ComputeItemHashesVisitor {
244         hcx: StableHashingContext::new(tcx),
245         hashes: IncrementalHashesMap::new(),
246     };
247
248     record_time(&tcx.sess.perf_stats.incr_comp_hashes_time, || {
249         visitor.hash_crate_root_module(krate);
250         krate.visit_all_item_likes(&mut visitor);
251
252         for macro_def in krate.exported_macros.iter() {
253             let def_id = tcx.hir.local_def_id(macro_def.id);
254             visitor.compute_and_store_ich_for_item_like(DepNode::Hir(def_id), false, macro_def);
255             visitor.compute_and_store_ich_for_item_like(DepNode::HirBody(def_id), true, macro_def);
256         }
257
258         for filemap in tcx.sess
259                           .codemap()
260                           .files_untracked()
261                           .iter()
262                           .filter(|fm| !fm.is_imported()) {
263             assert_eq!(LOCAL_CRATE.as_u32(), filemap.crate_of_origin);
264             let def_id = DefId {
265                 krate: LOCAL_CRATE,
266                 index: CRATE_DEF_INDEX,
267             };
268             let name = Arc::new(filemap.name.clone());
269             let dep_node = DepNode::FileMap(def_id, name);
270             let mut hasher = IchHasher::new();
271             filemap.hash_stable(&mut visitor.hcx, &mut hasher);
272             let fingerprint = hasher.finish();
273             visitor.hashes.insert(dep_node, fingerprint);
274         }
275     });
276
277     tcx.sess.perf_stats.incr_comp_hashes_count.set(visitor.hashes.len() as u64);
278
279     record_time(&tcx.sess.perf_stats.svh_time, || visitor.compute_crate_hash());
280     visitor.hashes
281 }