Skip to main content

rustc_middle/dep_graph/
mod.rs

1use std::panic;
2use std::path::PathBuf;
3use std::sync::Arc;
4
5use rustc_data_structures::flock;
6use tracing::instrument;
7
8pub use self::dep_node::{DepKind, DepKindVTable, DepNode, WorkProductId, dep_kind_from_label};
9pub use self::dep_node_key::DepNodeKey;
10pub use self::graph::{
11    DepGraph, DepGraphData, DepNodeColor, DepNodeIndex, QuerySideEffect, TaskDepsRef, WorkProduct,
12    WorkProductMap, hash_result,
13};
14use self::graph::{MarkFrame, print_markframe_trace};
15pub use self::retained::RetainedDepGraph;
16pub use self::serialized::{SerializedDepGraph, SerializedDepNodeIndex};
17pub use crate::dep_graph::debug::{DepNodeFilter, EdgeFilter};
18pub use crate::ty::print::with_reduced_queries;
19use crate::ty::{self, TyCtxt};
20
21mod debug;
22pub(crate) mod dep_node;
23mod dep_node_key;
24mod edges;
25mod graph;
26mod retained;
27mod serialized;
28
29/// Holds data on the current incremental compilation session, if there is one.
30pub struct IncrCompSession {
31    /// The directory from which cached data of a previous session can be read.
32    pub old_session_directory: Option<flock::LockedDir>,
33    /// The directory to which cached data for the current session can be
34    /// written to.
35    pub new_session_directory: flock::LockedDir,
36    pub new_work_products: WorkProductMap,
37    borrows: Arc<()>,
38}
39
40impl IncrCompSession {
41    pub fn new(
42        old_session_directory: Option<flock::LockedDir>,
43        new_session_directory: flock::LockedDir,
44    ) -> Self {
45        IncrCompSession {
46            old_session_directory,
47            new_session_directory,
48            new_work_products: WorkProductMap::default(),
49            borrows: Arc::new(()),
50        }
51    }
52
53    pub fn borrow(&self) -> BorrowedIncrCompSession {
54        BorrowedIncrCompSession {
55            old_session_directory: self.old_session_directory.as_deref().map(ToOwned::to_owned),
56            new_session_directory: (&*self.new_session_directory).to_owned(),
57            _borrows: Arc::clone(&self.borrows),
58        }
59    }
60}
61
62impl Drop for IncrCompSession {
63    fn drop(&mut self) {
64        // Check that there are no worker threads remaining that use the incr
65        // comp session before we unlock the old and new session dir. If there
66        // does exist a worker thread, there is not much we can do, but at
67        // least we will unconditionally complain rather than the worker thread
68        // sometimes crashing depending on what other rustc instances run.
69        if !(Arc::strong_count(&self.borrows) == 1) {
    {
        ::core::panicking::panic_fmt(format_args!("Incr comp session dropped while there are still references"));
    }
};assert!(
70            Arc::strong_count(&self.borrows) == 1,
71            "Incr comp session dropped while there are still references",
72        );
73    }
74}
75
76/// A runtime tracked borrow of the incr comp session. Can be sent to worker threads.
77pub struct BorrowedIncrCompSession {
78    pub old_session_directory: Option<PathBuf>,
79    pub new_session_directory: PathBuf,
80    _borrows: Arc<()>,
81}
82
83/// Describes the contents of the fingerprint generated by a given query.
84///
85/// This is mainly for determining whether and how we can reconstruct a key
86/// from the fingerprint.
87#[derive(#[automatically_derived]impl ::core::fmt::Debug for KeyFingerprintStyle {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                KeyFingerprintStyle::DefPathHash => "DefPathHash",
                KeyFingerprintStyle::HirId => "HirId",
                KeyFingerprintStyle::Unit => "Unit",
                KeyFingerprintStyle::Opaque => "Opaque",
            })
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    KeyFingerprintStyle {
}
#[automatically_derived]impl ::core::cmp::PartialEq for KeyFingerprintStyle {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for KeyFingerprintStyle { }Eq, #[automatically_derived]impl ::core::marker::Copy for KeyFingerprintStyle { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for KeyFingerprintStyle {
}
#[automatically_derived]impl ::core::clone::Clone for KeyFingerprintStyle {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
88pub enum KeyFingerprintStyle {
89    /// The fingerprint is actually a DefPathHash.
90    DefPathHash,
91    /// The fingerprint is actually a HirId.
92    HirId,
93    /// Query key was `()` or equivalent, so fingerprint is just zero.
94    Unit,
95    /// The fingerprint is an opaque hash, and a key cannot be reconstructed from it.
96    Opaque,
97}
98
99impl KeyFingerprintStyle {
100    /// True if a key can _potentially_ be recovered from a key fingerprint
101    /// with this style.
102    ///
103    /// For some key types, recovery is possible but not guaranteed.
104    #[inline]
105    pub const fn is_maybe_recoverable(self) -> bool {
106        match self {
107            KeyFingerprintStyle::DefPathHash
108            | KeyFingerprintStyle::Unit
109            | KeyFingerprintStyle::HirId => true,
110            KeyFingerprintStyle::Opaque => false,
111        }
112    }
113}
114
115/// Execute the operation with provided dependencies.
116fn with_deps<OP, R>(task_deps: TaskDepsRef<'_>, op: OP) -> R
117where
118    OP: FnOnce() -> R,
119{
120    ty::tls::with_context(|icx| {
121        let icx = ty::tls::ImplicitCtxt { task_deps, ..*icx };
122        ty::tls::enter_context(&icx, op)
123    })
124}
125
126/// Access dependencies from current implicit context.
127fn read_deps<OP>(op: OP)
128where
129    OP: for<'a> FnOnce(TaskDepsRef<'a>),
130{
131    ty::tls::with_context_opt(|icx| {
132        let Some(icx) = icx else { return };
133        op(icx.task_deps)
134    })
135}
136
137impl<'tcx> TyCtxt<'tcx> {
138    #[inline]
139    pub fn dep_kind_vtable(self, dk: DepKind) -> &'tcx DepKindVTable<'tcx> {
140        &self.query_system.dep_kind_vtables[dk.as_usize()]
141    }
142
143    #[inline(always)]
144    pub fn key_fingerprint_style(self, kind: DepKind) -> KeyFingerprintStyle {
145        self.dep_kind_vtable(kind).key_fingerprint_style
146    }
147
148    /// Try to force a dep node to execute and see if it's green.
149    ///
150    /// Returns true if the query has actually been forced. It is valid that a query
151    /// fails to be forced, e.g. when the query key cannot be reconstructed from the
152    /// dep-node or when the query kind outright does not support it.
153    #[inline]
154    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("try_force_from_dep_node",
                                    "rustc_middle::dep_graph", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(154u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("dep_node")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("dep_node");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("prev_index")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("prev_index");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dep_node)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&prev_index)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(force_fn) =
                    self.dep_kind_vtable(dep_node.kind).force_from_dep_node_fn {
                match panic::catch_unwind(panic::AssertUnwindSafe(||
                                { force_fn(self, dep_node, prev_index) })) {
                    Err(value) => {
                        if !value.is::<rustc_errors::FatalErrorMarker>() {
                            print_markframe_trace(&self.dep_graph, frame);
                        }
                        panic::resume_unwind(value)
                    }
                    Ok(query_has_been_forced) => query_has_been_forced,
                }
            } else { false }
        }
    }
}#[instrument(skip(self, frame), level = "debug")]
155    fn try_force_from_dep_node(
156        self,
157        dep_node: DepNode,
158        prev_index: SerializedDepNodeIndex,
159        frame: &MarkFrame<'_>,
160    ) -> bool {
161        if let Some(force_fn) = self.dep_kind_vtable(dep_node.kind).force_from_dep_node_fn {
162            match panic::catch_unwind(panic::AssertUnwindSafe(|| {
163                force_fn(self, dep_node, prev_index)
164            })) {
165                Err(value) => {
166                    if !value.is::<rustc_errors::FatalErrorMarker>() {
167                        print_markframe_trace(&self.dep_graph, frame);
168                    }
169                    panic::resume_unwind(value)
170                }
171                Ok(query_has_been_forced) => query_has_been_forced,
172            }
173        } else {
174            false
175        }
176    }
177}