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