]> git.lizzy.rs Git - rust.git/blob - src/librustc_incremental/calculate_svh/mod.rs
change the format of the linked issue number
[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 syntax::ast;
31 use std::cell::RefCell;
32 use std::hash::Hash;
33 use rustc::dep_graph::DepNode;
34 use rustc::hir;
35 use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
36 use rustc::hir::intravisit as visit;
37 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
38 use rustc::ich::{Fingerprint, DefPathHashes, CachingCodemapView};
39 use rustc::ty::TyCtxt;
40 use rustc_data_structures::stable_hasher::StableHasher;
41 use rustc_data_structures::fx::FxHashMap;
42 use rustc::util::common::record_time;
43 use rustc::session::config::DebugInfoLevel::NoDebugInfo;
44
45 use self::svh_visitor::StrictVersionHashVisitor;
46
47 mod svh_visitor;
48
49 pub type IchHasher = StableHasher<Fingerprint>;
50
51 pub struct IncrementalHashesMap {
52     hashes: FxHashMap<DepNode<DefId>, Fingerprint>,
53
54     // These are the metadata hashes for the current crate as they were stored
55     // during the last compilation session. They are only loaded if
56     // -Z query-dep-graph was specified and are needed for auto-tests using
57     // the #[rustc_metadata_dirty] and #[rustc_metadata_clean] attributes to
58     // check whether some metadata hash has changed in between two revisions.
59     pub prev_metadata_hashes: RefCell<FxHashMap<DefId, Fingerprint>>,
60 }
61
62 impl IncrementalHashesMap {
63     pub fn new() -> IncrementalHashesMap {
64         IncrementalHashesMap {
65             hashes: FxHashMap(),
66             prev_metadata_hashes: RefCell::new(FxHashMap()),
67         }
68     }
69
70     pub fn insert(&mut self, k: DepNode<DefId>, v: Fingerprint) -> Option<Fingerprint> {
71         self.hashes.insert(k, v)
72     }
73
74     pub fn iter<'a>(&'a self)
75                     -> ::std::collections::hash_map::Iter<'a, DepNode<DefId>, Fingerprint> {
76         self.hashes.iter()
77     }
78
79     pub fn len(&self) -> usize {
80         self.hashes.len()
81     }
82 }
83
84 impl<'a> ::std::ops::Index<&'a DepNode<DefId>> for IncrementalHashesMap {
85     type Output = Fingerprint;
86
87     fn index(&self, index: &'a DepNode<DefId>) -> &Fingerprint {
88         match self.hashes.get(index) {
89             Some(fingerprint) => fingerprint,
90             None => {
91                 bug!("Could not find ICH for {:?}", index);
92             }
93         }
94     }
95 }
96
97
98 pub fn compute_incremental_hashes_map<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
99                                                     -> IncrementalHashesMap {
100     let _ignore = tcx.dep_graph.in_ignore();
101     let krate = tcx.hir.krate();
102     let hash_spans = tcx.sess.opts.debuginfo != NoDebugInfo;
103     let mut visitor = HashItemsVisitor {
104         tcx: tcx,
105         hashes: IncrementalHashesMap::new(),
106         def_path_hashes: DefPathHashes::new(tcx),
107         codemap: CachingCodemapView::new(tcx),
108         hash_spans: hash_spans,
109     };
110     record_time(&tcx.sess.perf_stats.incr_comp_hashes_time, || {
111         visitor.calculate_def_id(DefId::local(CRATE_DEF_INDEX), |v| {
112             v.hash_crate_root_module(krate);
113         });
114         krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
115
116         for macro_def in krate.exported_macros.iter() {
117             visitor.calculate_node_id(macro_def.id,
118                                       |v| v.visit_macro_def(macro_def));
119         }
120     });
121
122     tcx.sess.perf_stats.incr_comp_hashes_count.set(visitor.hashes.len() as u64);
123
124     record_time(&tcx.sess.perf_stats.svh_time, || visitor.compute_crate_hash());
125     visitor.hashes
126 }
127
128 struct HashItemsVisitor<'a, 'tcx: 'a> {
129     tcx: TyCtxt<'a, 'tcx, 'tcx>,
130     def_path_hashes: DefPathHashes<'a, 'tcx>,
131     codemap: CachingCodemapView<'tcx>,
132     hashes: IncrementalHashesMap,
133     hash_spans: bool,
134 }
135
136 impl<'a, 'tcx> HashItemsVisitor<'a, 'tcx> {
137     fn calculate_node_id<W>(&mut self, id: ast::NodeId, walk_op: W)
138         where W: for<'v> FnMut(&mut StrictVersionHashVisitor<'v, 'a, 'tcx>)
139     {
140         let def_id = self.tcx.hir.local_def_id(id);
141         self.calculate_def_id(def_id, walk_op)
142     }
143
144     fn calculate_def_id<W>(&mut self, def_id: DefId, mut walk_op: W)
145         where W: for<'v> FnMut(&mut StrictVersionHashVisitor<'v, 'a, 'tcx>)
146     {
147         assert!(def_id.is_local());
148         debug!("HashItemsVisitor::calculate(def_id={:?})", def_id);
149         self.calculate_def_hash(DepNode::Hir(def_id), false, &mut walk_op);
150         self.calculate_def_hash(DepNode::HirBody(def_id), true, &mut walk_op);
151     }
152
153     fn calculate_def_hash<W>(&mut self,
154                              dep_node: DepNode<DefId>,
155                              hash_bodies: bool,
156                              walk_op: &mut W)
157         where W: for<'v> FnMut(&mut StrictVersionHashVisitor<'v, 'a, 'tcx>)
158     {
159         let mut state = IchHasher::new();
160         walk_op(&mut StrictVersionHashVisitor::new(&mut state,
161                                                    self.tcx,
162                                                    &mut self.def_path_hashes,
163                                                    &mut self.codemap,
164                                                    self.hash_spans,
165                                                    hash_bodies));
166         let bytes_hashed = state.bytes_hashed();
167         let item_hash = state.finish();
168         debug!("calculate_def_hash: dep_node={:?} hash={:?}", dep_node, item_hash);
169         self.hashes.insert(dep_node, item_hash);
170
171         let bytes_hashed = self.tcx.sess.perf_stats.incr_comp_bytes_hashed.get() +
172             bytes_hashed;
173         self.tcx.sess.perf_stats.incr_comp_bytes_hashed.set(bytes_hashed);
174     }
175
176     fn compute_crate_hash(&mut self) {
177         let krate = self.tcx.hir.krate();
178
179         let mut crate_state = IchHasher::new();
180
181         let crate_disambiguator = self.tcx.sess.local_crate_disambiguator();
182         "crate_disambiguator".hash(&mut crate_state);
183         crate_disambiguator.as_str().len().hash(&mut crate_state);
184         crate_disambiguator.as_str().hash(&mut crate_state);
185
186         // add each item (in some deterministic order) to the overall
187         // crate hash.
188         {
189             let def_path_hashes = &mut self.def_path_hashes;
190             let mut item_hashes: Vec<_> =
191                 self.hashes.iter()
192                            .map(|(item_dep_node, &item_hash)| {
193                                // convert from a DepNode<DefId> tp a
194                                // DepNode<u64> where the u64 is the
195                                // hash of the def-id's def-path:
196                                let item_dep_node =
197                                    item_dep_node.map_def(|&did| Some(def_path_hashes.hash(did)))
198                                                 .unwrap();
199                                (item_dep_node, item_hash)
200                            })
201                            .collect();
202             item_hashes.sort(); // avoid artificial dependencies on item ordering
203             item_hashes.hash(&mut crate_state);
204         }
205
206         {
207             let mut visitor = StrictVersionHashVisitor::new(&mut crate_state,
208                                                             self.tcx,
209                                                             &mut self.def_path_hashes,
210                                                             &mut self.codemap,
211                                                             self.hash_spans,
212                                                             false);
213             visitor.hash_attributes(&krate.attrs);
214         }
215
216         let crate_hash = crate_state.finish();
217         self.hashes.insert(DepNode::Krate, crate_hash);
218         debug!("calculate_crate_hash: crate_hash={:?}", crate_hash);
219     }
220 }
221
222
223 impl<'a, 'tcx> Visitor<'tcx> for HashItemsVisitor<'a, 'tcx> {
224     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
225         NestedVisitorMap::None
226     }
227
228     fn visit_item(&mut self, item: &'tcx hir::Item) {
229         self.calculate_node_id(item.id, |v| v.visit_item(item));
230         visit::walk_item(self, item);
231     }
232
233     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
234         self.calculate_node_id(trait_item.id, |v| v.visit_trait_item(trait_item));
235         visit::walk_trait_item(self, trait_item);
236     }
237
238     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
239         self.calculate_node_id(impl_item.id, |v| v.visit_impl_item(impl_item));
240         visit::walk_impl_item(self, impl_item);
241     }
242 }