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