Skip to main content

rustc_incremental/persist/
save.rs

1use std::fs;
2
3use rustc_data_structures::fx::FxIndexMap;
4use rustc_data_structures::sync::par_join;
5use rustc_middle::dep_graph::{DepGraph, WorkProduct, WorkProductId};
6use rustc_middle::query::on_disk_cache;
7use rustc_middle::ty::TyCtxt;
8use rustc_serialize::Encodable as RustcEncodable;
9use rustc_serialize::opaque::FileEncoder;
10use rustc_session::Session;
11use tracing::debug;
12
13use super::data::*;
14use super::fs::*;
15use super::{clean, file_format, work_product};
16use crate::assert_dep_graph::assert_dep_graph;
17use crate::errors;
18
19/// Saves and writes the [`DepGraph`] to the file system.
20///
21/// This function saves both the dep-graph and the query result cache,
22/// and drops the result cache.
23///
24/// This function should only run after all queries have completed.
25/// Trying to execute a query afterwards would attempt to read the result cache we just dropped.
26pub(crate) fn save_dep_graph(tcx: TyCtxt<'_>) {
27    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_incremental/src/persist/save.rs:27",
                        "rustc_incremental::persist::save", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_incremental/src/persist/save.rs"),
                        ::tracing_core::__macro_support::Option::Some(27u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::save"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("save_dep_graph()")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("save_dep_graph()");
28    tcx.dep_graph.with_ignore(|| {
29        let sess = tcx.sess;
30        if sess.opts.incremental.is_none() {
31            return;
32        }
33        // This is going to be deleted in finalize_session_directory, so let's not create it.
34        if sess.dcx().has_errors_or_delayed_bugs().is_some() {
35            return;
36        }
37
38        let query_cache_path = query_cache_path(sess);
39        let dep_graph_path = dep_graph_path(sess);
40        let staging_dep_graph_path = staging_dep_graph_path(sess);
41
42        sess.time("assert_dep_graph", || assert_dep_graph(tcx));
43        sess.time("check_clean", || clean::check_clean_annotations(tcx));
44
45        par_join(
46            move || {
47                sess.time("incr_comp_persist_dep_graph", || {
48                    if let Err(err) = fs::rename(&staging_dep_graph_path, &dep_graph_path) {
49                        sess.dcx().emit_err(errors::MoveDepGraph {
50                            from: &staging_dep_graph_path,
51                            to: &dep_graph_path,
52                            err,
53                        });
54                    }
55                });
56            },
57            move || {
58                // We execute this after `incr_comp_persist_dep_graph` for the serial compiler
59                // to catch any potential query execution writing to the dep graph.
60                sess.time("incr_comp_persist_result_cache", || {
61                    // The on-disk cache struct is always present in incremental mode,
62                    // even if there was no previous session.
63                    let on_disk_cache = tcx.query_system.on_disk_cache.as_ref().unwrap();
64
65                    // For every green dep node that has a disk-cached value from the
66                    // previous session, make sure the value is loaded into the memory
67                    // cache, so that it will be serialized as part of this session.
68                    //
69                    // This reads data from the previous session, so it needs to happen
70                    // before dropping the mmap.
71                    //
72                    // FIXME(Zalathar): This step is intended to be cheap, but still does
73                    // quite a lot of work, especially in builds with few or no changes.
74                    // Can we be smarter about how we identify values that need promotion?
75                    // Can we promote values without decoding them into the memory cache?
76                    tcx.dep_graph.exec_cache_promotions(tcx);
77
78                    // Drop the memory map so that we can remove the file and write to it.
79                    on_disk_cache.close_serialized_data_mmap();
80
81                    file_format::save_in(sess, query_cache_path, "query cache", |encoder| {
82                        tcx.sess.time("incr_comp_serialize_result_cache", || {
83                            on_disk_cache::OnDiskCache::serialize(tcx, encoder)
84                        })
85                    });
86                });
87            },
88        );
89    })
90}
91
92/// Saves the work product index.
93pub fn save_work_product_index(
94    sess: &Session,
95    dep_graph: &DepGraph,
96    new_work_products: FxIndexMap<WorkProductId, WorkProduct>,
97) {
98    if sess.opts.incremental.is_none() {
99        return;
100    }
101    // This is going to be deleted in finalize_session_directory, so let's not create it
102    if sess.dcx().has_errors().is_some() {
103        return;
104    }
105
106    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_incremental/src/persist/save.rs:106",
                        "rustc_incremental::persist::save", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_incremental/src/persist/save.rs"),
                        ::tracing_core::__macro_support::Option::Some(106u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::save"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("save_work_product_index()")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("save_work_product_index()");
107    dep_graph.assert_ignored();
108    let path = work_products_path(sess);
109    file_format::save_in(sess, path, "work product index", |mut e| {
110        encode_work_product_index(&new_work_products, &mut e);
111        e.finish()
112    });
113
114    // We also need to clean out old work-products, as not all of them are
115    // deleted during invalidation. Some object files don't change their
116    // content, they are just not needed anymore.
117    let previous_work_products = dep_graph.previous_work_products();
118    for (id, wp) in previous_work_products.to_sorted_stable_ord() {
119        if !new_work_products.contains_key(id) {
120            work_product::delete_workproduct_files(sess, wp);
121            if true {
    if !!wp.saved_files.items().all(|(_, path)|
                        in_incr_comp_dir_sess(sess, path).exists()) {
        ::core::panicking::panic("assertion failed: !wp.saved_files.items().all(|(_, path)|\n            in_incr_comp_dir_sess(sess, path).exists())")
    };
};debug_assert!(
122                !wp.saved_files.items().all(|(_, path)| in_incr_comp_dir_sess(sess, path).exists())
123            );
124        }
125    }
126
127    // Check that we did not delete one of the current work-products:
128    if true {
    if !{
                new_work_products.iter().all(|(_, wp)|
                        {
                            wp.saved_files.items().all(|(_, path)|
                                    in_incr_comp_dir_sess(sess, path).exists())
                        })
            } {
        ::core::panicking::panic("assertion failed: {\n    new_work_products.iter().all(|(_, wp)|\n            {\n                wp.saved_files.items().all(|(_, path)|\n                        in_incr_comp_dir_sess(sess, path).exists())\n            })\n}")
    };
};debug_assert!({
129        new_work_products.iter().all(|(_, wp)| {
130            wp.saved_files.items().all(|(_, path)| in_incr_comp_dir_sess(sess, path).exists())
131        })
132    });
133}
134
135fn encode_work_product_index(
136    work_products: &FxIndexMap<WorkProductId, WorkProduct>,
137    encoder: &mut FileEncoder,
138) {
139    let serialized_products: Vec<_> = work_products
140        .iter()
141        .map(|(id, work_product)| SerializedWorkProduct {
142            id: *id,
143            work_product: work_product.clone(),
144        })
145        .collect();
146
147    serialized_products.encode(encoder)
148}