Skip to main content

rustc_middle/dep_graph/
graph.rs

1use std::assert_matches;
2use std::cell::Cell;
3use std::fmt::Debug;
4use std::hash::Hash;
5use std::sync::Arc;
6use std::sync::atomic::{AtomicU32, Ordering};
7
8use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint};
9use rustc_data_structures::fx::FxHashSet;
10use rustc_data_structures::profiling::QueryInvocationId;
11use rustc_data_structures::sharded::{self, ShardedHashMap};
12use rustc_data_structures::stable_hash::{StableHash, StableHasher};
13use rustc_data_structures::sync::{AtomicU64, Lock, WorkerLocal};
14use rustc_data_structures::unord::UnordMap;
15use rustc_errors::DiagInner;
16use rustc_index::IndexVec;
17use rustc_macros::{Decodable, Encodable};
18use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
19use rustc_session::Session;
20use rustc_span::Symbol;
21use tracing::instrument;
22#[cfg(debug_assertions)]
23use {super::debug::EdgeFilter, std::env};
24
25use super::retained::RetainedDepGraph;
26use super::serialized::{GraphEncoder, SerializedDepGraph, SerializedDepNodeIndex};
27use super::{DepKind, DepNode, WorkProductId, read_deps, with_deps};
28use crate::dep_graph::edges::EdgesVec;
29use crate::ich::StableHashState;
30use crate::ty::TyCtxt;
31use crate::verify_ich::incremental_verify_ich;
32
33/// Tracks 'side effects' for a particular query.
34/// This struct is saved to disk along with the query result,
35/// and loaded from disk if we mark the query as green.
36/// This allows us to 'replay' changes to global state
37/// that would otherwise only occur if we actually
38/// executed the query method.
39///
40/// Each side effect gets an unique dep node index which is added
41/// as a dependency of the query which had the effect.
42#[derive(#[automatically_derived]
impl ::core::fmt::Debug for QuerySideEffect {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            QuerySideEffect::Diagnostic(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Diagnostic", &__self_0),
            QuerySideEffect::CheckFeature { symbol: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "CheckFeature", "symbol", &__self_0),
        }
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for QuerySideEffect {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        QuerySideEffect::Diagnostic(ref __binding_0) => { 0usize }
                        QuerySideEffect::CheckFeature { symbol: ref __binding_0 } =>
                            {
                            1usize
                        }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    QuerySideEffect::Diagnostic(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    QuerySideEffect::CheckFeature { symbol: ref __binding_0 } =>
                        {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for QuerySideEffect {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        QuerySideEffect::Diagnostic(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    1usize => {
                        QuerySideEffect::CheckFeature {
                            symbol: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `QuerySideEffect`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable)]
43pub enum QuerySideEffect {
44    /// Stores a diagnostic emitted during query execution.
45    /// This diagnostic will be re-emitted if we mark
46    /// the query as green, as that query will have the side
47    /// effect dep node as a dependency.
48    Diagnostic(DiagInner),
49    /// Records the feature used during query execution.
50    /// This feature will be inserted into `sess.used_features`
51    /// if we mark the query as green, as that query will have
52    /// the side effect dep node as a dependency.
53    CheckFeature { symbol: Symbol },
54}
55
56#[derive(#[automatically_derived]
impl ::core::clone::Clone for DepGraph {
    #[inline]
    fn clone(&self) -> DepGraph {
        DepGraph {
            data: ::core::clone::Clone::clone(&self.data),
            virtual_dep_node_index: ::core::clone::Clone::clone(&self.virtual_dep_node_index),
        }
    }
}Clone)]
57pub struct DepGraph {
58    data: Option<Arc<DepGraphData>>,
59
60    /// This field is used for assigning DepNodeIndices when running in
61    /// non-incremental mode. Even in non-incremental mode we make sure that
62    /// each task has a `DepNodeIndex` that uniquely identifies it. This unique
63    /// ID is used for self-profiling.
64    virtual_dep_node_index: Arc<AtomicU32>,
65}
66
67impl ::std::fmt::Debug for DepNodeIndex {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
68    pub struct DepNodeIndex {}
69}
70
71// We store a large collection of these in `prev_index_to_index` during
72// non-full incremental builds, and want to ensure that the element size
73// doesn't inadvertently increase.
74const _: [(); 4] = [(); ::std::mem::size_of::<Option<DepNodeIndex>>()];rustc_data_structures::static_assert_size!(Option<DepNodeIndex>, 4);
75
76impl DepNodeIndex {
77    const SINGLETON_ZERO_DEPS_ANON_NODE: DepNodeIndex = DepNodeIndex::ZERO;
78    pub const FOREVER_RED_NODE: DepNodeIndex = DepNodeIndex::from_u32(1);
79}
80
81impl From<DepNodeIndex> for QueryInvocationId {
82    #[inline(always)]
83    fn from(dep_node_index: DepNodeIndex) -> Self {
84        QueryInvocationId(dep_node_index.as_u32())
85    }
86}
87
88pub(crate) struct MarkFrame<'a> {
89    index: SerializedDepNodeIndex,
90    parent: Option<&'a MarkFrame<'a>>,
91}
92
93/// The edge list of one node being marked green: it occupies `buf[start..]` of the shared
94/// scratch buffer and is popped again on drop, restoring the buffer for the enclosing call.
95struct EdgeFrame<'a> {
96    buf: &'a mut Vec<DepNodeIndex>,
97    start: usize,
98}
99
100impl<'a> EdgeFrame<'a> {
101    #[inline]
102    fn new(buf: &'a mut Vec<DepNodeIndex>) -> Self {
103        EdgeFrame { start: buf.len(), buf }
104    }
105
106    #[inline]
107    fn push(&mut self, edge: DepNodeIndex) {
108        self.buf.push(edge);
109    }
110
111    /// The edges pushed onto this frame so far.
112    #[inline]
113    fn get(&self) -> &[DepNodeIndex] {
114        &self.buf[self.start..]
115    }
116}
117
118impl Drop for EdgeFrame<'_> {
119    #[inline]
120    fn drop(&mut self) {
121        self.buf.truncate(self.start);
122    }
123}
124
125#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DepNodeColor {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            DepNodeColor::Green(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Green",
                    &__self_0),
            DepNodeColor::Red => ::core::fmt::Formatter::write_str(f, "Red"),
            DepNodeColor::Unknown =>
                ::core::fmt::Formatter::write_str(f, "Unknown"),
        }
    }
}Debug)]
126pub(super) enum DepNodeColor {
127    Green(DepNodeIndex),
128    Red,
129    Unknown,
130}
131
132pub struct DepGraphData {
133    /// The new encoding of the dependency graph, optimized for red/green
134    /// tracking. The `current` field is the dependency graph of only the
135    /// current compilation session: We don't merge the previous dep-graph into
136    /// current one anymore, but we do reference shared data to save space.
137    current: CurrentDepGraph,
138
139    /// The dep-graph from the previous compilation session. It contains all
140    /// nodes and edges as well as all fingerprints of nodes that have them.
141    previous: Arc<SerializedDepGraph>,
142
143    colors: DepNodeColorMap,
144
145    /// When we load, there may be `.o` files, cached MIR, or other such
146    /// things available to us. If we find that they are not dirty, we
147    /// load the path to the file storing those work-products here into
148    /// this map. We can later look for and extract that data.
149    previous_work_products: WorkProductMap,
150
151    /// Used by incremental compilation tests to assert that
152    /// a particular query result was decoded from disk
153    /// (not just marked green)
154    debug_loaded_from_disk: Lock<FxHashSet<DepNode>>,
155
156    /// Per-worker edge buffer amortized across `try_mark_green` calls.
157    green_edge_buf: WorkerLocal<Cell<Vec<DepNodeIndex>>>,
158}
159
160pub fn hash_result<R>(hcx: &mut StableHashState<'_>, result: &R) -> Fingerprint
161where
162    R: StableHash,
163{
164    let mut stable_hasher = StableHasher::new();
165    result.stable_hash(hcx, &mut stable_hasher);
166    stable_hasher.finish()
167}
168
169impl DepGraph {
170    pub fn new(
171        session: &Session,
172        prev_graph: Arc<SerializedDepGraph>,
173        prev_work_products: WorkProductMap,
174        encoder: FileEncoder<'static>,
175    ) -> DepGraph {
176        let prev_graph_node_count = prev_graph.node_count();
177
178        let current =
179            CurrentDepGraph::new(session, prev_graph_node_count, encoder, Arc::clone(&prev_graph));
180
181        let colors = DepNodeColorMap::new(prev_graph_node_count);
182
183        // Instantiate a node with zero dependencies only once for anonymous queries.
184        let _green_node_index = current.alloc_new_node(
185            DepNode { kind: DepKind::AnonZeroDeps, key_fingerprint: current.anon_id_seed.into() },
186            EdgesVec::new(),
187            Fingerprint::ZERO,
188        );
189        match (&_green_node_index, &DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(_green_node_index, DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE);
190
191        // Create a single always-red node, with no dependencies of its own.
192        // Other nodes can use the always-red node as a fake dependency, to
193        // ensure that their dependency list will never be all-green.
194        let red_node_index = current.alloc_new_node(
195            DepNode { kind: DepKind::Red, key_fingerprint: Fingerprint::ZERO.into() },
196            EdgesVec::new(),
197            Fingerprint::ZERO,
198        );
199        match (&red_node_index, &DepNodeIndex::FOREVER_RED_NODE) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(red_node_index, DepNodeIndex::FOREVER_RED_NODE);
200        if prev_graph_node_count > 0 {
201            let prev_index =
202                const { SerializedDepNodeIndex::from_u32(DepNodeIndex::FOREVER_RED_NODE.as_u32()) };
203            let result = colors.try_set_color(prev_index, DesiredColor::Red);
204            {
    match result {
        TrySetColorResult::Success => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "TrySetColorResult::Success", ::core::option::Option::None);
        }
    }
};assert_matches!(result, TrySetColorResult::Success);
205        }
206
207        DepGraph {
208            data: Some(Arc::new(DepGraphData {
209                previous_work_products: prev_work_products,
210                current,
211                previous: prev_graph,
212                colors,
213                debug_loaded_from_disk: Default::default(),
214                green_edge_buf: WorkerLocal::default(),
215            })),
216            virtual_dep_node_index: Arc::new(AtomicU32::new(0)),
217        }
218    }
219
220    pub fn new_disabled() -> DepGraph {
221        DepGraph { data: None, virtual_dep_node_index: Arc::new(AtomicU32::new(0)) }
222    }
223
224    #[inline]
225    pub fn data(&self) -> Option<&DepGraphData> {
226        self.data.as_deref()
227    }
228
229    /// Returns `true` if we are actually building the full dep-graph, and `false` otherwise.
230    #[inline]
231    pub fn is_fully_enabled(&self) -> bool {
232        self.data.is_some()
233    }
234
235    /// Returns a clone of the in-memory retained dep graph, if it is being built
236    /// (i.e. `-Zquery-dep-graph` is set). Cloning rather than exposing the lock keeps
237    /// callers from holding it while forcing queries, which would deadlock against a
238    /// reentrant `record` under the parallel frontend.
239    pub fn retained_dep_graph(&self) -> Option<RetainedDepGraph> {
240        self.data.as_ref().and_then(|data| data.current.encoder.retained_dep_graph())
241    }
242
243    pub fn assert_ignored(&self) {
244        if let Some(..) = self.data {
245            read_deps(|task_deps| {
246                {
    match task_deps {
        TaskDepsRef::Ignore => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "TaskDepsRef::Ignore",
                ::core::option::Option::Some(format_args!("expected no task dependency tracking")));
        }
    }
};assert_matches!(
247                    task_deps,
248                    TaskDepsRef::Ignore,
249                    "expected no task dependency tracking"
250                );
251            })
252        }
253    }
254
255    pub fn assert_eval_always(&self) {
256        if self.data.is_some() {
257            read_deps(|deps| {
258                {
    match deps {
        TaskDepsRef::EvalAlways => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "TaskDepsRef::EvalAlways",
                ::core::option::Option::Some(format_args!("expected eval always context")));
        }
    }
}assert_matches!(deps, TaskDepsRef::EvalAlways, "expected eval always context")
259            });
260        }
261    }
262
263    pub fn with_ignore<OP, R>(&self, op: OP) -> R
264    where
265        OP: FnOnce() -> R,
266    {
267        with_deps(TaskDepsRef::Ignore, op)
268    }
269
270    /// Used to wrap the deserialization of a query result from disk,
271    /// This method enforces that no new `DepNodes` are created during
272    /// query result deserialization.
273    ///
274    /// Enforcing this makes the query dep graph simpler - all nodes
275    /// must be created during the query execution, and should be
276    /// created from inside the 'body' of a query (the implementation
277    /// provided by a particular compiler crate).
278    ///
279    /// Consider the case of three queries `A`, `B`, and `C`, where
280    /// `A` invokes `B` and `B` invokes `C`:
281    ///
282    /// `A -> B -> C`
283    ///
284    /// Suppose that decoding the result of query `B` required re-computing
285    /// the query `C`. If we did not create a fresh `TaskDeps` when
286    /// decoding `B`, we would still be using the `TaskDeps` for query `A`
287    /// (if we needed to re-execute `A`). This would cause us to create
288    /// a new edge `A -> C`. If this edge did not previously
289    /// exist in the `DepGraph`, then we could end up with a different
290    /// `DepGraph` at the end of compilation, even if there were no
291    /// meaningful changes to the overall program (e.g. a newline was added).
292    /// In addition, this edge might cause a subsequent compilation run
293    /// to try to force `C` before marking other necessary nodes green. If
294    /// `C` did not exist in the new compilation session, then we could
295    /// get an ICE. Normally, we would have tried (and failed) to mark
296    /// some other query green (e.g. `item_children`) which was used
297    /// to obtain `C`, which would prevent us from ever trying to force
298    /// a nonexistent `D`.
299    ///
300    /// It might be possible to enforce that all `DepNode`s read during
301    /// deserialization already exist in the previous `DepGraph`. In
302    /// the above example, we would invoke `D` during the deserialization
303    /// of `B`. Since we correctly create a new `TaskDeps` from the decoding
304    /// of `B`, this would result in an edge `B -> D`. If that edge already
305    /// existed (with the same `DepPathHash`es), then it should be correct
306    /// to allow the invocation of the query to proceed during deserialization
307    /// of a query result. We would merely assert that the dep-graph fragment
308    /// that would have been added by invoking `C` while decoding `B`
309    /// is equivalent to the dep-graph fragment that we already instantiated for B
310    /// (at the point where we successfully marked B as green).
311    ///
312    /// However, this would require additional complexity
313    /// in the query infrastructure, and is not currently needed by the
314    /// decoding of any query results. Should the need arise in the future,
315    /// we should consider extending the query system with this functionality.
316    pub fn with_query_deserialization<OP, R>(&self, op: OP) -> R
317    where
318        OP: FnOnce() -> R,
319    {
320        with_deps(TaskDepsRef::Forbid, op)
321    }
322
323    #[inline(always)]
324    pub fn with_task<'tcx, OP, R>(
325        &self,
326        dep_node: DepNode,
327        tcx: TyCtxt<'tcx>,
328        op: OP,
329        hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
330    ) -> (R, DepNodeIndex)
331    where
332        OP: FnOnce() -> R,
333    {
334        match self.data() {
335            Some(data) => data.with_task(dep_node, tcx, op, hash_result),
336            None => (op(), self.next_virtual_depnode_index()),
337        }
338    }
339
340    pub fn with_anon_task<'tcx, OP, R>(
341        &self,
342        tcx: TyCtxt<'tcx>,
343        dep_kind: DepKind,
344        op: OP,
345    ) -> (R, DepNodeIndex)
346    where
347        OP: FnOnce() -> R,
348    {
349        match self.data() {
350            Some(data) => {
351                let (result, index) = data.with_anon_task_inner(tcx, dep_kind, op);
352                self.read_index(index);
353                (result, index)
354            }
355            None => (op(), self.next_virtual_depnode_index()),
356        }
357    }
358}
359
360impl DepGraphData {
361    #[inline(always)]
362    pub fn with_task<'tcx, OP, R>(
363        &self,
364        dep_node: DepNode,
365        tcx: TyCtxt<'tcx>,
366        op: OP,
367        hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
368    ) -> (R, DepNodeIndex)
369    where
370        OP: FnOnce() -> R,
371    {
372        // If the following assertion triggers, it can have two reasons:
373        // 1. Something is wrong with DepNode creation, either here or
374        //    in `DepGraph::try_mark_green()`.
375        // 2. Two distinct query keys get mapped to the same `DepNode`
376        //    (see for example #48923).
377        self.assert_dep_node_not_yet_allocated_in_current_session(tcx.sess, &dep_node, || {
378            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("forcing query with already existing `DepNode`: {0:?}",
                dep_node))
    })format!("forcing query with already existing `DepNode`: {dep_node:?}")
