Skip to main content

rustc_middle/dep_graph/
serialized.rs

1//! The data that we will serialize and deserialize.
2//!
3//! Notionally, the dep-graph is a sequence of NodeInfo with the dependencies
4//! specified inline. The total number of nodes and edges are stored as the last
5//! 16 bytes of the file, so we can find them easily at decoding time.
6//!
7//! The serialisation is performed on-demand when each node is emitted. Using this
8//! scheme, we do not need to keep the current graph in memory.
9//!
10//! The deserialization is performed manually, in order to convert from the stored
11//! sequence of NodeInfos to the different arrays in SerializedDepGraph. Since the
12//! node and edge count are stored at the end of the file, all the arrays can be
13//! pre-allocated with the right length.
14//!
15//! The encoding of the dep-graph is generally designed around the fact that fixed-size
16//! reads of encoded data are generally faster than variable-sized reads. Ergo we adopt
17//! essentially the same varint encoding scheme used in the rmeta format; the edge lists
18//! for each node on the graph store a 2-bit integer which is the number of bytes per edge
19//! index in that node's edge list. We effectively ignore that an edge index of 0 could be
20//! encoded with 0 bytes in order to not require 3 bits to store the byte width of the edges.
21//! The overhead of calculating the correct byte width for each edge is mitigated by
22//! building edge lists with [`EdgesVec`] which keeps a running max of the edges in a node.
23//!
24//! When we decode this data, we do not immediately create [`SerializedDepNodeIndex`] and
25//! instead keep the data in its denser serialized form which lets us turn our on-disk size
26//! efficiency directly into a peak memory reduction. When we convert these encoded-in-memory
27//! values into their fully-deserialized type, we use a fixed-size read of the encoded array
28//! then mask off any errant bytes we read. The array of edge index bytes is padded to permit this.
29//!
30//! We also encode and decode the entire rest of each node using [`SerializedNodeHeader`]
31//! to let this encoding and decoding be done in one fixed-size operation. These headers contain
32//! two [`Fingerprint`]s along with the serialized [`DepKind`], and the number of edge indices
33//! in the node and the number of bytes used to encode the edge indices for this node. The
34//! [`DepKind`], number of edges, and bytes per edge are all bit-packed together, if they fit.
35//! If the number of edges in this node does not fit in the bits available in the header, we
36//! store it directly after the header with leb128.
37//!
38//! Dep-graph indices are bulk allocated to threads inside `LocalEncoderState`. Having threads
39//! own these indices helps avoid races when they are conditionally used when marking nodes green.
40//! It also reduces congestion on the shared index count.
41
42use std::cell::RefCell;
43use std::cmp::max;
44use std::sync::atomic::Ordering;
45use std::sync::{Arc, OnceLock};
46use std::{iter, mem};
47
48use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint};
49use rustc_data_structures::fx::FxHashMap;
50use rustc_data_structures::outline;
51use rustc_data_structures::profiling::SelfProfilerRef;
52use rustc_data_structures::sync::{AtomicU64, Lock, WorkerLocal, broadcast};
53use rustc_data_structures::unhash::UnhashMap;
54use rustc_index::{IndexSlice, IndexVec};
55use rustc_serialize::opaque::mem_encoder::MemEncoder;
56use rustc_serialize::opaque::{FileEncodeResult, FileEncoder, IntEncodedWithFixedSize, MemDecoder};
57use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
58use rustc_session::Session;
59use tracing::{debug, instrument};
60
61use super::graph::{CurrentDepGraph, DepNodeColorMap, DesiredColor, TrySetColorResult};
62use super::retained::RetainedDepGraph;
63use super::{DepKind, DepNode, DepNodeIndex};
64use crate::dep_graph::edges::EdgesVec;
65
66// The maximum value of `SerializedDepNodeIndex` leaves the upper two bits
67// unused so that we can store multiple index types in `CompressedHybridIndex`,
68// and use those bits to encode which index type it contains.
69impl ::std::fmt::Debug for SerializedDepNodeIndex {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
70    #[encodable]
71    #[max = 0x7FFF_FFFF]
72    pub struct SerializedDepNodeIndex {}
73}
74
75impl SerializedDepNodeIndex {
76    /// Converts a current-session dep node index to a "serialized" index,
77    /// for the purpose of serializing data to be loaded by future sessions.
78    #[inline(always)]
79    pub fn from_curr_for_serialization(index: DepNodeIndex) -> Self {
80        SerializedDepNodeIndex::from_u32(index.as_u32())
81    }
82}
83
84const DEP_NODE_SIZE: usize = size_of::<SerializedDepNodeIndex>();
85/// Amount of padding we need to add to the edge list data so that we can retrieve every
86/// SerializedDepNodeIndex with a fixed-size read then mask.
87const DEP_NODE_PAD: usize = DEP_NODE_SIZE - 1;
88/// Number of bits we need to store the number of used bytes in a SerializedDepNodeIndex.
89/// Note that wherever we encode byte widths like this we actually store the number of bytes used
90/// minus 1; for a 4-byte value we technically would have 5 widths to store, but using one byte to
91/// store zeroes (which are relatively rare) is a decent tradeoff to save a bit in our bitfields.
92const DEP_NODE_WIDTH_BITS: usize = DEP_NODE_SIZE / 2;
93
94/// Data for use when recompiling the **current crate**.
95///
96/// There may be unused indices with DepKind::Null in this graph due to batch allocation of
97/// indices to threads.
98#[derive(#[automatically_derived]
impl ::core::default::Default for SerializedDepGraph {
    #[inline]
    fn default() -> SerializedDepGraph {
        SerializedDepGraph {
            nodes: ::core::default::Default::default(),
            value_fingerprints: ::core::default::Default::default(),
            edge_list_indices: ::core::default::Default::default(),
            edge_list_data: ::core::default::Default::default(),
            reverse_index: ::core::default::Default::default(),
            session_count: ::core::default::Default::default(),
            profiler: ::core::default::Default::default(),
        }
    }
}Default)]
99pub struct SerializedDepGraph {
100    /// The set of all DepNodes in the graph
101    nodes: IndexVec<SerializedDepNodeIndex, DepNode>,
102    /// A value fingerprint associated with each [`DepNode`] in [`Self::nodes`],
103    /// typically a hash of the value returned by the node's query in the
104    /// previous incremental-compilation session.
105    ///
106    /// Some nodes don't have a meaningful value hash (e.g. queries with `no_hash`),
107    /// so they store a dummy value here instead (e.g. [`Fingerprint::ZERO`]).
108    value_fingerprints: IndexVec<SerializedDepNodeIndex, Fingerprint>,
109    /// For each DepNode, stores the list of edges originating from that
110    /// DepNode. Encoded as a [start, end) pair indexing into edge_list_data,
111    /// which holds the actual DepNodeIndices of the target nodes.
112    edge_list_indices: IndexVec<SerializedDepNodeIndex, EdgeHeader>,
113    /// A flattened list of all edge targets in the graph, stored in the same
114    /// varint encoding that we use on disk. Edge sources are implicit in edge_list_indices.
115    edge_list_data: Vec<u8>,
116    /// The lazily-built inverse of `nodes`: maps a [`DepNode`] back to its
117    /// [`SerializedDepNodeIndex`] via the node's key fingerprint. See
118    /// [`LazyNodeIndex`].
119    reverse_index: LazyNodeIndex,
120    /// The number of previous compilation sessions. This is used to generate
121    /// unique anon dep nodes per session.
122    session_count: u64,
123    /// Used to time the lazy per-`DepKind` reverse-index build. `None` only for
124    /// the empty default graph, which is never looked up.
125    profiler: Option<SelfProfilerRef>,
126}
127
128// `SelfProfilerRef` is not `Debug`, so we can't derive this.
129impl std::fmt::Debug for SerializedDepGraph {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        f.debug_struct("SerializedDepGraph")
132            .field("nodes", &self.nodes)
133            .field("value_fingerprints", &self.value_fingerprints)
134            .field("edge_list_indices", &self.edge_list_indices)
135            .field("edge_list_data", &self.edge_list_data)
136            .field("reverse_index", &self.reverse_index)
137            .field("session_count", &self.session_count)
138            .finish_non_exhaustive()
139    }
140}
141
142/// The inverse of [`SerializedDepGraph::nodes`], built lazily per [`DepKind`].
143///
144/// Only few nodes are ever looked up here, and those cluster into a handful of
145/// `DepKind`s. Building a map for every kind up front would be wasted work.
146#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LazyNodeIndex {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "LazyNodeIndex",
            "nodes_by_kind", &self.nodes_by_kind, "kinds", &&self.kinds)
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for LazyNodeIndex {
    #[inline]
    fn default() -> LazyNodeIndex {
        LazyNodeIndex {
            nodes_by_kind: ::core::default::Default::default(),
            kinds: ::core::default::Default::default(),
        }
    }
}Default)]
147struct LazyNodeIndex {
148    /// All (non-`Null`) node indices, grouped into contiguous per-`DepKind`
149    /// ranges described by `kinds`. For any non-`Null` `DepKind` `k`, all values in
150    /// `nodes_by_kind[kinds[k].start..][..kinds[k].len]`
151    /// must be `Some` and have kind `k`.
152    nodes_by_kind: Vec<Option<SerializedDepNodeIndex>>,
153    /// For each `DepKind`, the range of `nodes_by_kind` holding its node indices
154    /// and the lazily-built fingerprint map over that range.
155    kinds: Vec<LazyKindIndex>,
156}
157
158#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LazyKindIndex {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "LazyKindIndex",
            "start", &self.start, "len", &self.len, "map", &&self.map)
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for LazyKindIndex {
    #[inline]
    fn default() -> LazyKindIndex {
        LazyKindIndex {
            start: ::core::default::Default::default(),
            len: ::core::default::Default::default(),
            map: ::core::default::Default::default(),
        }
    }
}Default)]
159struct LazyKindIndex {
160    /// Offset into `LazyNodeIndex::nodes_by_kind` of this kind's first node.
161    start: u32,
162    /// Number of nodes of this kind.
163    len: u32,
164    /// `key_fingerprint -> node index`, built from this kind's range on first
165    /// lookup. Empty kinds (and kinds never looked up) never build a map.
166    map: OnceLock<UnhashMap<PackedFingerprint, SerializedDepNodeIndex>>,
167}
168
169impl LazyKindIndex {
170    /// Returns this kind's `key_fingerprint -> node index` map.
171    fn fingerprint_map(
172        &self,
173        kind: DepKind,
174        nodes: &IndexSlice<SerializedDepNodeIndex, DepNode>,
175        nodes_by_kind: &[Option<SerializedDepNodeIndex>],
176        profiler: &Option<SelfProfilerRef>,
177    ) -> &UnhashMap<PackedFingerprint, SerializedDepNodeIndex> {
178        self.map.get_or_init(|| {
179            let _prof_timer = profiler
180                .as_ref()
181                .map(|p| p.generic_activity("incr_comp_load_dep_graph_reverse_index"));
182            let range = (self.start as usize)..(self.start as usize + self.len as usize);
183            let mut map =
184                UnhashMap::with_capacity_and_hasher(self.len as usize, Default::default());
185            for &idx in &nodes_by_kind[range] {
186                let idx = idx.expect("counting sort fills every slot of a kind's range");
187                let node = nodes[idx];
188                if true {
    match (&node.kind, &kind) {
        (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!(node.kind, kind);
189                if map.insert(node.key_fingerprint, idx).is_some()
190                    // Side effect nodes can legitimately share a fingerprint.
191                    && node.kind != DepKind::SideEffect
192                {
193                    {
    ::core::panicking::panic_fmt(format_args!("Error: A dep graph node ({0:?}) does not have an unique index. Running a clean build on a nightly compiler with `-Z incremental-verify-ich` can help narrow down the issue for reporting. A clean build may also work around the issue.\n\n                         DepNode: {1:?}",
            kind, node));
}panic!(
194                        "Error: A dep graph node ({kind:?}) does not have an unique index. \
195                         Running a clean build on a nightly compiler with \
196                         `-Z incremental-verify-ich` can help narrow down the issue for reporting. \
197                         A clean build may also work around the issue.\n
198                         DepNode: {node:?}"
199                    )
200                }
201            }
202            map
203        })
204    }
205}
206
207impl SerializedDepGraph {
208    #[inline]
209    pub fn edge_targets_from(
210        &self,
211        source: SerializedDepNodeIndex,
212    ) -> impl Iterator<Item = SerializedDepNodeIndex> + Clone {
213        let header = self.edge_list_indices[source];
214        let mut raw = &self.edge_list_data[header.start()..];
215
216        let bytes_per_index = header.bytes_per_index();
217
218        // LLVM doesn't hoist EdgeHeader::mask so we do it ourselves.
219        let mask = header.mask();
220        (0..header.num_edges).map(move |_| {
221            // Doing this slicing in this order ensures that the first bounds check suffices for
222            // all the others.
223            let index = &raw[..DEP_NODE_SIZE];
224            raw = &raw[bytes_per_index..];
225            let index = u32::from_le_bytes(index.try_into().unwrap()) & mask;
226            SerializedDepNodeIndex::from_u32(index)
227        })
228    }
229
230    #[inline]
231    pub fn index_to_node(&self, dep_node_index: SerializedDepNodeIndex) -> &DepNode {
232        &self.nodes[dep_node_index]
233    }
234
235    #[inline]
236    pub fn node_to_index_opt(&self, dep_node: &DepNode) -> Option<SerializedDepNodeIndex> {
237        let kind = self.reverse_index.kinds.get(dep_node.kind.as_usize())?;
238        let map = kind.fingerprint_map(
239            dep_node.kind,
240            &self.nodes,
241            &self.reverse_index.nodes_by_kind,
242            &self.profiler,
243        );
244        map.get(&dep_node.key_fingerprint).copied()
245    }
246
247    #[inline]
248    pub fn value_fingerprint_for_index(
249        &self,
250        dep_node_index: SerializedDepNodeIndex,
251    ) -> Fingerprint {
252        self.value_fingerprints[dep_node_index]
253    }
254
255    #[inline]
256    pub fn node_count(&self) -> usize {
257        self.nodes.len()
258    }
259
260    #[inline]
261    pub fn session_count(&self) -> u64 {
262        self.session_count
263    }
264}
265
266/// A packed representation of an edge's start index and byte width.
267///
268/// This is packed by stealing 2 bits from the start index, which means we only accommodate edge
269/// data arrays up to a quarter of our address space. Which seems fine.
270#[derive(#[automatically_derived]
impl ::core::fmt::Debug for EdgeHeader {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "EdgeHeader",
            "repr", &self.repr, "num_edges", &&self.num_edges)
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for EdgeHeader {
    #[inline]
    fn clone(&self) -> EdgeHeader {
        let _: ::core::clone::AssertParamIsClone<usize>;
        let _: ::core::clone::AssertParamIsClone<u32>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for EdgeHeader { }Copy)]
271struct EdgeHeader {
272    repr: usize,
273    num_edges: u32,
274}
275
276impl EdgeHeader {
277    #[inline]
278    fn start(self) -> usize {
279        self.repr >> DEP_NODE_WIDTH_BITS
280    }
281
282    #[inline]
283    fn bytes_per_index(self) -> usize {
284        (self.repr & mask(DEP_NODE_WIDTH_BITS)) + 1
285    }
286
287    #[inline]
288    fn mask(self) -> u32 {
289        mask(self.bytes_per_index() * 8) as u32
290    }
291}
292
293#[inline]
294fn mask(bits: usize) -> usize {
295    usize::MAX >> ((size_of::<usize>() * 8) - bits)
296}
297
298impl SerializedDepGraph {
299    #[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("decode",
                                    "rustc_middle::dep_graph::serialized",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
                                    ::tracing_core::__macro_support::Option::Some(299u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                                    ::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: Arc<SerializedDepGraph> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/serialized.rs:302",
                                    "rustc_middle::dep_graph::serialized",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
                                    ::tracing_core::__macro_support::Option::Some(302u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
                                                                d.position()) as &dyn Value))])
                        });
                } else { ; }
            };
            let (node_max, node_count, edge_count) =
                d.with_position(d.len() -
                        3 * IntEncodedWithFixedSize::ENCODED_SIZE,
                    |d|
                        {
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/serialized.rs:308",
                                                    "rustc_middle::dep_graph::serialized",
                                                    ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(308u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                                                    ::tracing_core::field::FieldSet::new(&["message"],
                                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                    ::tracing::metadata::Kind::EVENT)
                                            };
                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                    };
                                let enabled =
                                    ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                            ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::LevelFilter::current() &&
                                        {
                                            let interest = __CALLSITE.interest();
                                            !interest.is_never() &&
                                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                    interest)
                                        };
                                if enabled {
                                    (|value_set: ::tracing::field::ValueSet|
                                                {
                                                    let meta = __CALLSITE.metadata();
                                                    ::tracing::Event::dispatch(meta, &value_set);
                                                    ;
                                                })({
                                            #[allow(unused_imports)]
                                            use ::tracing::field::{debug, display, Value};
                                            let mut iter = __CALLSITE.metadata().fields().iter();
                                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                ::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
                                                                                d.position()) as &dyn Value))])
                                        });
                                } else { ; }
                            };
                            let node_max =
                                IntEncodedWithFixedSize::decode(d).0 as usize;
                            let node_count =
                                IntEncodedWithFixedSize::decode(d).0 as usize;
                            let edge_count =
                                IntEncodedWithFixedSize::decode(d).0 as usize;
                            (node_max, node_count, edge_count)
                        });
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/serialized.rs:314",
                                    "rustc_middle::dep_graph::serialized",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
                                    ::tracing_core::__macro_support::Option::Some(314u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
                                                                d.position()) as &dyn Value))])
                        });
                } else { ; }
            };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/serialized.rs:316",
                                    "rustc_middle::dep_graph::serialized",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
                                    ::tracing_core::__macro_support::Option::Some(316u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                                    ::tracing_core::field::FieldSet::new(&["node_count",
                                                    "edge_count"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&node_count)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&edge_count)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let graph_bytes =
                d.len() - (3 * IntEncodedWithFixedSize::ENCODED_SIZE) -
                    d.position();
            let mut nodes =
                IndexVec::from_elem_n(DepNode {
                        kind: DepKind::Null,
                        key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
                    }, node_max);
            let mut value_fingerprints =
                IndexVec::from_elem_n(Fingerprint::ZERO, node_max);
            let mut edge_list_indices =
                IndexVec::from_elem_n(EdgeHeader { repr: 0, num_edges: 0 },
                    node_max);
            let mut edge_list_data =
                Vec::with_capacity(graph_bytes -
                        node_count * size_of::<SerializedNodeHeader>());
            for _ in 0..node_count {
                let node_header =
                    SerializedNodeHeader { bytes: d.read_array() };
                let index = node_header.index();
                let node = &mut nodes[index];
                if !(node_header.node().kind != DepKind::Null &&
                            node.kind == DepKind::Null) {
                    ::core::panicking::panic("assertion failed: node_header.node().kind != DepKind::Null && node.kind == DepKind::Null")
                };
                *node = node_header.node();
                value_fingerprints[index] = node_header.value_fingerprint();
                let num_edges =
                    node_header.len().unwrap_or_else(|| d.read_u32());
                let edges_len_bytes =
                    node_header.bytes_per_index() * (num_edges as usize);
                let edges_header =
                    node_header.edges_header(&edge_list_data, num_edges);
                edge_list_data.extend(d.read_raw_bytes(edges_len_bytes));
                edge_list_indices[index] = edges_header;
            }
            edge_list_data.extend(&[0u8; DEP_NODE_PAD]);
            let mut kinds = Vec::with_capacity(DepKind::MAX as usize + 1);
            let mut offset = 0u32;
            for _ in 0..(DepKind::MAX + 1) {
                let len = d.read_u32();
                kinds.push(LazyKindIndex {
                        start: offset,
                        len,
                        map: OnceLock::new(),
                    });
                offset += len;
            }
            if true {
                match (&(offset as usize), &node_count) {
                    (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);
                        }
                    }
                };
            };
            let session_count = d.read_u64();
            let mut nodes_by_kind = ::alloc::vec::from_elem(None, node_count);
            let mut fill: Vec<u32> = kinds.iter().map(|k| k.start).collect();
            for (idx, node) in nodes.iter_enumerated() {
                if node.kind == DepKind::Null { continue; }
                let k = node.kind.as_usize();
                nodes_by_kind[fill[k] as usize] = Some(idx);
                fill[k] += 1;
            }
            if true {
                if !kinds.iter().zip(&fill).all(|(k, &f)|
                                f == k.start + k.len) {
                    ::core::panicking::panic("assertion failed: kinds.iter().zip(&fill).all(|(k, &f)| f == k.start + k.len)")
                };
            };
            let reverse_index = LazyNodeIndex { nodes_by_kind, kinds };
            Arc::new(SerializedDepGraph {
                    nodes,
                    value_fingerprints,
                    edge_list_indices,
                    edge_list_data,
                    reverse_index,
                    session_count,
                    profiler: Some(profiler.clone()),
                })
        }
    }
}#[instrument(level = "debug", skip(d, profiler))]
300    pub fn decode(d: &mut MemDecoder<'_>, profiler: &SelfProfilerRef) -> Arc<SerializedDepGraph> {
301        // The last 16 bytes are the node count and edge count.
302        debug!("position: {:?}", d.position());
303
304        // `node_max` is the number of indices including empty nodes while `node_count`
305        // is the number of actually encoded nodes.
306        let (node_max, node_count, edge_count) =
307            d.with_position(d.len() - 3 * IntEncodedWithFixedSize::ENCODED_SIZE, |d| {
308                debug!("position: {:?}", d.position());
309                let node_max = IntEncodedWithFixedSize::decode(d).0 as usize;
310                let node_count = IntEncodedWithFixedSize::decode(d).0 as usize;
311                let edge_count = IntEncodedWithFixedSize::decode(d).0 as usize;
312                (node_max, node_count, edge_count)
313            });
314        debug!("position: {:?}", d.position());
315
316        debug!(?node_count, ?edge_count);
317
318        let graph_bytes = d.len() - (3 * IntEncodedWithFixedSize::ENCODED_SIZE) - d.position();
319
320        let mut nodes = IndexVec::from_elem_n(
321            DepNode {
322                kind: DepKind::Null,
323                key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
324            },
325            node_max,
326        );
327        let mut value_fingerprints = IndexVec::from_elem_n(Fingerprint::ZERO, node_max);
328        let mut edge_list_indices =
329            IndexVec::from_elem_n(EdgeHeader { repr: 0, num_edges: 0 }, node_max);
330
331        // This estimation assumes that all of the encoded bytes are for the edge lists or for the
332        // fixed-size node headers. But that's not necessarily true; if any edge list has a length
333        // that spills out of the size we can bit-pack into SerializedNodeHeader then some of the
334        // total serialized size is also used by leb128-encoded edge list lengths. Neglecting that
335        // contribution to graph_bytes means our estimation of the bytes needed for edge_list_data
336        // slightly overshoots. But it cannot overshoot by much; consider that the worse case is
337        // for a node with length 64, which means the spilled 1-byte leb128 length is 1 byte of at
338        // least (34 byte header + 1 byte len + 64 bytes edge data), which is ~1%. A 2-byte leb128
339        // length is about the same fractional overhead and it amortizes for yet greater lengths.
340        let mut edge_list_data =
341            Vec::with_capacity(graph_bytes - node_count * size_of::<SerializedNodeHeader>());
342
343        for _ in 0..node_count {
344            // Decode the header for this edge; the header packs together as many of the fixed-size
345            // fields as possible to limit the number of times we update decoder state.
346            let node_header = SerializedNodeHeader { bytes: d.read_array() };
347
348            let index = node_header.index();
349
350            let node = &mut nodes[index];
351            // Make sure there's no duplicate indices in the dep graph.
352            assert!(node_header.node().kind != DepKind::Null && node.kind == DepKind::Null);
353            *node = node_header.node();
354
355            value_fingerprints[index] = node_header.value_fingerprint();
356
357            // If the length of this node's edge list is small, the length is stored in the header.
358            // If it is not, we fall back to another decoder call.
359            let num_edges = node_header.len().unwrap_or_else(|| d.read_u32());
360
361            // The edges index list uses the same varint strategy as rmeta tables; we select the
362            // number of byte elements per-array not per-element. This lets us read the whole edge
363            // list for a node with one decoder call and also use the on-disk format in memory.
364            let edges_len_bytes = node_header.bytes_per_index() * (num_edges as usize);
365            // The in-memory structure for the edges list stores the byte width of the edges on
366            // this node with the offset into the global edge data array.
367            let edges_header = node_header.edges_header(&edge_list_data, num_edges);
368
369            edge_list_data.extend(d.read_raw_bytes(edges_len_bytes));
370
371            edge_list_indices[index] = edges_header;
372        }
373
374        // When we access the edge list data, we do a fixed-size read from the edge list data then
375        // mask off the bytes that aren't for that edge index, so the last read may dangle off the
376        // end of the array. This padding ensure it doesn't.
377        edge_list_data.extend(&[0u8; DEP_NODE_PAD]);
378
379        // Read the number of nodes of each dep kind, and perform
380        // counting sort for `LazyNodeIndex`.
381        let mut kinds = Vec::with_capacity(DepKind::MAX as usize + 1);
382        let mut offset = 0u32;
383        for _ in 0..(DepKind::MAX + 1) {
384            let len = d.read_u32();
385            kinds.push(LazyKindIndex { start: offset, len, map: OnceLock::new() });
386            offset += len;
387        }
388        debug_assert_eq!(offset as usize, node_count);
389
390        let session_count = d.read_u64();
391
392        // Counting sort: place each node index into its kind's range. `fill[k]`
393        // points at the next free slot in kind `k`'s range, so a kind's nodes end
394        // up contiguous. Slots start as `None` and are each filled exactly once
395        // (the counts sum to the number of non-`Null` nodes).
396        let mut nodes_by_kind = vec![None; node_count];
397        let mut fill: Vec<u32> = kinds.iter().map(|k| k.start).collect();
398        for (idx, node) in nodes.iter_enumerated() {
399            // Unused indices from batch allocation stay `Null`; they carry no
400            // encoded node and are never looked up by fingerprint, so skip them.
401            if node.kind == DepKind::Null {
402                continue;
403            }
404            let k = node.kind.as_usize();
405            nodes_by_kind[fill[k] as usize] = Some(idx);
406            fill[k] += 1;
407        }
408        // Each kind's range was filled exactly to its end.
409        debug_assert!(kinds.iter().zip(&fill).all(|(k, &f)| f == k.start + k.len));
410        let reverse_index = LazyNodeIndex { nodes_by_kind, kinds };
411
412        Arc::new(SerializedDepGraph {
413            nodes,
414            value_fingerprints,
415            edge_list_indices,
416            edge_list_data,
417            reverse_index,
418            session_count,
419            profiler: Some(profiler.clone()),
420        })
421    }
422}
423
424/// A packed representation of all the fixed-size fields in a `NodeInfo`.
425///
426/// This stores in one byte array:
427/// * The value `Fingerprint` in the `NodeInfo`
428/// * The key `Fingerprint` in `DepNode` that is in this `NodeInfo`
429/// * The `DepKind`'s discriminant (a u16, but not all bits are used...)
430/// * The byte width of the encoded edges for this node
431/// * In whatever bits remain, the length of the edge list for this node, if it fits
432struct SerializedNodeHeader {
433    // 2 bytes for the DepNode
434    // 4 bytes for the index
435    // 16 for Fingerprint in DepNode
436    // 16 for Fingerprint in NodeInfo
437    bytes: [u8; 38],
438}
439
440// The fields of a `SerializedNodeHeader`, this struct is an implementation detail and exists only
441// to make the implementation of `SerializedNodeHeader` simpler.
442struct Unpacked {
443    len: Option<u32>,
444    bytes_per_index: usize,
445    kind: DepKind,
446    index: SerializedDepNodeIndex,
447    key_fingerprint: PackedFingerprint,
448    value_fingerprint: Fingerprint,
449}
450
451// Bit fields, where
452// M: bits used to store the length of a node's edge list
453// N: bits used to store the byte width of elements of the edge list
454// are
455// 0..M    length of the edge
456// M..M+N  bytes per index
457// M+N..16 kind
458impl SerializedNodeHeader {
459    const TOTAL_BITS: usize = size_of::<DepKind>() * 8;
460    const LEN_BITS: usize = Self::TOTAL_BITS - Self::KIND_BITS - Self::WIDTH_BITS;
461    const WIDTH_BITS: usize = DEP_NODE_WIDTH_BITS;
462    const KIND_BITS: usize = Self::TOTAL_BITS - DepKind::MAX.leading_zeros() as usize;
463    const MAX_INLINE_LEN: usize = (u16::MAX as usize >> (Self::TOTAL_BITS - Self::LEN_BITS)) - 1;
464
465    #[inline]
466    fn new(
467        node: &DepNode,
468        index: DepNodeIndex,
469        value_fingerprint: Fingerprint,
470        edge_max_index: u32,
471        edge_count: usize,
472    ) -> Self {
473        if true {
    match (&Self::TOTAL_BITS,
            &(Self::LEN_BITS + Self::WIDTH_BITS + Self::KIND_BITS)) {
        (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::TOTAL_BITS, Self::LEN_BITS + Self::WIDTH_BITS + Self::KIND_BITS);
474
475        let mut head = node.kind.as_u16();
476
477        let free_bytes = edge_max_index.leading_zeros() as usize / 8;
478        let bytes_per_index = (DEP_NODE_SIZE - free_bytes).saturating_sub(1);
479        head |= (bytes_per_index as u16) << Self::KIND_BITS;
480
481        // Encode number of edges + 1 so that we can reserve 0 to indicate that the len doesn't fit
482        // in this bitfield.
483        if edge_count <= Self::MAX_INLINE_LEN {
484            head |= (edge_count as u16 + 1) << (Self::KIND_BITS + Self::WIDTH_BITS);
485        }
486
487        let hash: Fingerprint = node.key_fingerprint.into();
488
489        // Using half-open ranges ensures an unconditional panic if we get the magic numbers wrong.
490        let mut bytes = [0u8; 38];
491        bytes[..2].copy_from_slice(&head.to_le_bytes());
492        bytes[2..6].copy_from_slice(&index.as_u32().to_le_bytes());
493        bytes[6..22].copy_from_slice(&hash.to_le_bytes());
494        bytes[22..].copy_from_slice(&value_fingerprint.to_le_bytes());
495
496        #[cfg(debug_assertions)]
497        {
498            let res = Self { bytes };
499            match (&value_fingerprint, &res.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::None);
        }
    }
};assert_eq!(value_fingerprint, res.value_fingerprint());
500            match (&*node, &res.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!(*node, res.node());
501            if let Some(len) = res.len() {
502                match (&edge_count, &(len as usize)) {
    (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!(edge_count, len as usize);
503            }
504        }
505        Self { bytes }
506    }
507
508    #[inline]
509    fn unpack(&self) -> Unpacked {
510        let head = u16::from_le_bytes(self.bytes[..2].try_into().unwrap());
511        let index = u32::from_le_bytes(self.bytes[2..6].try_into().unwrap());
512        let key_fingerprint = self.bytes[6..22].try_into().unwrap();
513        let value_fingerprint = self.bytes[22..].try_into().unwrap();
514
515        let kind = head & mask(Self::KIND_BITS) as u16;
516        let bytes_per_index = (head >> Self::KIND_BITS) & mask(Self::WIDTH_BITS) as u16;
517        let len = (head as u32) >> (Self::WIDTH_BITS + Self::KIND_BITS);
518
519        Unpacked {
520            len: len.checked_sub(1),
521            bytes_per_index: bytes_per_index as usize + 1,
522            kind: DepKind::from_u16(kind),
523            index: SerializedDepNodeIndex::from_u32(index),
524            key_fingerprint: Fingerprint::from_le_bytes(key_fingerprint).into(),
525            value_fingerprint: Fingerprint::from_le_bytes(value_fingerprint),
526        }
527    }
528
529    #[inline]
530    fn len(&self) -> Option<u32> {
531        self.unpack().len
532    }
533
534    #[inline]
535    fn bytes_per_index(&self) -> usize {
536        self.unpack().bytes_per_index
537    }
538
539    #[inline]
540    fn index(&self) -> SerializedDepNodeIndex {
541        self.unpack().index
542    }
543
544    #[inline]
545    fn value_fingerprint(&self) -> Fingerprint {
546        self.unpack().value_fingerprint
547    }
548
549    #[inline]
550    fn node(&self) -> DepNode {
551        let Unpacked { kind, key_fingerprint, .. } = self.unpack();
552        DepNode { kind, key_fingerprint }
553    }
554
555    #[inline]
556    fn edges_header(&self, edge_list_data: &[u8], num_edges: u32) -> EdgeHeader {
557        EdgeHeader {
558            repr: (edge_list_data.len() << DEP_NODE_WIDTH_BITS) | (self.bytes_per_index() - 1),
559            num_edges,
560        }
561    }
562}
563
564#[derive(#[automatically_derived]
impl ::core::fmt::Debug for NodeInfo {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "NodeInfo",
            "node", &self.node, "value_fingerprint", &self.value_fingerprint,
            "edges", &&self.edges)
    }
}Debug)]
565struct NodeInfo {
566    node: DepNode,
567    value_fingerprint: Fingerprint,
568    edges: EdgesVec,
569}
570
571impl NodeInfo {
572    fn encode(&self, e: &mut MemEncoder, index: DepNodeIndex) {
573        let NodeInfo { ref node, value_fingerprint, ref edges } = *self;
574        let header = SerializedNodeHeader::new(
575            node,
576            index,
577            value_fingerprint,
578            edges.max_index(),
579            edges.len(),
580        );
581        e.write_array(header.bytes);
582
583        if header.len().is_none() {
584            // The edges are all unique and the number of unique indices is less than u32::MAX.
585            e.emit_u32(edges.len().try_into().unwrap());
586        }
587
588        let bytes_per_index = header.bytes_per_index();
589        for node_index in edges.iter() {
590            e.write_with(|dest| {
591                *dest = node_index.as_u32().to_le_bytes();
592                bytes_per_index
593            });
594        }
595    }
596
597    /// Encode a node that was promoted from the previous graph. It reads the edges directly from
598    /// the previous dep graph and expects all edges to already have a new dep node index assigned.
599    /// This avoids the overhead of constructing `EdgesVec`, which would be needed to call `encode`.
600    #[inline]
601    fn encode_promoted(
602        e: &mut MemEncoder,
603        node: &DepNode,
604        index: DepNodeIndex,
605        value_fingerprint: Fingerprint,
606        edges: &[DepNodeIndex],
607    ) -> usize {
608        let edge_count = edges.len();
609
610        // Find the highest edge in the new dep node indices
611        let edge_max = edges.iter().map(|x| x.as_u32()).max().unwrap_or(0);
612
613        let header =
614            SerializedNodeHeader::new(node, index, value_fingerprint, edge_max, edge_count);
615        e.write_array(header.bytes);
616
617        if header.len().is_none() {
618            // The edges are all unique and the number of unique indices is less than u32::MAX.
619            e.emit_u32(edge_count.try_into().unwrap());
620        }
621
622        let bytes_per_index = header.bytes_per_index();
623        for edge in edges {
624            let edge = edge.as_u32();
625            e.write_with(|dest| {
626                *dest = edge.to_le_bytes();
627                bytes_per_index
628            });
629        }
630
631        edge_count
632    }
633}
634
635struct Stat {
636    kind: DepKind,
637    node_counter: u64,
638    edge_counter: u64,
639}
640
641struct LocalEncoderState {
642    next_node_index: u32,
643    remaining_node_index: u32,
644    encoder: MemEncoder,
645    node_count: usize,
646    edge_count: usize,
647
648    /// Stores the number of times we've encoded each dep kind.
649    kind_stats: Vec<u32>,
650}
651
652struct LocalEncoderResult {
653    node_max: u32,
654    node_count: usize,
655    edge_count: usize,
656
657    /// Stores the number of times we've encoded each dep kind.
658    kind_stats: Vec<u32>,
659}
660
661struct EncoderState {
662    next_node_index: AtomicU64,
663    previous: Arc<SerializedDepGraph>,
664    file: Lock<Option<FileEncoder<'static>>>,
665    local: WorkerLocal<RefCell<LocalEncoderState>>,
666    stats: Option<Lock<FxHashMap<DepKind, Stat>>>,
667}
668
669impl EncoderState {
670    fn new(
671        encoder: FileEncoder<'static>,
672        record_stats: bool,
673        previous: Arc<SerializedDepGraph>,
674    ) -> Self {
675        Self {
676            previous,
677            next_node_index: AtomicU64::new(0),
678            stats: record_stats.then(|| Lock::new(FxHashMap::default())),
679            file: Lock::new(Some(encoder)),
680            local: WorkerLocal::new(|_| {
681                RefCell::new(LocalEncoderState {
682                    next_node_index: 0,
683                    remaining_node_index: 0,
684                    edge_count: 0,
685                    node_count: 0,
686                    encoder: MemEncoder::new(),
687                    kind_stats: iter::repeat_n(0, DepKind::MAX as usize + 1).collect(),
688                })
689            }),
690        }
691    }
692
693    #[inline]
694    fn next_index(&self, local: &mut LocalEncoderState) -> DepNodeIndex {
695        if local.remaining_node_index == 0 {
696            const COUNT: u32 = 256;
697
698            // We assume that there won't be enough active threads to overflow `u64` from `u32::MAX` here.
699            // This can exceed u32::MAX by at most `N` * `COUNT` where `N` is the thread pool count since
700            // `try_into().unwrap()` will make threads panic when `self.next_node_index` exceeds u32::MAX.
701            local.next_node_index =
702                self.next_node_index.fetch_add(COUNT as u64, Ordering::Relaxed).try_into().unwrap();
703
704            // Check that we'll stay within `u32`
705            local.next_node_index.checked_add(COUNT).unwrap();
706
707            local.remaining_node_index = COUNT;
708        }
709
710        DepNodeIndex::from_u32(local.next_node_index)
711    }
712
713    /// Marks the index previously returned by `next_index` as used.
714    #[inline]
715    fn bump_index(&self, local: &mut LocalEncoderState) {
716        local.remaining_node_index -= 1;
717        local.next_node_index += 1;
718        local.node_count += 1;
719    }
720
721    #[inline]
722    fn record(
723        &self,
724        node: &DepNode,
725        index: DepNodeIndex,
726        edge_count: usize,
727        edges: &[DepNodeIndex],
728        retained_graph: &Option<Lock<RetainedDepGraph>>,
729        local: &mut LocalEncoderState,
730    ) {
731        local.kind_stats[node.kind.as_usize()] += 1;
732        local.edge_count += edge_count;
733
734        if let Some(retained_graph) = &retained_graph {
735            // Outline the build of the full dep graph as it's typically disabled and cold.
736            outline(move || {
737                // Block on the lock rather than using `try_lock`: under the parallel frontend
738                // several threads record nodes concurrently, and dropping a node on lock
739                // contention would make the retained graph nondeterministic. Readers take a
740                // clone of the graph (`retained_dep_graph`) rather than holding the lock, so
741                // this never deadlocks against a reentrant `record`.
742                retained_graph.lock().push(index, *node, edges);
743            });
744        }
745
746        if let Some(stats) = &self.stats {
747            let kind = node.kind;
748
749            // Outline the stats code as it's typically disabled and cold.
750            outline(move || {
751                let mut stats = stats.lock();
752                let stat =
753                    stats.entry(kind).or_insert(Stat { kind, node_counter: 0, edge_counter: 0 });
754                stat.node_counter += 1;
755                stat.edge_counter += edge_count as u64;
756            });
757        }
758    }
759
760    #[inline]
761    fn flush_mem_encoder(&self, local: &mut LocalEncoderState) {
762        let data = &mut local.encoder.data;
763        if data.len() > 64 * 1024 {
764            self.file.lock().as_mut().unwrap().emit_raw_bytes(&data[..]);
765            data.clear();
766        }
767    }
768
769    /// Encodes a node to the current graph.
770    fn encode_node(
771        &self,
772        index: DepNodeIndex,
773        node: &NodeInfo,
774        retained_graph: &Option<Lock<RetainedDepGraph>>,
775        local: &mut LocalEncoderState,
776    ) {
777        node.encode(&mut local.encoder, index);
778        self.flush_mem_encoder(&mut *local);
779        self.record(&node.node, index, node.edges.len(), &node.edges, retained_graph, &mut *local);
780    }
781
782    /// Encodes a node that was promoted from the previous graph. It reads the information directly from
783    /// the previous dep graph for performance reasons.
784    ///
785    /// This differs from `encode_node` where you have to explicitly provide the relevant `NodeInfo`.
786    ///
787    /// It expects all edges to already have a new dep node index assigned.
788    #[inline]
789    fn encode_promoted_node(
790        &self,
791        index: DepNodeIndex,
792        prev_index: SerializedDepNodeIndex,
793        retained_graph: &Option<Lock<RetainedDepGraph>>,
794        local: &mut LocalEncoderState,
795        edges: &[DepNodeIndex],
796    ) {
797        let node = self.previous.index_to_node(prev_index);
798        let value_fingerprint = self.previous.value_fingerprint_for_index(prev_index);
799        let edge_count =
800            NodeInfo::encode_promoted(&mut local.encoder, node, index, value_fingerprint, edges);
801        self.flush_mem_encoder(&mut *local);
802        self.record(node, index, edge_count, edges, retained_graph, &mut *local);
803    }
804
805    fn finish(&self, profiler: &SelfProfilerRef, current: &CurrentDepGraph) -> FileEncodeResult {
806        // Prevent more indices from being allocated.
807        self.next_node_index.store(u32::MAX as u64 + 1, Ordering::SeqCst);
808
809        let results = broadcast(|_| {
810            let mut local = self.local.borrow_mut();
811
812            // Prevent more indices from being allocated on this thread.
813            local.remaining_node_index = 0;
814
815            let data = mem::take(&mut local.encoder.data);
816            self.file.lock().as_mut().unwrap().emit_raw_bytes(&data);
817
818            LocalEncoderResult {
819                kind_stats: local.kind_stats.clone(),
820                node_max: local.next_node_index,
821                node_count: local.node_count,
822                edge_count: local.edge_count,
823            }
824        });
825
826        let mut encoder = self.file.lock().take().unwrap();
827
828        let mut kind_stats: Vec<u32> = iter::repeat_n(0, DepKind::MAX as usize + 1).collect();
829
830        let mut node_max = 0;
831        let mut node_count = 0;
832        let mut edge_count = 0;
833
834        for result in results {
835            node_max = max(node_max, result.node_max);
836            node_count += result.node_count;
837            edge_count += result.edge_count;
838            for (i, stat) in result.kind_stats.iter().enumerate() {
839                kind_stats[i] += stat;
840            }
841        }
842
843        // Encode the number of each dep kind encountered
844        for count in kind_stats.iter() {
845            count.encode(&mut encoder);
846        }
847
848        self.previous.session_count.checked_add(1).unwrap().encode(&mut encoder);
849
850        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/serialized.rs:850",
                        "rustc_middle::dep_graph::serialized",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
                        ::tracing_core::__macro_support::Option::Some(850u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                        ::tracing_core::field::FieldSet::new(&["node_max",
                                        "node_count", "edge_count"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&node_max)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&node_count)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&edge_count)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?node_max, ?node_count, ?edge_count);
851        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/serialized.rs:851",
                        "rustc_middle::dep_graph::serialized",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
                        ::tracing_core::__macro_support::Option::Some(851u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
                                                    encoder.position()) as &dyn Value))])
            });
    } else { ; }
};debug!("position: {:?}", encoder.position());
852        IntEncodedWithFixedSize(node_max.try_into().unwrap()).encode(&mut encoder);
853        IntEncodedWithFixedSize(node_count.try_into().unwrap()).encode(&mut encoder);
854        IntEncodedWithFixedSize(edge_count.try_into().unwrap()).encode(&mut encoder);
855        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/serialized.rs:855",
                        "rustc_middle::dep_graph::serialized",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
                        ::tracing_core::__macro_support::Option::Some(855u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
                                                    encoder.position()) as &dyn Value))])
            });
    } else { ; }
};debug!("position: {:?}", encoder.position());
856        // Drop the encoder so that nothing is written after the counts.
857        let result = encoder.finish();
858        if let Ok(position) = result {
859            // FIXME(rylev): we hardcode the dep graph file name so we
860            // don't need a dependency on rustc_incremental just for that.
861            profiler.artifact_size("dep_graph", "dep-graph.bin", position as u64);
862        }
863
864        self.print_incremental_info(current, node_count, edge_count);
865
866        result
867    }
868
869    fn print_incremental_info(
870        &self,
871        current: &CurrentDepGraph,
872        total_node_count: usize,
873        total_edge_count: usize,
874    ) {
875        if let Some(record_stats) = &self.stats {
876            let record_stats = record_stats.lock();
877            // `stats` is sorted below so we can allow this lint here.
878            #[allow(rustc::potential_query_instability)]
879            let mut stats: Vec<_> = record_stats.values().collect();
880            stats.sort_by_key(|s| -(s.node_counter as i64));
881
882            const SEPARATOR: &str = "[incremental] --------------------------------\
883                                     ----------------------------------------------\
884                                     ------------";
885
886            { ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
887            { ::std::io::_eprint(format_args!("[incremental] DepGraph Statistics\n")); };eprintln!("[incremental] DepGraph Statistics");
888            { ::std::io::_eprint(format_args!("{0}\n", SEPARATOR)); };eprintln!("{SEPARATOR}");
889            { ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
890            {
    ::std::io::_eprint(format_args!("[incremental] Total Node Count: {0}\n",
            total_node_count));
};eprintln!("[incremental] Total Node Count: {}", total_node_count);
891            {
    ::std::io::_eprint(format_args!("[incremental] Total Edge Count: {0}\n",
            total_edge_count));
};eprintln!("[incremental] Total Edge Count: {}", total_edge_count);
892
893            if truecfg!(debug_assertions) {
894                let total_read_count = current.total_read_count.load(Ordering::Relaxed);
895                let total_duplicate_read_count =
896                    current.total_duplicate_read_count.load(Ordering::Relaxed);
897                {
    ::std::io::_eprint(format_args!("[incremental] Total Edge Reads: {0}\n",
            total_read_count));
};eprintln!("[incremental] Total Edge Reads: {total_read_count}");
898                {
    ::std::io::_eprint(format_args!("[incremental] Total Duplicate Edge Reads: {0}\n",
            total_duplicate_read_count));
};eprintln!("[incremental] Total Duplicate Edge Reads: {total_duplicate_read_count}");
899            }
900
901            { ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
902            {
    ::std::io::_eprint(format_args!("[incremental]  {0:<36}| {1:<17}| {2:<12}| {3:<17}|\n",
            "Node Kind", "Node Frequency", "Node Count", "Avg. Edge Count"));
};eprintln!(
903                "[incremental]  {:<36}| {:<17}| {:<12}| {:<17}|",
904                "Node Kind", "Node Frequency", "Node Count", "Avg. Edge Count"
905            );
906            { ::std::io::_eprint(format_args!("{0}\n", SEPARATOR)); };eprintln!("{SEPARATOR}");
907
908            for stat in stats {
909                let node_kind_ratio =
910                    (100.0 * (stat.node_counter as f64)) / (total_node_count as f64);
911                let node_kind_avg_edges = (stat.edge_counter as f64) / (stat.node_counter as f64);
912
913                {
    ::std::io::_eprint(format_args!("[incremental]  {0:<36}|{1:>16.1}% |{2:>12} |{3:>17.1} |\n",
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0:?}", stat.kind))
                }), node_kind_ratio, stat.node_counter, node_kind_avg_edges));
};eprintln!(
914                    "[incremental]  {:<36}|{:>16.1}% |{:>12} |{:>17.1} |",
915                    format!("{:?}", stat.kind),
916                    node_kind_ratio,
917                    stat.node_counter,
918                    node_kind_avg_edges,
919                );
920            }
921
922            { ::std::io::_eprint(format_args!("{0}\n", SEPARATOR)); };eprintln!("{SEPARATOR}");
923            { ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
924        }
925    }
926}
927
928pub(crate) struct GraphEncoder {
929    profiler: SelfProfilerRef,
930    status: EncoderState,
931    /// In-memory copy of the dep graph; only present if `-Zquery-dep-graph` is set.
932    retained_graph: Option<Lock<RetainedDepGraph>>,
933}
934
935impl GraphEncoder {
936    pub(crate) fn new(
937        sess: &Session,
938        encoder: FileEncoder<'static>,
939        prev_node_count: usize,
940        previous: Arc<SerializedDepGraph>,
941    ) -> Self {
942        let retained_graph = sess
943            .opts
944            .unstable_opts
945            .query_dep_graph
946            .then(|| Lock::new(RetainedDepGraph::new(prev_node_count)));
947        let status = EncoderState::new(encoder, sess.opts.unstable_opts.incremental_info, previous);
948        GraphEncoder { status, retained_graph, profiler: sess.prof.clone() }
949    }
950
951    pub(crate) fn retained_dep_graph(&self) -> Option<RetainedDepGraph> {
952        self.retained_graph.as_ref().map(|retained_graph| retained_graph.lock().clone())
953    }
954
955    /// Encodes a node that does not exists in the previous graph.
956    pub(crate) fn send_new(
957        &self,
958        node: DepNode,
959        value_fingerprint: Fingerprint,
960        edges: EdgesVec,
961    ) -> DepNodeIndex {
962        let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
963        let node = NodeInfo { node, value_fingerprint, edges };
964        let mut local = self.status.local.borrow_mut();
965        let index = self.status.next_index(&mut *local);
966        self.status.bump_index(&mut *local);
967        self.status.encode_node(index, &node, &self.retained_graph, &mut *local);
968        index
969    }
970
971    /// Encodes a node that exists in the previous graph, but was re-executed.
972    ///
973    /// This will also ensure the dep node is colored either red or green.
974    pub(crate) fn send_and_color(
975        &self,
976        prev_index: SerializedDepNodeIndex,
977        colors: &DepNodeColorMap,
978        node: DepNode,
979        value_fingerprint: Fingerprint,
980        edges: EdgesVec,
981        is_green: bool,
982    ) -> DepNodeIndex {
983        let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
984        let node = NodeInfo { node, value_fingerprint, edges };
985
986        let mut local = self.status.local.borrow_mut();
987
988        let index = self.status.next_index(&mut *local);
989        let color = if is_green { DesiredColor::Green { index } } else { DesiredColor::Red };
990
991        // Use `try_set_color` to avoid racing when `send_promoted` is called concurrently
992        // on the same index.
993        match colors.try_set_color(prev_index, color) {
994            TrySetColorResult::Success => {}
995            TrySetColorResult::AlreadyRed => {
    ::core::panicking::panic_fmt(format_args!("dep node {0:?} is unexpectedly red",
            prev_index));
}panic!("dep node {prev_index:?} is unexpectedly red"),
996            TrySetColorResult::AlreadyGreen { index } => return index,
997        }
998
999        self.status.bump_index(&mut *local);
1000        self.status.encode_node(index, &node, &self.retained_graph, &mut *local);
1001        index
1002    }
1003
1004    /// Encodes a node that was promoted from the previous graph. It reads the information directly
1005    /// from the previous dep graph and expects all edges to already have a new dep node index
1006    /// assigned.
1007    ///
1008    /// Tries to mark the dep node green, and returns Some if it is now green,
1009    /// or None if had already been concurrently marked red.
1010    #[inline]
1011    pub(crate) fn send_promoted(
1012        &self,
1013        prev_index: SerializedDepNodeIndex,
1014        colors: &DepNodeColorMap,
1015        edges: &[DepNodeIndex],
1016    ) -> Option<DepNodeIndex> {
1017        let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
1018
1019        let mut local = self.status.local.borrow_mut();
1020        let index = self.status.next_index(&mut *local);
1021
1022        // Use `try_set_color` to avoid racing when `send_promoted` or `send_and_color`
1023        // is called concurrently on the same index.
1024        match colors.try_set_color(prev_index, DesiredColor::Green { index }) {
1025            TrySetColorResult::Success => {
1026                self.status.bump_index(&mut *local);
1027                self.status.encode_promoted_node(
1028                    index,
1029                    prev_index,
1030                    &self.retained_graph,
1031                    &mut *local,
1032                    edges,
1033                );
1034                Some(index)
1035            }
1036            TrySetColorResult::AlreadyRed => None,
1037            TrySetColorResult::AlreadyGreen { index } => Some(index),
1038        }
1039    }
1040
1041    pub(crate) fn finish(&self, current: &CurrentDepGraph) -> FileEncodeResult {
1042        let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph_finish");
1043
1044        self.status.finish(&self.profiler, current)
1045    }
1046}