summary refs log tree commit diff
path: root/src/librustc_incremental/persist/load.rs
blob: 0ac1018462ee7a7eb06a2e6cc2b75a01eacda4db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Code to save/load the dep-graph from files.

use rbml::Error;
use rbml::opaque::Decoder;
use rustc::dep_graph::DepNode;
use rustc::hir::def_id::DefId;
use rustc::ty::TyCtxt;
use rustc_data_structures::fnv::FnvHashSet;
use rustc_serialize::Decodable as RustcDecodable;
use std::io::Read;
use std::fs::File;
use std::path::Path;

use super::data::*;
use super::directory::*;
use super::dirty_clean;
use super::hash::*;
use super::util::*;

type DirtyNodes = FnvHashSet<DepNode<DefId>>;

type CleanEdges = Vec<(DepNode<DefId>, DepNode<DefId>)>;

/// If we are in incremental mode, and a previous dep-graph exists,
/// then load up those nodes/edges that are still valid into the
/// dep-graph for this session. (This is assumed to be running very
/// early in compilation, before we've really done any work, but
/// actually it doesn't matter all that much.) See `README.md` for
/// more general overview.
pub fn load_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
    let _ignore = tcx.dep_graph.in_ignore();

    if let Some(dep_graph) = dep_graph_path(tcx) {
        // FIXME(#32754) lock file?
        load_dep_graph_if_exists(tcx, &dep_graph);
        dirty_clean::check_dirty_clean_annotations(tcx);
    }
}

pub fn load_dep_graph_if_exists<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, path: &Path) {
    if !path.exists() {
        return;
    }

    let mut data = vec![];
    match
        File::open(path)
        .and_then(|mut file| file.read_to_end(&mut data))
    {
        Ok(_) => { }
        Err(err) => {
            tcx.sess.err(
                &format!("could not load dep-graph from `{}`: {}",
                         path.display(), err));
            return;
        }
    }

    match decode_dep_graph(tcx, &data) {
        Ok(dirty) => dirty,
        Err(err) => {
            bug!("decoding error in dep-graph from `{}`: {}", path.display(), err);
        }
    }
}

pub fn decode_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                  data: &[u8])
                                  -> Result<(), Error>
{
    // Deserialize the directory and dep-graph.
    let mut decoder = Decoder::new(data, 0);
    let directory = try!(DefIdDirectory::decode(&mut decoder));
    let serialized_dep_graph = try!(SerializedDepGraph::decode(&mut decoder));

    debug!("decode_dep_graph: directory = {:#?}", directory);
    debug!("decode_dep_graph: serialized_dep_graph = {:#?}", serialized_dep_graph);

    // Retrace the paths in the directory to find their current location (if any).
    let retraced = directory.retrace(tcx);

    debug!("decode_dep_graph: retraced = {:#?}", retraced);

    // Compute the set of Hir nodes whose data has changed.
    let mut dirty_nodes =
        initial_dirty_nodes(tcx, &serialized_dep_graph.hashes, &retraced);

    debug!("decode_dep_graph: initial dirty_nodes = {:#?}", dirty_nodes);

    // Find all DepNodes reachable from that core set. This loop
    // iterates repeatedly over the list of edges whose source is not
    // known to be dirty (`clean_edges`). If it finds an edge whose
    // source is dirty, it removes it from that list and adds the
    // target to `dirty_nodes`. It stops when it reaches a fixed
    // point.
    let clean_edges = compute_clean_edges(&serialized_dep_graph.edges,
                                          &retraced,
                                          &mut dirty_nodes);

    // Add synthetic `foo->foo` edges for each clean node `foo` that
    // we had before. This is sort of a hack to create clean nodes in
    // the graph, since the existence of a node is a signal that the
    // work it represents need not be repeated.
    let clean_nodes =
        serialized_dep_graph.nodes
                            .iter()
                            .filter_map(|node| retraced.map(node))
                            .filter(|node| !dirty_nodes.contains(node))
                            .map(|node| (node.clone(), node));

    // Add nodes and edges that are not dirty into our main graph.
    let dep_graph = tcx.dep_graph.clone();
    for (source, target) in clean_edges.into_iter().chain(clean_nodes) {
        let _task = dep_graph.in_task(target.clone());
        dep_graph.read(source.clone());

        debug!("decode_dep_graph: clean edge: {:?} -> {:?}", source, target);
    }

    Ok(())
}

fn initial_dirty_nodes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                 hashes: &[SerializedHash],
                                 retraced: &RetracedDefIdDirectory)
                                 -> DirtyNodes {
    let mut hcx = HashContext::new(tcx);
    let mut items_removed = false;
    let mut dirty_nodes = FnvHashSet();
    for hash in hashes {
        match hash.node.map_def(|&i| retraced.def_id(i)) {
            Some(dep_node) => {
                let current_hash = hcx.hash(&dep_node).unwrap();
                debug!("initial_dirty_nodes: hash of {:?} is {:?}, was {:?}",
                       dep_node, current_hash, hash.hash);
                if current_hash != hash.hash {
                    dirty_nodes.insert(dep_node);
                }
            }
            None => {
                items_removed = true;
            }
        }
    }

    // If any of the items in the krate have changed, then we consider
    // the meta-node `Krate` to be dirty, since that means something
    // which (potentially) read the contents of every single item.
    if items_removed || !dirty_nodes.is_empty() {
        dirty_nodes.insert(DepNode::Krate);
    }

    dirty_nodes
}

fn compute_clean_edges(serialized_edges: &[(SerializedEdge)],
                       retraced: &RetracedDefIdDirectory,
                       dirty_nodes: &mut DirtyNodes)
                       -> CleanEdges {
    // Build up an initial list of edges. Include an edge (source,
    // target) if neither node has been removed. If the source has
    // been removed, add target to the list of dirty nodes.
    let mut clean_edges = Vec::with_capacity(serialized_edges.len());
    for &(ref serialized_source, ref serialized_target) in serialized_edges {
        if let Some(target) = retraced.map(serialized_target) {
            if let Some(source) = retraced.map(serialized_source) {
                clean_edges.push((source, target))
            } else {
                // source removed, target must be dirty
                dirty_nodes.insert(target);
            }
        } else {
            // target removed, ignore the edge
        }
    }

    debug!("compute_clean_edges: dirty_nodes={:#?}", dirty_nodes);

    // Propagate dirty marks by iterating repeatedly over
    // `clean_edges`. If we find an edge `(source, target)` where
    // `source` is dirty, add `target` to the list of dirty nodes and
    // remove it. Keep doing this until we find no more dirty nodes.
    let mut previous_size = 0;
    while dirty_nodes.len() > previous_size {
        debug!("compute_clean_edges: previous_size={}", previous_size);
        previous_size = dirty_nodes.len();
        let mut i = 0;
        while i < clean_edges.len() {
            if dirty_nodes.contains(&clean_edges[i].0) {
                let (source, target) = clean_edges.swap_remove(i);
                debug!("compute_clean_edges: dirty source {:?} -> {:?}",
                       source, target);
                dirty_nodes.insert(target);
            } else if dirty_nodes.contains(&clean_edges[i].1) {
                let (source, target) = clean_edges.swap_remove(i);
                debug!("compute_clean_edges: dirty target {:?} -> {:?}",
                       source, target);
            } else {
                i += 1;
            }
        }
    }

    clean_edges
}