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.
4142use std::cell::RefCell;
43use std::cmp::max;
44use std::sync::atomic::Ordering;
45use std::sync::{Arc, OnceLock};
46use std::{iter, mem};
4748use 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};
6061use super::graph::{CurrentDepGraph, DepNodeColorMap, DesiredColor, TrySetColorResult};
62use super::retained::RetainedDepGraph;
63use super::{DepKind, DepNode, DepNodeIndex};
6465// 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]
71pub struct SerializedDepNodeIndex {}
72}7374impl 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)]
78pub fn from_curr_for_serialization(index: DepNodeIndex) -> Self {
79SerializedDepNodeIndex::from_u32(index.as_u32())
80 }
81}
8283const 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;
9293/// 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
100nodes: 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`]).
107value_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.
111edge_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.
114edge_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`].
118reverse_index: LazyNodeIndex,
119/// The number of previous compilation sessions. This is used to generate
120 /// unique anon dep nodes per session.
121session_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.
124profiler: Option<SelfProfilerRef>,
125}
126127// `SelfProfilerRef` is not `Debug`, so we can't derive this.
128impl std::fmt::Debugfor SerializedDepGraph {
129fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130f.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}
140141/// 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`.
151nodes_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.
154kinds: Vec<LazyKindIndex>,
155}
156157#[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.
160start: u32,
161/// Number of nodes of this kind.
162len: 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.
165map: OnceLock<UnhashMap<PackedFingerprint, SerializedDepNodeIndex>>,
166}
167168impl LazyKindIndex {
169/// Returns this kind's `key_fingerprint -> node index` map.
170fn 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> {
177self.map.get_or_init(|| {
178let _prof_timer = profiler179 .as_ref()
180 .map(|p| p.generic_activity("incr_comp_load_dep_graph_reverse_index"));
181let range = (self.start as usize)..(self.start as usize + self.len as usize);
182let mut map =
183UnhashMap::with_capacity_and_hasher(self.len as usize, Default::default());
184for &idx in &nodes_by_kind[range] {
185let idx = idx.expect("counting sort fills every slot of a kind's range");
186let node = nodes[idx];
187if 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);
188if 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 }
201map202 })
203 }
204}
205206impl SerializedDepGraph {
207#[inline]
208pub fn edge_targets_from(
209&self,
210 source: SerializedDepNodeIndex,
211 ) -> impl Iterator<Item = SerializedDepNodeIndex> + Clone {
212let header = self.edge_list_indices[source];
213let mut raw = &self.edge_list_data[header.start()..];
214215let bytes_per_index = header.bytes_per_index();
216217// LLVM doesn't hoist EdgeHeader::mask so we do it ourselves.
218let 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.
222let index = &raw[..DEP_NODE_SIZE];
223raw = &raw[bytes_per_index..];
224let index = u32::from_le_bytes(index.try_into().unwrap()) & mask;
225SerializedDepNodeIndex::from_u32(index)
226 })
227 }
228229#[inline]
230pub fn index_to_node(&self, dep_node_index: SerializedDepNodeIndex) -> &DepNode {
231&self.nodes[dep_node_index]
232 }
233234#[inline]
235pub fn node_to_index_opt(&self, dep_node: &DepNode) -> Option<SerializedDepNodeIndex> {
236let kind = self.reverse_index.kinds.get(dep_node.kind.as_usize())?;
237let map = kind.fingerprint_map(
238dep_node.kind,
239&self.nodes,
240&self.reverse_index.nodes_by_kind,
241&self.profiler,
242 );
243map.get(&dep_node.key_fingerprint).copied()
244 }
245246#[inline]
247pub fn value_fingerprint_for_index(
248&self,
249 dep_node_index: SerializedDepNodeIndex,
250 ) -> Fingerprint {
251self.value_fingerprints[dep_node_index]
252 }
253254#[inline]
255pub fn node_count(&self) -> usize {
256self.nodes.len()
257 }
258259#[inline]
260pub fn session_count(&self) -> u64 {
261self.session_count
262 }
263}
264265/// 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}
274275impl EdgeHeader {
276#[inline]
277fn start(self) -> usize {
278self.repr >> DEP_NODE_WIDTH_BITS279 }
280281#[inline]
282fn bytes_per_index(self) -> usize {
283 (self.repr & mask(DEP_NODE_WIDTH_BITS)) + 1
284}
285286#[inline]
287fn mask(self) -> u32 {
288mask(self.bytes_per_index() * 8) as u32289 }
290}
291292#[inline]
293fn mask(bits: usize) -> usize {
294usize::MAX >> ((size_of::<usize>() * 8) - bits)
295}
296297impl 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))]299pub fn decode(d: &mut MemDecoder<'_>, profiler: &SelfProfilerRef) -> Arc<SerializedDepGraph> {
300// The last 16 bytes are the node count and edge count.
301debug!("position: {:?}", d.position());
302303// `node_max` is the number of indices including empty nodes while `node_count`
304 // is the number of actually encoded nodes.
305let (node_max, node_count, edge_count) =
306 d.with_position(d.len() - 3 * IntEncodedWithFixedSize::ENCODED_SIZE, |d| {
307debug!("position: {:?}", d.position());
308let node_max = IntEncodedWithFixedSize::decode(d).0 as usize;
309let node_count = IntEncodedWithFixedSize::decode(d).0 as usize;
310let edge_count = IntEncodedWithFixedSize::decode(d).0 as usize;
311 (node_max, node_count, edge_count)
312 });
313debug!("position: {:?}", d.position());
314315debug!(?node_count, ?edge_count);
316317let graph_bytes = d.len() - (3 * IntEncodedWithFixedSize::ENCODED_SIZE) - d.position();
318319let mut nodes = IndexVec::from_elem_n(
320 DepNode {
321 kind: DepKind::Null,
322 key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
323 },
324 node_max,
325 );
326let mut value_fingerprints = IndexVec::from_elem_n(Fingerprint::ZERO, node_max);
327let mut edge_list_indices =
328 IndexVec::from_elem_n(EdgeHeader { repr: 0, num_edges: 0 }, node_max);
329330// 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.
339let mut edge_list_data =
340 Vec::with_capacity(graph_bytes - node_count * size_of::<SerializedNodeHeader>());
341342for _ 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.
345let node_header = SerializedNodeHeader { bytes: d.read_array() };
346347let index = node_header.index();
348349let node = &mut nodes[index];
350// Make sure there's no duplicate indices in the dep graph.
351assert!(node_header.node().kind != DepKind::Null && node.kind == DepKind::Null);
352*node = node_header.node();
353354 value_fingerprints[index] = node_header.value_fingerprint();
355356// 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.
358let num_edges = node_header.len().unwrap_or_else(|| d.read_u32());
359360// 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.
363let 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.
366let edges_header = node_header.edges_header(&edge_list_data, num_edges);
367368 edge_list_data.extend(d.read_raw_bytes(edges_len_bytes));
369370 edge_list_indices[index] = edges_header;
371 }
372373// 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.
376edge_list_data.extend(&[0u8; DEP_NODE_PAD]);
377378// Read the number of nodes of each dep kind, and perform
379 // counting sort for `LazyNodeIndex`.
380let mut kinds = Vec::with_capacity(DepKind::MAX as usize + 1);
381let mut offset = 0u32;
382for _ in 0..(DepKind::MAX + 1) {
383let len = d.read_u32();
384 kinds.push(LazyKindIndex { start: offset, len, map: OnceLock::new() });
385 offset += len;
386 }
387debug_assert_eq!(offset as usize, node_count);
388389let session_count = d.read_u64();
390391// 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).
395let mut nodes_by_kind = vec![None; node_count];
396let mut fill: Vec<u32> = kinds.iter().map(|k| k.start).collect();
397for (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.
400if node.kind == DepKind::Null {
401continue;
402 }
403let 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.
408debug_assert!(kinds.iter().zip(&fill).all(|(k, &f)| f == k.start + k.len));
409let reverse_index = LazyNodeIndex { nodes_by_kind, kinds };
410411 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}
422423/// 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
436bytes: [u8; 38],
437}
438439// 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}
449450// 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 {
458const TOTAL_BITS: usize = size_of::<DepKind>() * 8;
459const LEN_BITS: usize = Self::TOTAL_BITS - Self::KIND_BITS - Self::WIDTH_BITS;
460const WIDTH_BITS: usize = DEP_NODE_WIDTH_BITS;
461const KIND_BITS: usize = Self::TOTAL_BITS - DepKind::MAX.leading_zeros() as usize;
462const MAX_INLINE_LEN: usize = (u16::MAXas usize >> (Self::TOTAL_BITS - Self::LEN_BITS)) - 1;
463464#[inline]
465fn new(
466 node: &DepNode,
467 index: DepNodeIndex,
468 value_fingerprint: Fingerprint,
469 edge_max_index: u32,
470 edge_count: usize,
471 ) -> Self {
472if 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);
473474let mut head = node.kind.as_u16();
475476let free_bytes = edge_max_index.leading_zeros() as usize / 8;
477let bytes_per_index = (DEP_NODE_SIZE - free_bytes).saturating_sub(1);
478head |= (bytes_per_indexas u16) << Self::KIND_BITS;
479480// Encode number of edges + 1 so that we can reserve 0 to indicate that the len doesn't fit
481 // in this bitfield.
482if edge_count <= Self::MAX_INLINE_LEN {
483head |= (edge_countas u16 + 1) << (Self::KIND_BITS + Self::WIDTH_BITS);
484 }
485486let hash: Fingerprint = node.key_fingerprint.into();
487488// Using half-open ranges ensures an unconditional panic if we get the magic numbers wrong.
489let mut bytes = [0u8; 38];
490bytes[..2].copy_from_slice(&head.to_le_bytes());
491bytes[2..6].copy_from_slice(&index.as_u32().to_le_bytes());
492bytes[6..22].copy_from_slice(&hash.to_le_bytes());
493bytes[22..].copy_from_slice(&value_fingerprint.to_le_bytes());
494495#[cfg(debug_assertions)]
496{
497let 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());
500if 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 }
504Self { bytes }
505 }
506507#[inline]
508fn unpack(&self) -> Unpacked {
509let head = u16::from_le_bytes(self.bytes[..2].try_into().unwrap());
510let index = u32::from_le_bytes(self.bytes[2..6].try_into().unwrap());
511let key_fingerprint = self.bytes[6..22].try_into().unwrap();
512let value_fingerprint = self.bytes[22..].try_into().unwrap();
513514let kind = head & mask(Self::KIND_BITS) as u16;
515let bytes_per_index = (head >> Self::KIND_BITS) & mask(Self::WIDTH_BITS) as u16;
516let len = (headas u32) >> (Self::WIDTH_BITS + Self::KIND_BITS);
517518Unpacked {
519 len: len.checked_sub(1),
520 bytes_per_index: bytes_per_indexas 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 }
527528#[inline]
529fn len(&self) -> Option<u32> {
530self.unpack().len
531 }
532533#[inline]
534fn bytes_per_index(&self) -> usize {
535self.unpack().bytes_per_index
536 }
537538#[inline]
539fn index(&self) -> SerializedDepNodeIndex {
540self.unpack().index
541 }
542543#[inline]
544fn value_fingerprint(&self) -> Fingerprint {
545self.unpack().value_fingerprint
546 }
547548#[inline]
549fn node(&self) -> DepNode {
550let Unpacked { kind, key_fingerprint, .. } = self.unpack();
551DepNode { kind, key_fingerprint }
552 }
553554#[inline]
555fn edges_header(&self, edge_list_data: &[u8], num_edges: u32) -> EdgeHeader {
556EdgeHeader {
557 repr: (edge_list_data.len() << DEP_NODE_WIDTH_BITS) | (self.bytes_per_index() - 1),
558num_edges,
559 }
560 }
561}
562563#[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}
569570impl NodeInfo<'_> {
571fn encode(&self, e: &mut MemEncoder, index: DepNodeIndex) {
572let NodeInfo { ref node, value_fingerprint, edges } = *self;
573// The largest index picks the byte width of the edge list.
574let edge_max = edges.iter().map(|e| e.as_u32()).max().unwrap_or(0);
575let header =
576SerializedNodeHeader::new(node, index, value_fingerprint, edge_max, edges.len());
577e.write_array(header.bytes);
578579if header.len().is_none() {
580// The edges are all unique and the number of unique indices is less than u32::MAX.
581e.emit_u32(edges.len().try_into().unwrap());
582 }
583584let bytes_per_index = header.bytes_per_index();
585for 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}
593594struct Stat {
595 kind: DepKind,
596 node_counter: u64,
597 edge_counter: u64,
598}
599600struct LocalEncoderState {
601 next_node_index: u32,
602 remaining_node_index: u32,
603 encoder: MemEncoder,
604 node_count: usize,
605 edge_count: usize,
606607/// Stores the number of times we've encoded each dep kind.
608kind_stats: Vec<u32>,
609}
610611struct LocalEncoderResult {
612 node_max: u32,
613 node_count: usize,
614 edge_count: usize,
615616/// Stores the number of times we've encoded each dep kind.
617kind_stats: Vec<u32>,
618}
619620struct 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}
627628impl EncoderState {
629fn new(
630 encoder: FileEncoder<'static>,
631 record_stats: bool,
632 previous: Arc<SerializedDepGraph>,
633 ) -> Self {
634Self {
635previous,
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(|_| {
640RefCell::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::MAXas usize + 1).collect(),
647 })
648 }),
649 }
650 }
651652#[inline]
653fn next_index(&self, local: &mut LocalEncoderState) -> DepNodeIndex {
654if local.remaining_node_index == 0 {
655const COUNT: u32 = 256;
656657// 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.
660local.next_node_index =
661self.next_node_index.fetch_add(COUNTas u64, Ordering::Relaxed).try_into().unwrap();
662663// Check that we'll stay within `u32`
664local.next_node_index.checked_add(COUNT).unwrap();
665666local.remaining_node_index = COUNT;
667 }
668669DepNodeIndex::from_u32(local.next_node_index)
670 }
671672/// Marks the index previously returned by `next_index` as used.
673#[inline]
674fn bump_index(&self, local: &mut LocalEncoderState) {
675local.remaining_node_index -= 1;
676local.next_node_index += 1;
677local.node_count += 1;
678 }
679680#[inline]
681fn 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 ) {
690local.kind_stats[node.kind.as_usize()] += 1;
691local.edge_count += edge_count;
692693if let Some(retained_graph) = &retained_graph {
694// Outline the build of the full dep graph as it's typically disabled and cold.
695outline(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`.
701retained_graph.lock().push(index, *node, edges);
702 });
703 }
704705if let Some(stats) = &self.stats {
706let kind = node.kind;
707708// Outline the stats code as it's typically disabled and cold.
709outline(move || {
710let mut stats = stats.lock();
711let stat =
712stats.entry(kind).or_insert(Stat { kind, node_counter: 0, edge_counter: 0 });
713stat.node_counter += 1;
714stat.edge_counter += edge_countas u64;
715 });
716 }
717 }
718719#[inline]
720fn flush_mem_encoder(&self, local: &mut LocalEncoderState) {
721let data = &mut local.encoder.data;
722if data.len() > 64 * 1024 {
723self.file.lock().as_mut().unwrap().emit_raw_bytes(&data[..]);
724data.clear();
725 }
726 }
727728/// Encodes a node to the current graph.
729fn encode_node(
730&self,
731 index: DepNodeIndex,
732 node: &NodeInfo<'_>,
733 retained_graph: &Option<Lock<RetainedDepGraph>>,
734 local: &mut LocalEncoderState,
735 ) {
736node.encode(&mut local.encoder, index);
737self.flush_mem_encoder(&mut *local);
738self.record(&node.node, index, node.edges.len(), node.edges, retained_graph, &mut *local);
739 }
740741/// 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]
745fn 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 ) {
753let node = NodeInfo {
754 node: *self.previous.index_to_node(prev_index),
755 value_fingerprint: self.previous.value_fingerprint_for_index(prev_index),
756edges,
757 };
758self.encode_node(index, &node, retained_graph, local);
759 }
760761fn finish(&self, profiler: &SelfProfilerRef, current: &CurrentDepGraph) -> FileEncodeResult {
762// Prevent more indices from being allocated.
763self.next_node_index.store(u32::MAXas u64 + 1, Ordering::SeqCst);
764765let results = broadcast(|_| {
766let mut local = self.local.borrow_mut();
767768// Prevent more indices from being allocated on this thread.
769local.remaining_node_index = 0;
770771let data = mem::take(&mut local.encoder.data);
772self.file.lock().as_mut().unwrap().emit_raw_bytes(&data);
773774LocalEncoderResult {
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 });
781782let mut encoder = self.file.lock().take().unwrap();
783784let mut kind_stats: Vec<u32> = iter::repeat_n(0, DepKind::MAXas usize + 1).collect();
785786let mut node_max = 0;
787let mut node_count = 0;
788let mut edge_count = 0;
789790for result in results {
791 node_max = max(node_max, result.node_max);
792 node_count += result.node_count;
793 edge_count += result.edge_count;
794for (i, stat) in result.kind_stats.iter().enumerate() {
795 kind_stats[i] += stat;
796 }
797 }
798799// Encode the number of each dep kind encountered
800for count in kind_stats.iter() {
801 count.encode(&mut encoder);
802 }
803804self.previous.session_count.checked_add(1).unwrap().encode(&mut encoder);
805806{
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());
808IntEncodedWithFixedSize(node_max.try_into().unwrap()).encode(&mut encoder);
809IntEncodedWithFixedSize(node_count.try_into().unwrap()).encode(&mut encoder);
810IntEncodedWithFixedSize(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.
813let result = encoder.finish();
814if 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.
817profiler.artifact_size("dep_graph", "dep-graph.bin", positionas u64);
818 }
819820self.print_incremental_info(current, node_count, edge_count);
821822result823 }
824825fn print_incremental_info(
826&self,
827 current: &CurrentDepGraph,
828 total_node_count: usize,
829 total_edge_count: usize,
830 ) {
831if let Some(record_stats) = &self.stats {
832let record_stats = record_stats.lock();
833// `stats` is sorted below so we can allow this lint here.
834#[allow(rustc::potential_query_instability)]
835let mut stats: Vec<_> = record_stats.values().collect();
836stats.sort_by_key(|s| -(s.node_counter as i64));
837838const SEPARATOR: &str = "[incremental] --------------------------------\
839 ----------------------------------------------\
840 ------------";
841842{ ::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);
848849if truecfg!(debug_assertions) {
850let total_read_count = current.total_read_count.load(Ordering::Relaxed);
851let total_duplicate_read_count =
852current.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 }
856857{ ::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}");
863864for stat in stats {
865let node_kind_ratio =
866 (100.0 * (stat.node_counter as f64)) / (total_node_count as f64);
867let node_kind_avg_edges = (stat.edge_counter as f64) / (stat.node_counter as f64);
868869{
::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} |",
871format!("{:?}", stat.kind),
872 node_kind_ratio,
873 stat.node_counter,
874 node_kind_avg_edges,
875 );
876 }
877878{ ::std::io::_eprint(format_args!("{0}\n", SEPARATOR)); };eprintln!("{SEPARATOR}");
879{ ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
880 }
881 }
882}
883884pub(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.
888retained_graph: Option<Lock<RetainedDepGraph>>,
889}
890891impl GraphEncoder {
892pub(crate) fn new(
893 sess: &Session,
894 encoder: FileEncoder<'static>,
895 prev_node_count: usize,
896 previous: Arc<SerializedDepGraph>,
897 ) -> Self {
898let retained_graph = sess899 .opts
900 .unstable_opts
901 .query_dep_graph
902 .then(|| Lock::new(RetainedDepGraph::new(prev_node_count)));
903let status = EncoderState::new(encoder, sess.opts.unstable_opts.incremental_info, previous);
904GraphEncoder { status, retained_graph, profiler: sess.prof.clone() }
905 }
906907pub(crate) fn retained_dep_graph(&self) -> Option<RetainedDepGraph> {
908self.retained_graph.as_ref().map(|retained_graph| retained_graph.lock().clone())
909 }
910911/// Encodes a node that does not exists in the previous graph.
912pub(crate) fn send_new(
913&self,
914 node: DepNode,
915 value_fingerprint: Fingerprint,
916 edges: &[DepNodeIndex],
917 ) -> DepNodeIndex {
918let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
919let node = NodeInfo { node, value_fingerprint, edges };
920let mut local = self.status.local.borrow_mut();
921let index = self.status.next_index(&mut *local);
922self.status.bump_index(&mut *local);
923self.status.encode_node(index, &node, &self.retained_graph, &mut *local);
924index925 }
926927/// 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.
930pub(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 {
939let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
940let node = NodeInfo { node, value_fingerprint, edges };
941942let mut local = self.status.local.borrow_mut();
943944let index = self.status.next_index(&mut *local);
945let color = if is_green { DesiredColor::Green { index } } else { DesiredColor::Red };
946947// Use `try_set_color` to avoid racing when `send_promoted` is called concurrently
948 // on the same index.
949match 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 }
954955self.status.bump_index(&mut *local);
956self.status.encode_node(index, &node, &self.retained_graph, &mut *local);
957index958 }
959960/// 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]
967pub(crate) fn send_promoted(
968&self,
969 prev_index: SerializedDepNodeIndex,
970 colors: &DepNodeColorMap,
971 edges: &[DepNodeIndex],
972 ) -> Option<DepNodeIndex> {
973let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
974975let mut local = self.status.local.borrow_mut();
976let index = self.status.next_index(&mut *local);
977978// Use `try_set_color` to avoid racing when `send_promoted` or `send_and_color`
979 // is called concurrently on the same index.
980match colors.try_set_color(prev_index, DesiredColor::Green { index }) {
981 TrySetColorResult::Success => {
982self.status.bump_index(&mut *local);
983self.status.encode_promoted_node(
984index,
985prev_index,
986&self.retained_graph,
987&mut *local,
988edges,
989 );
990Some(index)
991 }
992 TrySetColorResult::AlreadyRed => None,
993 TrySetColorResult::AlreadyGreen { index } => Some(index),
994 }
995 }
996997pub(crate) fn finish(&self, current: &CurrentDepGraph) -> FileEncodeResult {
998let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph_finish");
9991000self.status.finish(&self.profiler, current)
1001 }
1002}