379        });
380
381        let (result, edges) = if tcx.is_eval_always(dep_node.kind) {
382            (with_deps(TaskDepsRef::EvalAlways, op), EdgesVec::new())
383        } else {
384            let task_deps = Lock::new(TaskDeps::new(
385                #[cfg(debug_assertions)]
386                Some(dep_node),
387                0,
388            ));
389            (with_deps(TaskDepsRef::Allow(&task_deps), op), task_deps.into_inner().reads)
390        };
391
392        let dep_node_index =
393            self.hash_result_and_alloc_node(tcx, dep_node, edges, &result, hash_result);
394
395        (result, dep_node_index)
396    }
397
398    /// Executes something within an "anonymous" task, that is, a task the
399    /// `DepNode` of which is determined by the list of inputs it read from.
400    ///
401    /// NOTE: this does not actually count as a read of the DepNode here.
402    /// Using the result of this task without reading the DepNode will result
403    /// in untracked dependencies which may lead to ICEs as nodes are
404    /// incorrectly marked green.
405    ///
406    /// FIXME: This could perhaps return a `WithDepNode` to ensure that the
407    /// user of this function actually performs the read.
408    fn with_anon_task_inner<'tcx, OP, R>(
409        &self,
410        tcx: TyCtxt<'tcx>,
411        dep_kind: DepKind,
412        op: OP,
413    ) -> (R, DepNodeIndex)
414    where
415        OP: FnOnce() -> R,
416    {
417        if true {
    if !!tcx.is_eval_always(dep_kind) {
        ::core::panicking::panic("assertion failed: !tcx.is_eval_always(dep_kind)")
    };
};debug_assert!(!tcx.is_eval_always(dep_kind));
418
419        // Large numbers of reads are common enough here that pre-sizing `read_set`
420        // to 128 actually helps perf on some benchmarks.
421        let task_deps = Lock::new(TaskDeps::new(
422            #[cfg(debug_assertions)]
423            None,
424            128,
425        ));
426        let result = with_deps(TaskDepsRef::Allow(&task_deps), op);
427        let task_deps = task_deps.into_inner();
428        let reads = task_deps.reads;
429
430        let dep_node_index = match reads.len() {
431            0 => {
432                // Because the dep-node id of anon nodes is computed from the sets of its
433                // dependencies we already know what the ID of this dependency-less node is
434                // going to be (i.e. equal to the precomputed
435                // `SINGLETON_DEPENDENCYLESS_ANON_NODE`). As a consequence we can skip creating
436                // a `StableHasher` and sending the node through interning.
437                DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE
438            }
439            1 => {
440                // When there is only one dependency, don't bother creating a node.
441                reads[0]
442            }
443            _ => {
444                // The dep node indices are hashed here instead of hashing the dep nodes of the
445                // dependencies. These indices may refer to different nodes per session, but this
446                // isn't a problem here because we that ensure the final dep node hash is per
447                // session only by combining it with the per session `anon_id_seed`. This hash only
448                // need to map the dependencies to a single value on a per session basis.
449                let mut hasher = StableHasher::new();
450                reads.hash(&mut hasher);
451
452                let target_dep_node = DepNode {
453                    kind: dep_kind,
454                    // Fingerprint::combine() is faster than sending Fingerprint
455                    // through the StableHasher (at least as long as StableHasher
456                    // is so slow).
457                    key_fingerprint: self.current.anon_id_seed.combine(hasher.finish()).into(),
458                };
459
460                // The DepNodes generated by the process above are not unique. 2 queries could
461                // have exactly the same dependencies. However, deserialization does not handle
462                // duplicated nodes, so we do the deduplication here directly.
463                //
464                // As anonymous nodes are a small quantity compared to the full dep-graph, the
465                // memory impact of this `anon_node_to_index` map remains tolerable, and helps
466                // us avoid useless growth of the graph with almost-equivalent nodes.
467                self.current.anon_node_to_index.get_or_insert_with(target_dep_node, || {
468                    self.current.alloc_new_node(target_dep_node, reads, Fingerprint::ZERO)
469                })
470            }
471        };
472
473        (result, dep_node_index)
474    }
475
476    /// Intern the new `DepNode` with the dependencies up-to-now.
477    fn hash_result_and_alloc_node<'tcx, R>(
478        &self,
479        tcx: TyCtxt<'tcx>,
480        node: DepNode,
481        edges: EdgesVec,
482        result: &R,
483        hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
484    ) -> DepNodeIndex {
485        let hashing_timer = tcx.prof.incr_result_hashing();
486        let current_fingerprint = hash_result.map(|hash_result| {
487            tcx.with_stable_hashing_context(|mut hcx| hash_result(&mut hcx, result))
488        });
489        let dep_node_index = self.alloc_and_color_node(node, edges, current_fingerprint);
490        hashing_timer.finish_with_query_invocation_id(dep_node_index.into());
491        dep_node_index
492    }
493}
494
495impl DepGraph {
496    #[inline]
497    pub fn read_index(&self, dep_node_index: DepNodeIndex) {
498        if let Some(ref data) = self.data {
499            read_deps(|task_deps| {
500                let mut task_deps = match task_deps {
501                    TaskDepsRef::Allow(deps) => deps.lock(),
502                    TaskDepsRef::EvalAlways => {
503                        // We don't need to record dependencies of eval_always
504                        // queries. They are re-evaluated unconditionally anyway.
505                        return;
506                    }
507                    TaskDepsRef::Ignore => return,
508                    TaskDepsRef::Forbid => {
509                        // Reading is forbidden in this context. ICE with a useful error message.
510                        panic_on_forbidden_read(data, dep_node_index)
511                    }
512                };
513                let task_deps = &mut *task_deps;
514
515                if truecfg!(debug_assertions) {
516                    data.current.total_read_count.fetch_add(1, Ordering::Relaxed);
517                }
518
519                // Has `dep_node_index` been seen before? Use either a linear scan or a hashset
520                // lookup to determine this. See `TaskDeps::read_set` for details.
521                let new_read = if task_deps.reads.len() <= TaskDeps::LINEAR_SCAN_MAX {
522                    !task_deps.reads.contains(&dep_node_index)
523                } else {
524                    task_deps.read_set.insert(dep_node_index)
525                };
526                if new_read {
527                    task_deps.reads.push(dep_node_index);
528                    if task_deps.reads.len() == TaskDeps::LINEAR_SCAN_MAX + 1 {
529                        // Fill `read_set` with what we have so far. Future lookups will use it.
530                        task_deps.read_set.extend(task_deps.reads.iter().copied());
531                    }
532
533                    #[cfg(debug_assertions)]
534                    {
535                        if let Some(target) = task_deps.node
536                            && let Some(ref forbidden_edge) = data.current.forbidden_edge
537                        {
538                            let src = forbidden_edge.index_to_node.lock()[&dep_node_index];
539                            if forbidden_edge.test(&src, &target) {
540                                {
    ::core::panicking::panic_fmt(format_args!("forbidden edge {0:?} -> {1:?} created",
            src, target));
}panic!("forbidden edge {:?} -> {:?} created", src, target)
541                            }
542                        }
543                    }
544                } else if truecfg!(debug_assertions) {
545                    data.current.total_duplicate_read_count.fetch_add(1, Ordering::Relaxed);
546                }
547            })
548        }
549    }
550
551    /// This encodes a side effect by creating a node with an unique index and associating
552    /// it with the node, for use in the next session.
553    #[inline]
554    pub fn record_diagnostic<'tcx>(&self, tcx: TyCtxt<'tcx>, diagnostic: &DiagInner) {
555        if let Some(ref data) = self.data {
556            read_deps(|task_deps| match task_deps {
557                TaskDepsRef::EvalAlways | TaskDepsRef::Ignore => return,
558                TaskDepsRef::Forbid | TaskDepsRef::Allow(..) => {
559                    let dep_node_index = data
560                        .encode_side_effect(tcx, QuerySideEffect::Diagnostic(diagnostic.clone()));
561                    self.read_index(dep_node_index);
562                }
563            })
564        }
565    }
566    /// This forces a side effect node green by running its side effect. `prev_index` would
567    /// refer to a node created used `encode_side_effect` in the previous session.
568    #[inline]
569    pub fn force_side_effect<'tcx>(&self, tcx: TyCtxt<'tcx>, prev_index: SerializedDepNodeIndex) {
570        if let Some(ref data) = self.data {
571            data.force_side_effect(tcx, prev_index);
572        }
573    }
574
575    #[inline]
576    pub fn encode_side_effect<'tcx>(
577        &self,
578        tcx: TyCtxt<'tcx>,
579        side_effect: QuerySideEffect,
580    ) -> DepNodeIndex {
581        if let Some(ref data) = self.data {
582            data.encode_side_effect(tcx, side_effect)
583        } else {
584            self.next_virtual_depnode_index()
585        }
586    }
587
588    /// Create a node when we force-feed a value into the query cache.
589    /// This is used to remove cycles during type-checking const generic parameters.
590    ///
591    /// As usual in the query system, we consider the current state of the calling query
592    /// only depends on the list of dependencies up to now. As a consequence, the value
593    /// that this query gives us can only depend on those dependencies too. Therefore,
594    /// it is sound to use the current dependency set for the created node.
595    ///
596    /// During replay, the order of the nodes is relevant in the dependency graph.
597    /// So the unchanged replay will mark the caller query before trying to mark this one.
598    /// If there is a change to report, the caller query will be re-executed before this one.
599    ///
600    /// FIXME: If the code is changed enough for this node to be marked before requiring the
601    /// caller's node, we suppose that those changes will be enough to mark this node red and
602    /// force a recomputation using the "normal" way.
603    pub fn with_feed_task<'tcx, R>(
604        &self,
605        node: DepNode,
606        tcx: TyCtxt<'tcx>,
607        result: &R,
608        hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
609        format_value_fn: fn(&R) -> String,
610    ) -> DepNodeIndex {
611        if let Some(data) = self.data.as_ref() {
612            // The caller query has more dependencies than the node we are creating. We may
613            // encounter a case where this created node is marked as green, but the caller query is
614            // subsequently marked as red or recomputed. In this case, we will end up feeding a
615            // value to an existing node.
616            //
617            // For sanity, we still check that the loaded stable hash and the new one match.
618            if let Some(prev_index) = data.previous.node_to_index_opt(&node) {
619                let dep_node_index = data.colors.current(prev_index);
620                if let Some(dep_node_index) = dep_node_index {
621                    incremental_verify_ich(
622                        tcx,
623                        data,
624                        result,
625                        prev_index,
626                        hash_result,
627                        format_value_fn,
628                    );
629
630                    #[cfg(debug_assertions)]
631                    if hash_result.is_some() {
632                        data.current.record_edge(
633                            dep_node_index,
634                            node,
635                            data.prev_value_fingerprint_of(prev_index),
636                        );
637                    }
638
639                    return dep_node_index;
640                }
641            }
642
643            let mut edges = EdgesVec::new();
644            read_deps(|task_deps| match task_deps {
645                TaskDepsRef::Allow(deps) => edges.extend(deps.lock().reads.iter().copied()),
646                TaskDepsRef::EvalAlways => {
647                    edges.push(DepNodeIndex::FOREVER_RED_NODE);
648                }
649                TaskDepsRef::Ignore => {}
650                TaskDepsRef::Forbid => {
651                    {
    ::core::panicking::panic_fmt(format_args!("Cannot summarize when dependencies are not recorded."));
}panic!("Cannot summarize when dependencies are not recorded.")
652                }
653            });
654
655            data.hash_result_and_alloc_node(tcx, node, edges, result, hash_result)
656        } else {
657            // Incremental compilation is turned off. We just execute the task
658            // without tracking. We still provide a dep-node index that uniquely
659            // identifies the task so that we have a cheap way of referring to
660            // the query for self-profiling.
661            self.next_virtual_depnode_index()
662        }
663    }
664}
665
666impl DepGraphData {
667    fn assert_dep_node_not_yet_allocated_in_current_session<S: std::fmt::Display>(
668        &self,
669        sess: &Session,
670        dep_node: &DepNode,
671        msg: impl FnOnce() -> S,
672    ) {
673        if let Some(prev_index) = self.previous.node_to_index_opt(dep_node) {
674            let color = self.colors.get(prev_index);
675            let ok = match color {
676                DepNodeColor::Unknown => true,
677                DepNodeColor::Red => false,
678                DepNodeColor::Green(..) => sess.threads().is_some(), // Other threads may mark this green
679            };
680            if !ok {
681                { ::core::panicking::panic_display(&msg()); }panic!("{}", msg())
682            }
683        }
684    }
685
686    fn node_color(&self, dep_node: &DepNode) -> DepNodeColor {
687        if let Some(prev_index) = self.previous.node_to_index_opt(dep_node) {
688            self.colors.get(prev_index)
689        } else {
690            // This is a node that did not exist in the previous compilation session.
691            DepNodeColor::Unknown
692        }
693    }
694
695    /// Returns true if the given node has been marked as green during the
696    /// current compilation session. Used in various assertions
697    #[inline]
698    pub fn is_index_green(&self, prev_index: SerializedDepNodeIndex) -> bool {
699        #[allow(non_exhaustive_omitted_patterns)] match self.colors.get(prev_index) {
    DepNodeColor::Green(_) => true,
    _ => false,
}matches!(self.colors.get(prev_index), DepNodeColor::Green(_))
700    }
701
702    #[inline]
703    pub fn prev_value_fingerprint_of(&self, prev_index: SerializedDepNodeIndex) -> Fingerprint {
704        self.previous.value_fingerprint_for_index(prev_index)
705    }
706
707    #[inline]
708    pub(crate) fn prev_node_of(&self, prev_index: SerializedDepNodeIndex) -> &DepNode {
709        self.previous.index_to_node(prev_index)
710    }
711
712    pub fn mark_debug_loaded_from_disk(&self, dep_node: DepNode) {
713        self.debug_loaded_from_disk.lock().insert(dep_node);
714    }
715
716    /// This encodes a side effect by creating a node with an unique index and associating
717    /// it with the node, for use in the next session.
718    #[inline]
719    fn encode_side_effect<'tcx>(
720        &self,
721        tcx: TyCtxt<'tcx>,
722        side_effect: QuerySideEffect,
723    ) -> DepNodeIndex {
724        // Use `send_new` so we get an unique index, even though the dep node is not.
725        let dep_node_index = self.current.encoder.send_new(
726            DepNode {
727                kind: DepKind::SideEffect,
728                key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
729            },
730            Fingerprint::ZERO,
731            // We want the side effect node to always be red so it will be forced and run the
732            // side effect.
733            std::iter::once(DepNodeIndex::FOREVER_RED_NODE).collect(),
734        );
735        tcx.query_system.side_effects.borrow_mut().insert(dep_node_index, side_effect);
736        dep_node_index
737    }
738
739    /// This forces a side effect node green by running its side effect. `prev_index` would
740    /// refer to a node created used `encode_side_effect` in the previous session.
741    #[inline]
742    fn force_side_effect<'tcx>(&self, tcx: TyCtxt<'tcx>, prev_index: SerializedDepNodeIndex) {
743        with_deps(TaskDepsRef::Ignore, || {
744            let side_effect = tcx
745                .query_system
746                .on_disk_cache
747                .as_ref()
748                .unwrap()
749                .load_side_effect(tcx, prev_index)
750                .unwrap();
751
752            // Use `send_and_color` as `promote_node_and_deps_to_current` expects all
753            // green dependencies. `send_and_color` will also prevent multiple nodes
754            // being encoded for concurrent calls.
755            let dep_node_index = self.current.encoder.send_and_color(
756                prev_index,
757                &self.colors,
758                DepNode {
759                    kind: DepKind::SideEffect,
760                    key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
761                },
762                Fingerprint::ZERO,
763                std::iter::once(DepNodeIndex::FOREVER_RED_NODE).collect(),
764                true,
765            );
766
767            match &side_effect {
768                QuerySideEffect::Diagnostic(diagnostic) => {
769                    tcx.dcx().emit_diagnostic(diagnostic.clone());
770                }
771                QuerySideEffect::CheckFeature { symbol } => {
772                    tcx.sess.used_features.lock().insert(*symbol, dep_node_index.as_u32());
773                }
774            }
775
776            // This will just overwrite the same value for concurrent calls.
777            tcx.query_system.side_effects.borrow_mut().insert(dep_node_index, side_effect);
778        })
779    }
780
781    fn alloc_and_color_node(
782        &self,
783        key: DepNode,
784        edges: EdgesVec,
785        value_fingerprint: Option<Fingerprint>,
786    ) -> DepNodeIndex {
787        if let Some(prev_index) = self.previous.node_to_index_opt(&key) {
788            // Determine the color and index of the new `DepNode`.
789            let is_green = if let Some(value_fingerprint) = value_fingerprint {
790                if value_fingerprint == self.previous.value_fingerprint_for_index(prev_index) {
791                    // This is a green node: it existed in the previous compilation,
792                    // its query was re-executed, and it has the same result as before.
793                    true
794                } else {
795                    // This is a red node: it existed in the previous compilation, its query
796                    // was re-executed, but it has a different result from before.
797                    false
798                }
799            } else {
800                // This is a red node, effectively: it existed in the previous compilation
801                // session, its query was re-executed, but it doesn't compute a result hash
802                // (i.e. it represents a `no_hash` query), so we have no way of determining
803                // whether or not the result was the same as before.
804                false
805            };
806
807            let value_fingerprint = value_fingerprint.unwrap_or(Fingerprint::ZERO);
808
809            let dep_node_index = self.current.encoder.send_and_color(
810                prev_index,
811                &self.colors,
812                key,
813                value_fingerprint,
814                edges,
815                is_green,
816            );
817
818            #[cfg(debug_assertions)]
819            self.current.record_edge(dep_node_index, key, value_fingerprint);
820
821            dep_node_index
822        } else {
823            self.current.alloc_new_node(key, edges, value_fingerprint.unwrap_or(Fingerprint::ZERO))
824        }
825    }
826
827    fn promote_node_and_deps_to_current(
828        &self,
829        prev_index: SerializedDepNodeIndex,
830        edges: &[DepNodeIndex],
831    ) -> Option<DepNodeIndex> {
832        let dep_node_index = self.current.encoder.send_promoted(prev_index, &self.colors, edges);
833
834        #[cfg(debug_assertions)]
835        if let Some(dep_node_index) = dep_node_index {
836            self.current.record_edge(
837                dep_node_index,
838                *self.previous.index_to_node(prev_index),
839                self.previous.value_fingerprint_for_index(prev_index),
840            );
841        }
842
843        dep_node_index
844    }
845}
846
847impl DepGraph {
848    /// Checks whether a previous work product exists for `v` and, if
849    /// so, return the path that leads to it. Used to skip doing work.
850    pub fn previous_work_product(&self, v: &WorkProductId) -> Option<WorkProduct> {
851        self.data.as_ref().and_then(|data| data.previous_work_products.get(v).cloned())
852    }
853
854    /// Access the map of work-products created during the cached run. Only
855    /// used during saving of the dep-graph.
856    pub fn previous_work_products(&self) -> &WorkProductMap {
857        &self.data.as_ref().unwrap().previous_work_products
858    }
859
860    pub fn debug_was_loaded_from_disk(&self, dep_node: DepNode) -> bool {
861        self.data.as_ref().unwrap().debug_loaded_from_disk.lock().contains(&dep_node)
862    }
863
864    pub fn debug_dep_kind_was_loaded_from_disk(&self, dep_kind: DepKind) -> bool {
865        // We only check if we have a dep node corresponding to the given dep kind.
866        #[allow(rustc::potential_query_instability)]
867        self.data
868            .as_ref()
869            .unwrap()
870            .debug_loaded_from_disk
871            .lock()
872            .iter()
873            .any(|node| node.kind == dep_kind)
874    }
875
876    fn node_color(&self, dep_node: &DepNode) -> DepNodeColor {
877        if let Some(ref data) = self.data {
878            return data.node_color(dep_node);
879        }
880
881        DepNodeColor::Unknown
882    }
883
884    pub fn try_mark_green<'tcx>(
885        &self,
886        tcx: TyCtxt<'tcx>,
887        dep_node: &DepNode,
888    ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
889        self.data()?.try_mark_green(tcx, dep_node)
890    }
891}
892
893impl DepGraphData {
894    /// Try to mark a node index for the node dep_node.
895    ///
896    /// A node will have an index, when it's already been marked green, or when we can mark it
897    /// green. This function will mark the current task as a reader of the specified node, when
898    /// a node index can be found for that node.
899    pub fn try_mark_green<'tcx>(
900        &self,
901        tcx: TyCtxt<'tcx>,
902        dep_node: &DepNode,
903    ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
904        if true {
    if !!tcx.is_eval_always(dep_node.kind) {
        ::core::panicking::panic("assertion failed: !tcx.is_eval_always(dep_node.kind)")
    };
};debug_assert!(!tcx.is_eval_always(dep_node.kind));
905
906        // Return None if the dep node didn't exist in the previous session
907        let prev_index = self.previous.node_to_index_opt(dep_node)?;
908
909        if true {
    match (&self.previous.index_to_node(prev_index), &dep_node) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(self.previous.index_to_node(prev_index), dep_node);
910
911        match self.colors.get(prev_index) {
912            DepNodeColor::Green(dep_node_index) => Some((prev_index, dep_node_index)),
913            DepNodeColor::Red => None,
914            DepNodeColor::Unknown => {
915                // This DepNode and the corresponding query invocation existed
916                // in the previous compilation session too, so we can try to
917                // mark it as green by recursively marking all of its
918                // dependencies green.
919
920                // Reuse a per-worker buffer for the edges instead of allocating one per call.
921                // The recursion gives it back empty: each `EdgeFrame` pops its edges on drop.
922                let mut edge_buf = self.green_edge_buf.take();
923                let result = self.try_mark_previous_green(tcx, prev_index, None, &mut edge_buf);
924                if true {
    if !edge_buf.is_empty() {
        ::core::panicking::panic("assertion failed: edge_buf.is_empty()")
    };
};debug_assert!(edge_buf.is_empty());
925                self.green_edge_buf.set(edge_buf);
926                result.map(|dep_node_index| (prev_index, dep_node_index))
927            }
928        }
929    }
930
931    /// Try to mark a dep-node which existed in the previous compilation session as green.
932    #[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_mark_previous_green",
                                    "rustc_middle::dep_graph::graph", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/graph.rs"),
                                    ::tracing_core::__macro_support::Option::Some(932u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::graph"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set(&[]) })
                } 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: Option<DepNodeIndex> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut edges = EdgeFrame::new(edge_buf);
            let frame =
                MarkFrame { index: prev_dep_node_index, parent: frame };
            if true {
                if !!tcx.is_eval_always(self.previous.index_to_node(prev_dep_node_index).kind)
                    {
                    ::core::panicking::panic("assertion failed: !tcx.is_eval_always(self.previous.index_to_node(prev_dep_node_index).kind)")
                };
            };
            for parent_dep_node_index in
                self.previous.edge_targets_from(prev_dep_node_index) {
                match self.colors.get(parent_dep_node_index) {
                    DepNodeColor::Green(parent_index) => {
                        edges.push(parent_index);
                        continue;
                    }
                    DepNodeColor::Red => return None,
                    DepNodeColor::Unknown => {}
                }
                let parent_dep_node =
                    self.previous.index_to_node(parent_dep_node_index);
                if !tcx.is_eval_always(parent_dep_node.kind) &&
                        let Some(parent_index) =
                            self.try_mark_previous_green(tcx, parent_dep_node_index,
                                Some(&frame), edges.buf) {
                    edges.push(parent_index);
                    continue;
                }
                if !tcx.try_force_from_dep_node(*parent_dep_node,
                            parent_dep_node_index, &frame) {
                    return None;
                }
                match self.colors.get(parent_dep_node_index) {
                    DepNodeColor::Green(parent_index) => {
                        edges.push(parent_index);
                        continue;
                    }
                    DepNodeColor::Red => return None,
                    DepNodeColor::Unknown => {}
                }
                if tcx.dcx().has_errors_or_delayed_bugs().is_none() {
                    {
                        ::core::panicking::panic_fmt(format_args!("try_mark_previous_green() - forcing failed to set a color"));
                    };
                }
                return None;
            }
            let dep_node_index =
                self.promote_node_and_deps_to_current(prev_dep_node_index,
                        edges.get())?;
            Some(dep_node_index)
        }
    }
}#[instrument(skip(self, tcx, prev_dep_node_index, frame, edge_buf), level = "debug")]
933    fn try_mark_previous_green<'tcx>(
934        &self,
935        tcx: TyCtxt<'tcx>,
936        prev_dep_node_index: SerializedDepNodeIndex,
937        frame: Option<&MarkFrame<'_>>,
938        // Amortized buffer to store edges in.
939        edge_buf: &mut Vec<DepNodeIndex>,
940    ) -> Option<DepNodeIndex> {
941        let mut edges = EdgeFrame::new(edge_buf);
942        let frame = MarkFrame { index: prev_dep_node_index, parent: frame };
943
944        // We never try to mark eval_always nodes as green
945        debug_assert!(!tcx.is_eval_always(self.previous.index_to_node(prev_dep_node_index).kind));
946
947        for parent_dep_node_index in self.previous.edge_targets_from(prev_dep_node_index) {
948            match self.colors.get(parent_dep_node_index) {
949                // This dependency has been marked as green before, we are still ok and can
950                // continue checking the remaining dependencies.
951                DepNodeColor::Green(parent_index) => {
952                    edges.push(parent_index);
953                    continue;
954                }
955
956                // This dependency's result is different to the previous compilation session. We
957                // cannot mark this dep_node as green, so stop checking.
958                DepNodeColor::Red => return None,
959
960                // We still need to determine this dependency's colour.
961                DepNodeColor::Unknown => {}
962            }
963
964            let parent_dep_node = self.previous.index_to_node(parent_dep_node_index);
965
966            // If this dependency isn't eval_always, try to mark it green recursively.
967            if !tcx.is_eval_always(parent_dep_node.kind)
968                && let Some(parent_index) = self.try_mark_previous_green(
969                    tcx,
970                    parent_dep_node_index,
971                    Some(&frame),
972                    // Pass the edge buffer to the recursive call.
973                    // It will use an `EdgeFrame` to give it back unchanged.
974                    edges.buf,
975                )
976            {
977                edges.push(parent_index);
978                continue;
979            }
980
981            // We failed to mark it green, so we try to force the query.
982            if !tcx.try_force_from_dep_node(*parent_dep_node, parent_dep_node_index, &frame) {
983                return None;
984            }
985
986            match self.colors.get(parent_dep_node_index) {
987                DepNodeColor::Green(parent_index) => {
988                    edges.push(parent_index);
989                    continue;
990                }
991                DepNodeColor::Red => return None,
992                DepNodeColor::Unknown => {}
993            }
994
995            if tcx.dcx().has_errors_or_delayed_bugs().is_none() {
996                panic!("try_mark_previous_green() - forcing failed to set a color");
997            }
998
999            // If the query we just forced has resulted in some kind of compilation error, we
1000            // cannot rely on the dep-node color having been properly updated. This means that the
1001            // query system has reached an invalid state. We let the compiler continue (by
1002            // returning `None`) so it can emit error messages and wind down, but rely on the fact
1003            // that this invalid state will not be persisted to the incremental compilation cache
1004            // because of compilation errors being present.
1005            return None;
1006        }
1007
1008        // If we got here without hitting a `return` that means that all
1009        // dependencies of this DepNode could be marked as green. Therefore we
1010        // can also mark this DepNode as green.
1011
1012        // There may be multiple threads trying to mark the same dep node green concurrently.
1013
1014        // We allocating an entry for the node in the current dependency graph and
1015        // adding all the appropriate edges imported from the previous graph.
1016        //
1017        // `no_hash` nodes may fail this promotion due to already being conservatively colored red.
1018        let dep_node_index =
1019            self.promote_node_and_deps_to_current(prev_dep_node_index, edges.get())?;
1020
1021        // ... and finally storing a "Green" entry in the color map.
1022        // Multiple threads can all write the same color here.
1023
1024        Some(dep_node_index)
1025    }
1026}
1027
1028impl DepGraph {
1029    /// Returns true if the given node has been marked as red during the
1030    /// current compilation session. Used in various assertions
1031    pub fn is_red(&self, dep_node: &DepNode) -> bool {
1032        #[allow(non_exhaustive_omitted_patterns)] match self.node_color(dep_node) {
    DepNodeColor::Red => true,
    _ => false,
}matches!(self.node_color(dep_node), DepNodeColor::Red)
1033    }
1034
1035    /// Returns true if the given node has been marked as green during the
1036    /// current compilation session. Used in various assertions
1037    pub fn is_green(&self, dep_node: &DepNode) -> bool {
1038        #[allow(non_exhaustive_omitted_patterns)] match self.node_color(dep_node) {
    DepNodeColor::Green(_) => true,
    _ => false,
}matches!(self.node_color(dep_node), DepNodeColor::Green(_))
1039    }
1040
1041    pub fn assert_dep_node_not_yet_allocated_in_current_session<S: std::fmt::Display>(
1042        &self,
1043        sess: &Session,
1044        dep_node: &DepNode,
1045        msg: impl FnOnce() -> S,
1046    ) {
1047        if let Some(data) = &self.data {
1048            data.assert_dep_node_not_yet_allocated_in_current_session(sess, dep_node, msg)
1049        }
1050    }
1051
1052    /// This method loads all on-disk cacheable query results into memory, so
1053    /// they can be written out to the new cache file again. Most query results
1054    /// will already be in memory but in the case where we marked something as
1055    /// green but then did not need the value, that value will never have been
1056    /// loaded from disk.
1057    ///
1058    /// This method will only load queries that will end up in the disk cache.
1059    /// Other queries will not be executed.
1060    pub fn exec_cache_promotions<'tcx>(&self, tcx: TyCtxt<'tcx>) {
1061        let _prof_timer = tcx.prof.generic_activity("incr_comp_query_cache_promotion");
1062
1063        let data = self.data.as_ref().unwrap();
1064        for prev_index in data.colors.values.indices() {
1065            match data.colors.get(prev_index) {
1066                DepNodeColor::Green(_) => {
1067                    let dep_node = data.previous.index_to_node(prev_index);
1068                    if let Some(promote_fn) =
1069                        tcx.dep_kind_vtable(dep_node.kind).promote_from_disk_fn
1070                    {
1071                        promote_fn(tcx, *dep_node)
1072                    };
1073                }
1074                DepNodeColor::Unknown | DepNodeColor::Red => {
1075                    // We can skip red nodes because a node can only be marked
1076                    // as red if the query result was recomputed and thus is
1077                    // already in memory.
1078                }
1079            }
1080        }
1081    }
1082
1083    pub(crate) fn finish_encoding(&self) -> FileEncodeResult {
1084        if let Some(data) = &self.data { data.current.encoder.finish(&data.current) } else { Ok(0) }
1085    }
1086
1087    pub fn next_virtual_depnode_index(&self) -> DepNodeIndex {
1088        if true {
    if !self.data.is_none() {
        ::core::panicking::panic("assertion failed: self.data.is_none()")
    };
};debug_assert!(self.data.is_none());
1089        let index = self.virtual_dep_node_index.fetch_add(1, Ordering::Relaxed);
1090        DepNodeIndex::from_u32(index)
1091    }
1092}
1093
1094/// A "work product" is an intermediate result that we save into the
1095/// incremental directory for later re-use. The primary example are
1096/// the object files that we save for each partition at code
1097/// generation time.
1098///
1099/// Each work product is associated with a dep-node, representing the
1100/// process that produced the work-product. If that dep-node is found
1101/// to be dirty when we load up, then we will delete the work-product
1102/// at load time. If the work-product is found to be clean, then we
1103/// will keep a record in the `previous_work_products` list.
1104///
1105/// In addition, work products have an associated hash. This hash is
1106/// an extra hash that can be used to decide if the work-product from
1107/// a previous compilation can be re-used (in addition to the dirty
1108/// edges check).
1109///
1110/// As the primary example, consider the object files we generate for
1111/// each partition. In the first run, we create partitions based on
1112/// the symbols that need to be compiled. For each partition P, we
1113/// hash the symbols in P and create a `WorkProduct` record associated
1114/// with `DepNode::CodegenUnit(P)`; the hash is the set of symbols
1115/// in P.
1116///
1117/// The next time we compile, if the `DepNode::CodegenUnit(P)` is
1118/// judged to be clean (which means none of the things we read to
1119/// generate the partition were found to be dirty), it will be loaded
1120/// into previous work products. We will then regenerate the set of
1121/// symbols in the partition P and hash them (note that new symbols
1122/// may be added -- for example, new monomorphizations -- even if
1123/// nothing in P changed!). We will compare that hash against the
1124/// previous hash. If it matches up, we can reuse the object file.
1125#[derive(#[automatically_derived]
impl ::core::clone::Clone for WorkProduct {
    #[inline]
    fn clone(&self) -> WorkProduct {
        WorkProduct {
            cgu_name: ::core::clone::Clone::clone(&self.cgu_name),
            saved_files: ::core::clone::Clone::clone(&self.saved_files),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for WorkProduct {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "WorkProduct",
            "cgu_name", &self.cgu_name, "saved_files", &&self.saved_files)
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for WorkProduct {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    WorkProduct {
                        cgu_name: ref __binding_0, saved_files: ref __binding_1 } =>
                        {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for WorkProduct {
            fn decode(__decoder: &mut __D) -> Self {
                WorkProduct {
                    cgu_name: ::rustc_serialize::Decodable::decode(__decoder),
                    saved_files: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
1126pub struct WorkProduct {
1127    pub cgu_name: String,
1128    /// Saved files associated with this CGU. In each key/value pair, the value is the path to the
1129    /// saved file and the key is some identifier for the type of file being saved.
1130    ///
1131    /// By convention, file extensions are currently used as identifiers, i.e. the key "o" maps to
1132    /// the object file's path, and "dwo" to the dwarf object file's path.
1133    pub saved_files: UnordMap<String, String>,
1134}
1135
1136pub type WorkProductMap = UnordMap<WorkProductId, WorkProduct>;
1137
1138// Index type for `DepNodeData`'s edges.
1139impl ::std::fmt::Debug for EdgeIndex {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
1140    struct EdgeIndex {}
1141}
1142
1143/// `CurrentDepGraph` stores the dependency graph for the current session. It
1144/// will be populated as we run queries or tasks. We never remove nodes from the
1145/// graph: they are only added.
1146///
1147/// The nodes in it are identified by a `DepNodeIndex`. We avoid keeping the nodes
1148/// in memory. This is important, because these graph structures are some of the
1149/// largest in the compiler.
1150///
1151/// For this reason, we avoid storing `DepNode`s more than once as map
1152/// keys. The `anon_node_to_index` map only contains nodes of anonymous queries not in the previous
1153/// graph, and we map nodes in the previous graph to indices via a two-step
1154/// mapping. `SerializedDepGraph` maps from `DepNode` to `SerializedDepNodeIndex`,
1155/// and the `prev_index_to_index` vector (which is more compact and faster than
1156/// using a map) maps from `SerializedDepNodeIndex` to `DepNodeIndex`.
1157///
1158/// This struct uses three locks internally. The `data`, `anon_node_to_index`,
1159/// and `prev_index_to_index` fields are locked separately. Operations that take
1160/// a `DepNodeIndex` typically just access the `data` field.
1161///
1162/// We only need to manipulate at most two locks simultaneously:
1163/// `anon_node_to_index` and `data`, or `prev_index_to_index` and `data`. When
1164/// manipulating both, we acquire `anon_node_to_index` or `prev_index_to_index`
1165/// first, and `data` second.
1166pub(super) struct CurrentDepGraph {
1167    encoder: GraphEncoder,
1168    anon_node_to_index: ShardedHashMap<DepNode, DepNodeIndex>,
1169
1170    /// This is used to verify that value fingerprints do not change between the
1171    /// creation of a node and its recomputation.
1172    #[cfg(debug_assertions)]
1173    value_fingerprints: Lock<IndexVec<DepNodeIndex, Option<Fingerprint>>>,
1174
1175    /// Used to trap when a specific edge is added to the graph.
1176    /// This is used for debug purposes and is only active with `debug_assertions`.
1177    #[cfg(debug_assertions)]
1178    forbidden_edge: Option<EdgeFilter>,
1179
1180    /// Anonymous `DepNode`s are nodes whose IDs we compute from the list of
1181    /// their edges. This has the beneficial side-effect that multiple anonymous
1182    /// nodes can be coalesced into one without changing the semantics of the
1183    /// dependency graph. However, the merging of nodes can lead to a subtle
1184    /// problem during red-green marking: The color of an anonymous node from
1185    /// the current session might "shadow" the color of the node with the same
1186    /// ID from the previous session. In order to side-step this problem, we make
1187    /// sure that anonymous `NodeId`s allocated in different sessions don't overlap.
1188    /// This is implemented by mixing a session-key into the ID fingerprint of
1189    /// each anon node. The session-key is a hash of the number of previous sessions.
1190    anon_id_seed: Fingerprint,
1191
1192    /// These are simple counters that are for profiling and
1193    /// debugging and only active with `debug_assertions`.
1194    pub(super) total_read_count: AtomicU64,
1195    pub(super) total_duplicate_read_count: AtomicU64,
1196}
1197
1198impl CurrentDepGraph {
1199    fn new(
1200        session: &Session,
1201        prev_graph_node_count: usize,
1202        encoder: FileEncoder<'static>,
1203        previous: Arc<SerializedDepGraph>,
1204    ) -> Self {
1205        let mut stable_hasher = StableHasher::new();
1206        previous.session_count().hash(&mut stable_hasher);
1207        let anon_id_seed = stable_hasher.finish();
1208
1209        #[cfg(debug_assertions)]
1210        let forbidden_edge = match env::var("RUST_FORBID_DEP_GRAPH_EDGE") {
1211            Ok(s) => match EdgeFilter::new(&s) {
1212                Ok(f) => Some(f),
1213                Err(err) => {
    ::core::panicking::panic_fmt(format_args!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {0}",
            err));
}panic!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {}", err),
1214            },
1215            Err(_) => None,
1216        };
1217
1218        let new_node_count_estimate = 102 * prev_graph_node_count / 100 + 200;
1219
1220        CurrentDepGraph {
1221            encoder: GraphEncoder::new(session, encoder, prev_graph_node_count, previous),
1222            anon_node_to_index: ShardedHashMap::with_capacity(
1223                // FIXME: The count estimate is off as anon nodes are only a portion of the nodes.
1224                new_node_count_estimate / sharded::shards(),
1225            ),
1226            anon_id_seed,
1227            #[cfg(debug_assertions)]
1228            forbidden_edge,
1229            #[cfg(debug_assertions)]
1230            value_fingerprints: Lock::new(IndexVec::from_elem_n(None, new_node_count_estimate)),
1231            total_read_count: AtomicU64::new(0),
1232            total_duplicate_read_count: AtomicU64::new(0),
1233        }
1234    }
1235
1236    #[cfg(debug_assertions)]
1237    fn record_edge(
1238        &self,
1239        dep_node_index: DepNodeIndex,
1240        key: DepNode,
1241        value_fingerprint: Fingerprint,
1242    ) {
1243        if let Some(forbidden_edge) = &self.forbidden_edge {
1244            forbidden_edge.index_to_node.lock().insert(dep_node_index, key);
1245        }
1246        let prior_value_fingerprint = *self
1247            .value_fingerprints
1248            .lock()
1249            .get_or_insert_with(dep_node_index, || value_fingerprint);
1250        match (&prior_value_fingerprint, &value_fingerprint) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("Unstable fingerprints for {0:?}",
                        key)));
        }
    }
};assert_eq!(prior_value_fingerprint, value_fingerprint, "Unstable fingerprints for {key:?}");
1251    }
1252
1253    /// Writes the node to the current dep-graph and allocates a `DepNodeIndex` for it.
1254    /// Assumes that this is a node that has no equivalent in the previous dep-graph.
1255    #[inline(always)]
1256    fn alloc_new_node(
1257        &self,
1258        key: DepNode,
1259        edges: EdgesVec,
1260        value_fingerprint: Fingerprint,
1261    ) -> DepNodeIndex {
1262        let dep_node_index = self.encoder.send_new(key, value_fingerprint, edges);
1263
1264        #[cfg(debug_assertions)]
1265        self.record_edge(dep_node_index, key, value_fingerprint);
1266
1267        dep_node_index
1268    }
1269}
1270
1271#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for TaskDepsRef<'a> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TaskDepsRef::Allow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Allow",
                    &__self_0),
            TaskDepsRef::EvalAlways =>
                ::core::fmt::Formatter::write_str(f, "EvalAlways"),
            TaskDepsRef::Ignore =>
                ::core::fmt::Formatter::write_str(f, "Ignore"),
            TaskDepsRef::Forbid =>
                ::core::fmt::Formatter::write_str(f, "Forbid"),
        }
    }
}Debug, #[automatically_derived]
impl<'a> ::core::clone::Clone for TaskDepsRef<'a> {
    #[inline]
    fn clone(&self) -> TaskDepsRef<'a> {
        let _: ::core::clone::AssertParamIsClone<&'a Lock<TaskDeps>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'a> ::core::marker::Copy for TaskDepsRef<'a> { }Copy)]
1272pub enum TaskDepsRef<'a> {
1273    /// New dependencies can be added to the
1274    /// `TaskDeps`. This is used when executing a 'normal' query
1275    /// (no `eval_always` modifier)
1276    Allow(&'a Lock<TaskDeps>),
1277    /// This is used when executing an `eval_always` query. We don't
1278    /// need to track dependencies for a query that's always
1279    /// re-executed -- but we need to know that this is an `eval_always`
1280    /// query in order to emit dependencies to `DepNodeIndex::FOREVER_RED_NODE`
1281    /// when directly feeding other queries.
1282    EvalAlways,
1283    /// New dependencies are ignored. This is also used for `dep_graph.with_ignore`.
1284    Ignore,
1285    /// Any attempt to add new dependencies will cause a panic.
1286    /// This is used when decoding a query result from disk,
1287    /// to ensure that the decoding process doesn't itself
1288    /// require the execution of any queries.
1289    Forbid,
1290}
1291
1292#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TaskDeps {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "TaskDeps",
            "node", &self.node, "reads", &self.reads, "read_set",
            &&self.read_set)
    }
}Debug)]
1293pub struct TaskDeps {
1294    #[cfg(debug_assertions)]
1295    node: Option<DepNode>,
1296
1297    /// A vector of `DepNodeIndex`, basically. Contains no duplicates.
1298    reads: EdgesVec,
1299
1300    /// When adding a new edge to `reads` in `DepGraph::read_index` we must determine if the edge
1301    /// has been seen before. We just do a linear scan of `reads` if its length is less than or
1302    /// equal to `LINEAR_SCAN_MAX`. Otherwise, we use this hashset for better performance. Note:
1303    /// `reads` is always the canonical edges representation; this field is just to speed up the
1304    /// seen-before test.
1305    read_set: FxHashSet<DepNodeIndex>,
1306}
1307
1308impl TaskDeps {
1309    /// See `TaskDeps::read_set` above.
1310    const LINEAR_SCAN_MAX: usize = 16;
1311
1312    #[inline]
1313    fn new(#[cfg(debug_assertions)] node: Option<DepNode>, read_set_capacity: usize) -> Self {
1314        TaskDeps {
1315            #[cfg(debug_assertions)]
1316            node,
1317            reads: EdgesVec::new(),
1318            read_set: FxHashSet::with_capacity_and_hasher(read_set_capacity, Default::default()),
1319        }
1320    }
1321}
1322
1323// A data structure that stores Option<DepNodeColor> values as a contiguous
1324// array, using one u32 per entry.
1325pub(super) struct DepNodeColorMap {
1326    values: IndexVec<SerializedDepNodeIndex, AtomicU32>,
1327}
1328
1329// All values below `COMPRESSED_RED` are green.
1330const COMPRESSED_RED: u32 = u32::MAX - 1;
1331const COMPRESSED_UNKNOWN: u32 = u32::MAX;
1332
1333impl DepNodeColorMap {
1334    fn new(size: usize) -> DepNodeColorMap {
1335        if true {
    if !(COMPRESSED_RED > DepNodeIndex::MAX_AS_U32) {
        ::core::panicking::panic("assertion failed: COMPRESSED_RED > DepNodeIndex::MAX_AS_U32")
    };
};debug_assert!(COMPRESSED_RED > DepNodeIndex::MAX_AS_U32);
1336        DepNodeColorMap { values: (0..size).map(|_| AtomicU32::new(COMPRESSED_UNKNOWN)).collect() }
1337    }
1338
1339    #[inline]
1340    pub(super) fn current(&self, index: SerializedDepNodeIndex) -> Option<DepNodeIndex> {
1341        let value = self.values[index].load(Ordering::Relaxed);
1342        if value <= DepNodeIndex::MAX_AS_U32 { Some(DepNodeIndex::from_u32(value)) } else { None }
1343    }
1344
1345    /// Atomically sets the color of a previous-session dep node to either green
1346    /// or red, if it has not already been colored.
1347    ///
1348    /// If the node already has a color, the new color is ignored, and the
1349    /// return value indicates the existing color.
1350    #[inline(always)]
1351    pub(super) fn try_set_color(
1352        &self,
1353        prev_index: SerializedDepNodeIndex,
1354        color: DesiredColor,
1355    ) -> TrySetColorResult {
1356        match self.values[prev_index].compare_exchange(
1357            COMPRESSED_UNKNOWN,
1358            match color {
1359                DesiredColor::Red => COMPRESSED_RED,
1360                DesiredColor::Green { index } => index.as_u32(),
1361            },
1362            Ordering::Relaxed,
1363            Ordering::Relaxed,
1364        ) {
1365            Ok(_) => TrySetColorResult::Success,
1366            Err(COMPRESSED_RED) => TrySetColorResult::AlreadyRed,
1367            Err(index) => TrySetColorResult::AlreadyGreen { index: DepNodeIndex::from_u32(index) },
1368        }
1369    }
1370
1371    #[inline]
1372    pub(super) fn get(&self, index: SerializedDepNodeIndex) -> DepNodeColor {
1373        let value = self.values[index].load(Ordering::Acquire);
1374        // Green is by far the most common case. Check for that first so we can succeed with a
1375        // single comparison.
1376        if value < COMPRESSED_RED {
1377            DepNodeColor::Green(DepNodeIndex::from_u32(value))
1378        } else if value == COMPRESSED_RED {
1379            DepNodeColor::Red
1380        } else {
1381            if true {
    match (&value, &COMPRESSED_UNKNOWN) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(value, COMPRESSED_UNKNOWN);
1382            DepNodeColor::Unknown
1383        }
1384    }
1385}
1386
1387/// The color that [`DepNodeColorMap::try_set_color`] should try to apply to a node.
1388#[derive(#[automatically_derived]
impl ::core::clone::Clone for DesiredColor {
    #[inline]
    fn clone(&self) -> DesiredColor {
        let _: ::core::clone::AssertParamIsClone<DepNodeIndex>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for DesiredColor { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for DesiredColor {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            DesiredColor::Red => ::core::fmt::Formatter::write_str(f, "Red"),
            DesiredColor::Green { index: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Green",
                    "index", &__self_0),
        }
    }
}Debug)]
1389pub(super) enum DesiredColor {
1390    /// Try to mark the node red.
1391    Red,
1392    /// Try to mark the node green, associating it with a current-session node index.
1393    Green { index: DepNodeIndex },
1394}
1395
1396/// Return value of [`DepNodeColorMap::try_set_color`], indicating success or failure,
1397/// and (on failure) what the existing color is.
1398#[derive(#[automatically_derived]
impl ::core::clone::Clone for TrySetColorResult {
    #[inline]
    fn clone(&self) -> TrySetColorResult {
        let _: ::core::clone::AssertParamIsClone<DepNodeIndex>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for TrySetColorResult { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for TrySetColorResult {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TrySetColorResult::Success =>
                ::core::fmt::Formatter::write_str(f, "Success"),
            TrySetColorResult::AlreadyRed =>
                ::core::fmt::Formatter::write_str(f, "AlreadyRed"),
            TrySetColorResult::AlreadyGreen { index: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "AlreadyGreen", "index", &__self_0),
        }
    }
}Debug)]
1399pub(super) enum TrySetColorResult {
1400    /// The [`DesiredColor`] was freshly applied to the node.
1401    Success,
1402    /// Coloring failed because the node was already marked red.
1403    AlreadyRed,
1404    /// Coloring failed because the node was already marked green,
1405    /// and corresponds to node `index` in the current-session dep graph.
1406    AlreadyGreen { index: DepNodeIndex },
1407}
1408
1409#[inline(never)]
1410#[cold]
1411pub(crate) fn print_markframe_trace(graph: &DepGraph, frame: &MarkFrame<'_>) {
1412    let data = graph.data.as_ref().unwrap();
1413
1414    {
    ::std::io::_eprint(format_args!("there was a panic while trying to force a dep node\n"));
};eprintln!("there was a panic while trying to force a dep node");
1415    { ::std::io::_eprint(format_args!("try_mark_green dep node stack:\n")); };eprintln!("try_mark_green dep node stack:");
1416
1417    let mut i = 0;
1418    let mut current = Some(frame);
1419    while let Some(frame) = current {
1420        let node = data.previous.index_to_node(frame.index);
1421        { ::std::io::_eprint(format_args!("#{0} {1:?}\n", i, node)); };eprintln!("#{i} {node:?}");
1422        current = frame.parent;
1423        i += 1;
1424    }
1425
1426    {
    ::std::io::_eprint(format_args!("end of try_mark_green dep node stack\n"));
};eprintln!("end of try_mark_green dep node stack");
1427}
1428
1429#[cold]
1430#[inline(never)]
1431fn panic_on_forbidden_read(data: &DepGraphData, dep_node_index: DepNodeIndex) -> ! {
1432    // We have to do an expensive reverse-lookup of the DepNode that
1433    // corresponds to `dep_node_index`, but that's OK since we are about
1434    // to ICE anyway.
1435    let mut dep_node = None;
1436
1437    // First try to find the dep node among those that already existed in the
1438    // previous session and has been marked green
1439    for prev_index in data.colors.values.indices() {
1440        if data.colors.current(prev_index) == Some(dep_node_index) {
1441            dep_node = Some(*data.previous.index_to_node(prev_index));
1442            break;
1443        }
1444    }
1445
1446    let dep_node = dep_node.map_or_else(
1447        || ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("with index {0:?}", dep_node_index))
    })format!("with index {:?}", dep_node_index),
1448        |dep_node| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0:?}`", dep_node))
    })format!("`{:?}`", dep_node),
1449    );
1450
1451    {
    ::core::panicking::panic_fmt(format_args!("Error: trying to record dependency on DepNode {0} in a context that does not allow it (e.g. during query deserialization). The most common case of recording a dependency on a DepNode `foo` is when the corresponding query `foo` is invoked. Invoking queries is not allowed as part of loading something from the incremental on-disk cache. See <https://github.com/rust-lang/rust/pull/91919>.",
            dep_node));
}panic!(
1452        "Error: trying to record dependency on DepNode {dep_node} in a \
1453         context that does not allow it (e.g. during query deserialization). \
1454         The most common case of recording a dependency on a DepNode `foo` is \
1455         when the corresponding query `foo` is invoked. Invoking queries is not \
1456         allowed as part of loading something from the incremental on-disk cache. \
1457         See <https://github.com/rust-lang/rust/pull/91919>."
1458    )
1459}
1460
1461impl<'tcx> TyCtxt<'tcx> {
1462    /// Return whether this kind always require evaluation.
1463    #[inline(always)]
1464    fn is_eval_always(self, kind: DepKind) -> bool {
1465        self.dep_kind_vtable(kind).is_eval_always
1466    }
1467}