Skip to main content

rustc_incremental/persist/
load.rs

1//! Code to load the dep-graph from files.
2
3use std::sync::Arc;
4
5use rustc_hashes::Hash64;
6use rustc_middle::dep_graph::{DepGraph, IncrCompSession, SerializedDepGraph, WorkProductMap};
7use rustc_middle::query::on_disk_cache::OnDiskCache;
8use rustc_serialize::opaque::{FileEncoder, MemDecoder};
9use rustc_serialize::{Decodable, Encodable};
10use rustc_session::config::IncrementalStateAssertion;
11use rustc_session::{Session, StableCrateId};
12use rustc_span::Symbol;
13use tracing::{debug, warn};
14
15use super::file_format;
16use super::fs::*;
17use super::work_product::SerializedWorkProduct;
18use crate::diagnostics;
19use crate::persist::file_format::{OpenFile, OpenFileError};
20
21/// Load the old dep graph and work product index.
22///
23/// Returns Err(()) if a file was produced by an incompatible compiler version, didn't
24/// exist or for some other reason couldn't be used.
25fn load_dep_graph(
26    sess: &Session,
27    incr_comp_session: &IncrCompSession,
28) -> Result<(Arc<SerializedDepGraph>, WorkProductMap), ()> {
29    if !sess.opts.incremental.is_some() {
    ::core::panicking::panic("assertion failed: sess.opts.incremental.is_some()")
};assert!(sess.opts.incremental.is_some());
30
31    let _timer = sess.prof.generic_activity("incr_comp_prepare_load_dep_graph");
32
33    // Calling `sess.incr_comp_session_dir()` will panic if `sess.opts.incremental.is_none()`.
34    // Fortunately, we just checked that this isn't the case.
35    let Some(path) = old_dep_graph_path(incr_comp_session) else {
36        return Err(());
37    };
38    let expected_hash = sess.opts.dep_tracking_hash(false);
39
40    let prev_work_products = load_work_product_index(sess, incr_comp_session)?;
41
42    let _prof_timer = sess.prof.generic_activity("incr_comp_load_dep_graph");
43
44    match file_format::open_incremental_file(sess, &path) {
45        Err(OpenFileError::NotFoundOrHeaderMismatch) => Err(()),
46        Err(OpenFileError::IoError { err }) => {
47            sess.dcx().emit_warn(diagnostics::LoadDepGraph { path, err });
48            Err(())
49        }
50        Ok(OpenFile { mmap, start_pos }) => {
51            let Ok(mut decoder) = MemDecoder::new(&mmap, start_pos) else {
52                sess.dcx().emit_warn(diagnostics::CorruptFile { path: &path });
53                return Err(());
54            };
55            let prev_commandline_args_hash = Hash64::decode(&mut decoder);
56
57            if prev_commandline_args_hash != expected_hash {
58                if sess.opts.unstable_opts.incremental_info {
59                    {
    ::std::io::_eprint(format_args!("[incremental] completely ignoring cache because of differing commandline arguments\n"));
};eprintln!(
60                        "[incremental] completely ignoring cache because of \
61                                    differing commandline arguments"
62                    );
63                }
64                // We can't reuse the cache, purge it.
65                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/load.rs:65",
                        "rustc_incremental::persist::load", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/load.rs"),
                        ::tracing_core::__macro_support::Option::Some(65u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::load"),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("load_dep_graph_new: differing commandline arg hashes")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("load_dep_graph_new: differing commandline arg hashes");
66
67                // No need to do any further work
68                return Err(());
69            }
70
71            let prev_graph = SerializedDepGraph::decode(&mut decoder, &sess.prof);
72
73            Ok((prev_graph, prev_work_products))
74        }
75    }
76}
77
78fn load_work_product_index(
79    sess: &Session,
80    incr_comp_session: &IncrCompSession,
81) -> Result<WorkProductMap, ()> {
82    let mut prev_work_products = WorkProductMap::default();
83
84    let Some(work_products_path) = old_work_products_path(incr_comp_session) else {
85        return Err(());
86    };
87
88    if let Ok(OpenFile { mmap, start_pos }) =
89        file_format::open_incremental_file(sess, &work_products_path)
90    {
91        // Decode the list of work_products
92        let Ok(mut work_product_decoder) = MemDecoder::new(&mmap[..], start_pos) else {
93            sess.dcx().emit_warn(diagnostics::CorruptFile { path: &work_products_path });
94            return Err(());
95        };
96        let work_products: Vec<SerializedWorkProduct> =
97            Decodable::decode(&mut work_product_decoder);
98
99        for swp in work_products {
100            let all_files_exist = swp.work_product.saved_files.items().all(|(_, path)| {
101                let exists = in_old_incr_comp_dir_sess(incr_comp_session, path).unwrap().exists();
102                if !exists && sess.opts.unstable_opts.incremental_info {
103                    {
    ::std::io::_eprint(format_args!("incremental: could not find file for work product: {0}\n",
            path));
};eprintln!("incremental: could not find file for work product: {path}",);
104                }
105                exists
106            });
107
108            if all_files_exist {
109                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/load.rs:109",
                        "rustc_incremental::persist::load", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/load.rs"),
                        ::tracing_core::__macro_support::Option::Some(109u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::load"),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("reconcile_work_products: all files for {0:?} exist",
                                                    swp) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("reconcile_work_products: all files for {:?} exist", swp);
110                prev_work_products.insert(swp.id, swp.work_product);
111            } else {
112                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/load.rs:112",
                        "rustc_incremental::persist::load", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/load.rs"),
                        ::tracing_core::__macro_support::Option::Some(112u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::load"),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("reconcile_work_products: some file for {0:?} does not exist",
                                                    swp) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("reconcile_work_products: some file for {:?} does not exist", swp);
113                return Err(());
114            }
115        }
116    }
117
118    Ok(prev_work_products)
119}
120
121/// Attempts to load the query result cache from disk
122///
123/// If we are not in incremental compilation mode, returns `None`.
124/// Otherwise, tries to load the query result cache from disk,
125/// creating an empty cache if it could not be loaded.
126pub fn load_query_result_cache(sess: &Session, incr_comp_session: &IncrCompSession) -> OnDiskCache {
127    let _prof_timer = sess.prof.generic_activity("incr_comp_load_query_result_cache");
128
129    let Some(path) = old_query_cache_path(incr_comp_session) else {
130        return OnDiskCache::new_empty();
131    };
132    match file_format::open_incremental_file(sess, &path) {
133        Ok(OpenFile { mmap, start_pos }) => {
134            OnDiskCache::new(sess, mmap, start_pos).unwrap_or_else(|()| {
135                sess.dcx().emit_warn(diagnostics::CorruptFile { path: &path });
136                OnDiskCache::new_empty()
137            })
138        }
139        Err(OpenFileError::NotFoundOrHeaderMismatch | OpenFileError::IoError { .. }) => {
140            OnDiskCache::new_empty()
141        }
142    }
143}
144
145/// Emits a fatal error if the assertion in `-Zassert-incr-state` doesn't match
146/// the outcome of trying to load previous-session state.
147fn maybe_assert_incr_state(sess: &Session, loaded: bool) {
148    // Return immediately if there's nothing to assert.
149    let Some(assertion) = sess.opts.unstable_opts.assert_incr_state else { return };
150
151    match assertion {
152        IncrementalStateAssertion::Loaded => {
153            if !loaded {
154                sess.dcx().emit_fatal(diagnostics::AssertLoaded);
155            }
156        }
157        IncrementalStateAssertion::NotLoaded => {
158            if loaded {
159                sess.dcx().emit_fatal(diagnostics::AssertNotLoaded)
160            }
161        }
162    }
163}
164
165/// Loads the previous session's dependency graph from disk if possible, and
166/// sets up streaming output for the current session's dep graph data into an
167/// incremental session directory.
168///
169/// In non-incremental mode, a dummy dep graph is returned immediately.
170pub fn setup_dep_graph(
171    sess: &Session,
172    crate_name: Symbol,
173    stable_crate_id: StableCrateId,
174) -> (DepGraph, Option<IncrCompSession>) {
175    if sess.opts.incremental.is_none() {
176        return (DepGraph::new_disabled(), None);
177    }
178
179    // `load_dep_graph` can only be called after `prepare_session_directory`.
180    let mut incr_comp_session = prepare_session_directory(sess, crate_name, stable_crate_id);
181    // Try to load the previous session's dep graph and work products.
182    let load_result = load_dep_graph(sess, &incr_comp_session);
183
184    sess.time("incr_comp_garbage_collect_session_directories", || {
185        if let Err(e) = garbage_collect_session_directories(sess, &incr_comp_session) {
186            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/load.rs:186",
                        "rustc_incremental::persist::load", ::tracing::Level::WARN,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/load.rs"),
                        ::tracing_core::__macro_support::Option::Some(186u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::load"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::WARN <=
                    ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Error while trying to garbage collect incremental compilation cache directory: {0}",
                                                    e) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};warn!(
187                "Error while trying to garbage collect incremental compilation \
188                cache directory: {e}",
189            );
190        }
191    });
192
193    // Emit a fatal error if `-Zassert-incr-state` is present and unsatisfied.
194    maybe_assert_incr_state(sess, load_result.is_ok());
195
196    let (prev_graph, prev_work_products) = match load_result {
197        Ok((prev_graph, prev_work_products)) => (prev_graph, prev_work_products),
198        Err(()) => {
199            invalidate_old_session_dir(sess, &mut incr_comp_session);
200            Default::default()
201        }
202    };
203
204    // Stream the dep-graph to an alternate file, to avoid overwriting anything in case of errors.
205    let path_buf = staging_dep_graph_path(&incr_comp_session);
206
207    let mut encoder = FileEncoder::new(&path_buf).unwrap_or_else(|err| {
208        // We're in incremental mode but couldn't set up streaming output of the dep graph.
209        // Exit immediately instead of continuing in an inconsistent and untested state.
210        sess.dcx().emit_fatal(diagnostics::CreateDepGraph { path: &path_buf, err })
211    });
212
213    file_format::write_file_header(&mut encoder, sess);
214
215    // First encode the commandline arguments hash
216    sess.opts.dep_tracking_hash(false).encode(&mut encoder);
217
218    (DepGraph::new(sess, prev_graph, prev_work_products, encoder), Some(incr_comp_session))
219}