Skip to main content

rustc_incremental/persist/
save.rs

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