1 // Copyright 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.
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.
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
13 StableHashingContextProvider};
14 use session::config::OutputType;
15 use std::cell::{Ref, RefCell};
17 use util::common::{ProfileQueriesMsg, profq_msg};
21 use super::dep_node::{DepNode, DepKind, WorkProductId};
22 use super::query::DepGraphQuery;
24 use super::safe::DepGraphSafe;
25 use super::edges::{DepGraphEdges, DepNodeIndex};
29 data: Option<Rc<DepGraphData>>,
31 // At the moment we are using DepNode as key here. In the future it might
32 // be possible to use an IndexVec<DepNodeIndex, _> here. At the moment there
33 // are a few problems with that:
34 // - Some fingerprints are needed even if incr. comp. is disabled -- yet
35 // we need to have a dep-graph to generate DepNodeIndices.
36 // - The architecture is still in flux and it's not clear what how to best
38 fingerprints: Rc<RefCell<FxHashMap<DepNode, Fingerprint>>>
42 /// The actual graph data.
43 edges: RefCell<DepGraphEdges>,
45 /// When we load, there may be `.o` files, cached mir, or other such
46 /// things available to us. If we find that they are not dirty, we
47 /// load the path to the file storing those work-products here into
48 /// this map. We can later look for and extract that data.
49 previous_work_products: RefCell<FxHashMap<WorkProductId, WorkProduct>>,
51 /// Work-products that we generate in this run.
52 work_products: RefCell<FxHashMap<WorkProductId, WorkProduct>>,
54 dep_node_debug: RefCell<FxHashMap<DepNode, String>>,
58 pub fn new(enabled: bool) -> DepGraph {
61 Some(Rc::new(DepGraphData {
62 previous_work_products: RefCell::new(FxHashMap()),
63 work_products: RefCell::new(FxHashMap()),
64 edges: RefCell::new(DepGraphEdges::new()),
65 dep_node_debug: RefCell::new(FxHashMap()),
70 fingerprints: Rc::new(RefCell::new(FxHashMap())),
74 /// True if we are actually building the full dep-graph.
76 pub fn is_fully_enabled(&self) -> bool {
80 pub fn query(&self) -> DepGraphQuery {
81 self.data.as_ref().unwrap().edges.borrow().query()
84 pub fn in_ignore<'graph>(&'graph self) -> Option<raii::IgnoreTask<'graph>> {
85 self.data.as_ref().map(|data| raii::IgnoreTask::new(&data.edges))
88 pub fn with_ignore<OP,R>(&self, op: OP) -> R
89 where OP: FnOnce() -> R
91 let _task = self.in_ignore();
95 /// Starts a new dep-graph task. Dep-graph tasks are specified
96 /// using a free function (`task`) and **not** a closure -- this
97 /// is intentional because we want to exercise tight control over
98 /// what state they have access to. In particular, we want to
99 /// prevent implicit 'leaks' of tracked state into the task (which
100 /// could then be read without generating correct edges in the
101 /// dep-graph -- see the [README] for more details on the
102 /// dep-graph). To this end, the task function gets exactly two
103 /// pieces of state: the context `cx` and an argument `arg`. Both
104 /// of these bits of state must be of some type that implements
105 /// `DepGraphSafe` and hence does not leak.
107 /// The choice of two arguments is not fundamental. One argument
108 /// would work just as well, since multiple values can be
109 /// collected using tuples. However, using two arguments works out
110 /// to be quite convenient, since it is common to need a context
111 /// (`cx`) and some argument (e.g., a `DefId` identifying what
112 /// item to process).
114 /// For cases where you need some other number of arguments:
116 /// - If you only need one argument, just use `()` for the `arg`
118 /// - If you need 3+ arguments, use a tuple for the
121 /// [README]: README.md
122 pub fn with_task<C, A, R, HCX>(&self,
128 where C: DepGraphSafe + StableHashingContextProvider<ContextType=HCX>,
131 if let Some(ref data) = self.data {
132 data.edges.borrow_mut().push_task(key);
133 if cfg!(debug_assertions) {
134 profq_msg(ProfileQueriesMsg::TaskBegin(key.clone()))
137 // In incremental mode, hash the result of the task. We don't
138 // do anything with the hash yet, but we are computing it
140 // - we make sure that the infrastructure works and
141 // - we can get an idea of the runtime cost.
142 let mut hcx = cx.create_stable_hashing_context();
144 let result = task(cx, arg);
145 if cfg!(debug_assertions) {
146 profq_msg(ProfileQueriesMsg::TaskEnd)
148 let dep_node_index = data.edges.borrow_mut().pop_task(key);
150 let mut stable_hasher = StableHasher::new();
151 result.hash_stable(&mut hcx, &mut stable_hasher);
153 assert!(self.fingerprints
155 .insert(key, stable_hasher.finish())
158 (result, dep_node_index)
160 if key.kind.fingerprint_needed_for_crate_hash() {
161 let mut hcx = cx.create_stable_hashing_context();
162 let result = task(cx, arg);
163 let mut stable_hasher = StableHasher::new();
164 result.hash_stable(&mut hcx, &mut stable_hasher);
165 assert!(self.fingerprints
167 .insert(key, stable_hasher.finish())
169 (result, DepNodeIndex::INVALID)
171 (task(cx, arg), DepNodeIndex::INVALID)
176 /// Execute something within an "anonymous" task, that is, a task the
177 /// DepNode of which is determined by the list of inputs it read from.
178 pub fn with_anon_task<OP,R>(&self, dep_kind: DepKind, op: OP) -> (R, DepNodeIndex)
179 where OP: FnOnce() -> R
181 if let Some(ref data) = self.data {
182 data.edges.borrow_mut().push_anon_task();
184 let dep_node = data.edges.borrow_mut().pop_anon_task(dep_kind);
187 (op(), DepNodeIndex::INVALID)
192 pub fn read(&self, v: DepNode) {
193 if let Some(ref data) = self.data {
194 data.edges.borrow_mut().read(v);
199 pub fn read_index(&self, v: DepNodeIndex) {
200 if let Some(ref data) = self.data {
201 data.edges.borrow_mut().read_index(v);
205 /// Only to be used during graph loading
207 pub fn add_edge_directly(&self, source: DepNode, target: DepNode) {
208 self.data.as_ref().unwrap().edges.borrow_mut().add_edge(source, target);
211 /// Only to be used during graph loading
212 pub fn add_node_directly(&self, node: DepNode) {
213 self.data.as_ref().unwrap().edges.borrow_mut().add_node(node);
216 pub fn alloc_input_node(&self, node: DepNode) -> DepNodeIndex {
217 if let Some(ref data) = self.data {
218 data.edges.borrow_mut().add_node(node)
220 DepNodeIndex::INVALID
224 pub fn fingerprint_of(&self, dep_node: &DepNode) -> Option<Fingerprint> {
225 self.fingerprints.borrow().get(dep_node).cloned()
228 /// Indicates that a previous work product exists for `v`. This is
229 /// invoked during initial start-up based on what nodes are clean
230 /// (and what files exist in the incr. directory).
231 pub fn insert_previous_work_product(&self, v: &WorkProductId, data: WorkProduct) {
232 debug!("insert_previous_work_product({:?}, {:?})", v, data);
236 .previous_work_products
238 .insert(v.clone(), data);
241 /// Indicates that we created the given work-product in this run
242 /// for `v`. This record will be preserved and loaded in the next
244 pub fn insert_work_product(&self, v: &WorkProductId, data: WorkProduct) {
245 debug!("insert_work_product({:?}, {:?})", v, data);
251 .insert(v.clone(), data);
254 /// Check whether a previous work product exists for `v` and, if
255 /// so, return the path that leads to it. Used to skip doing work.
256 pub fn previous_work_product(&self, v: &WorkProductId) -> Option<WorkProduct> {
260 data.previous_work_products.borrow().get(v).cloned()
264 /// Access the map of work-products created during this run. Only
265 /// used during saving of the dep-graph.
266 pub fn work_products(&self) -> Ref<FxHashMap<WorkProductId, WorkProduct>> {
267 self.data.as_ref().unwrap().work_products.borrow()
270 /// Access the map of work-products created during the cached run. Only
271 /// used during saving of the dep-graph.
272 pub fn previous_work_products(&self) -> Ref<FxHashMap<WorkProductId, WorkProduct>> {
273 self.data.as_ref().unwrap().previous_work_products.borrow()
277 pub fn register_dep_node_debug_str<F>(&self,
280 where F: FnOnce() -> String
282 let dep_node_debug = &self.data.as_ref().unwrap().dep_node_debug;
284 if dep_node_debug.borrow().contains_key(&dep_node) {
287 let debug_str = debug_str_gen();
288 dep_node_debug.borrow_mut().insert(dep_node, debug_str);
291 pub(super) fn dep_node_debug_str(&self, dep_node: DepNode) -> Option<String> {
292 self.data.as_ref().and_then(|t| t.dep_node_debug.borrow().get(&dep_node).cloned())
296 /// A "work product" is an intermediate result that we save into the
297 /// incremental directory for later re-use. The primary example are
298 /// the object files that we save for each partition at code
301 /// Each work product is associated with a dep-node, representing the
302 /// process that produced the work-product. If that dep-node is found
303 /// to be dirty when we load up, then we will delete the work-product
304 /// at load time. If the work-product is found to be clean, then we
305 /// will keep a record in the `previous_work_products` list.
307 /// In addition, work products have an associated hash. This hash is
308 /// an extra hash that can be used to decide if the work-product from
309 /// a previous compilation can be re-used (in addition to the dirty
312 /// As the primary example, consider the object files we generate for
313 /// each partition. In the first run, we create partitions based on
314 /// the symbols that need to be compiled. For each partition P, we
315 /// hash the symbols in P and create a `WorkProduct` record associated
316 /// with `DepNode::TransPartition(P)`; the hash is the set of symbols
319 /// The next time we compile, if the `DepNode::TransPartition(P)` is
320 /// judged to be clean (which means none of the things we read to
321 /// generate the partition were found to be dirty), it will be loaded
322 /// into previous work products. We will then regenerate the set of
323 /// symbols in the partition P and hash them (note that new symbols
324 /// may be added -- for example, new monomorphizations -- even if
325 /// nothing in P changed!). We will compare that hash against the
326 /// previous hash. If it matches up, we can reuse the object file.
327 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
328 pub struct WorkProduct {
329 pub cgu_name: String,
330 /// Extra hash used to decide if work-product is still suitable;
331 /// note that this is *not* a hash of the work-product itself.
332 /// See documentation on `WorkProduct` type for an example.
335 /// Saved files associated with this CGU
336 pub saved_files: Vec<(OutputType, String)>,