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(),
live_node_count: ::core::default::Default::default(),
session_count: ::core::default::Default::default(),
profiler: ::core::default::Default::default(),
}
}
}Default)]
98pub struct SerializedDepGraph {
99/// The set of all DepNodes in the graph
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 nodes actually encoded, which is below [`Self::index_space_len`]
120 /// whenever a thread left part of its batch of indices unused.
121live_node_count: usize,
122/// The number of previous compilation sessions. This is used to generate
123 /// unique anon dep nodes per session.
124session_count: u64,
125/// Used to time the lazy per-`DepKind` reverse-index build. `None` only for
126 /// the empty default graph, which is never looked up.
127profiler: Option<SelfProfilerRef>,
128}
129130// `SelfProfilerRef` is not `Debug`, so we can't derive this.
131impl std::fmt::Debugfor SerializedDepGraph {
132fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133f.debug_struct("SerializedDepGraph")
134 .field("nodes", &self.nodes)
135 .field("value_fingerprints", &self.value_fingerprints)
136 .field("edge_list_indices", &self.edge_list_indices)
137 .field("edge_list_data", &self.edge_list_data)
138 .field("reverse_index", &self.reverse_index)
139 .field("live_node_count", &self.live_node_count)
140 .field("session_count", &self.session_count)
141 .finish_non_exhaustive()
142 }
143}
144145/// The inverse of [`SerializedDepGraph::nodes`], built lazily per [`DepKind`].
146///
147/// Only few nodes are ever looked up here, and those cluster into a handful of
148/// `DepKind`s. Building a map for every kind up front would be wasted work.
149#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LazyNodeIndex {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "LazyNodeIndex",
"nodes_by_kind", &self.nodes_by_kind, "kinds", &&self.kinds)
}
}Debug, #[automatically_derived]
impl ::core::default::Default for LazyNodeIndex {
#[inline]
fn default() -> LazyNodeIndex {
LazyNodeIndex {
nodes_by_kind: ::core::default::Default::default(),
kinds: ::core::default::Default::default(),
}
}
}Default)]
150struct LazyNodeIndex {
151/// All (non-`Null`) node indices, grouped into contiguous per-`DepKind`
152 /// ranges described by `kinds`. For any non-`Null` `DepKind` `k`, all values in
153 /// `nodes_by_kind[kinds[k].start..][..kinds[k].len]`
154 /// must be `Some` and have kind `k`.
155nodes_by_kind: Vec<Option<SerializedDepNodeIndex>>,
156/// For each `DepKind`, the range of `nodes_by_kind` holding its node indices
157 /// and the lazily-built fingerprint map over that range.
158kinds: Vec<LazyKindIndex>,
159}
160161#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LazyKindIndex {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "LazyKindIndex",
"start", &self.start, "len", &self.len, "map", &&self.map)
}
}Debug, #[automatically_derived]
impl ::core::default::Default for LazyKindIndex {
#[inline]
fn default() -> LazyKindIndex {
LazyKindIndex {
start: ::core::default::Default::default(),
len: ::core::default::Default::default(),
map: ::core::default::Default::default(),
}
}
}Default)]
162struct LazyKindIndex {
163/// Offset into `LazyNodeIndex::nodes_by_kind` of this kind's first node.
164start: u32,
165/// Number of nodes of this kind.
166len: u32,
167/// `key_fingerprint -> node index`, built from this kind's range on first
168 /// lookup. Empty kinds (and kinds never looked up) never build a map.
169map: OnceLock<UnhashMap<PackedFingerprint, SerializedDepNodeIndex>>,
170}
171172impl LazyKindIndex {
173/// Returns this kind's `key_fingerprint -> node index` map.
174fn fingerprint_map(
175&self,
176 kind: DepKind,
177 nodes: &IndexSlice<SerializedDepNodeIndex, DepNode>,
178 nodes_by_kind: &[Option<SerializedDepNodeIndex>],
179 profiler: &Option<SelfProfilerRef>,
180 ) -> &UnhashMap<PackedFingerprint, SerializedDepNodeIndex> {
181self.map.get_or_init(|| {
182let _prof_timer = profiler183 .as_ref()
184 .map(|p| p.generic_activity("incr_comp_load_dep_graph_reverse_index"));
185let range = (self.start as usize)..(self.start as usize + self.len as usize);
186let mut map =
187UnhashMap::with_capacity_and_hasher(self.len as usize, Default::default());
188for &idx in &nodes_by_kind[range] {
189let idx = idx.expect("counting sort fills every slot of a kind's range");
190let node = nodes[idx];
191if 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);
192if map.insert(node.key_fingerprint, idx).is_some()
193// Side effect nodes can legitimately share a fingerprint.
194&& node.kind != DepKind::SideEffect
195 {
196{
::core::panicking::panic_fmt(format_args!("Error: A dep graph node ({0:?}) does not have an unique index. Running a clean build on a nightly compiler with `-Z incremental-verify-ich` can help narrow down the issue for reporting. A clean build may also work around the issue.\n\n DepNode: {1:?}",
kind, node));
}panic!(
197"Error: A dep graph node ({kind:?}) does not have an unique index. \
198 Running a clean build on a nightly compiler with \
199 `-Z incremental-verify-ich` can help narrow down the issue for reporting. \
200 A clean build may also work around the issue.\n
201 DepNode: {node:?}"
202)203 }
204 }
205map206 })
207 }
208}
209210impl SerializedDepGraph {
211#[inline]
212pub fn edge_targets_from(
213&self,
214 source: SerializedDepNodeIndex,
215 ) -> impl Iterator<Item = SerializedDepNodeIndex> + Clone {
216let header = self.edge_list_indices[source];
217let mut raw = &self.edge_list_data[header.start()..];
218219let bytes_per_index = header.bytes_per_index();
220221// LLVM doesn't hoist EdgeHeader::mask so we do it ourselves.
222let mask = header.mask();
223 (0..header.num_edges).map(move |_| {
224// Doing this slicing in this order ensures that the first bounds check suffices for
225 // all the others.
226let index = &raw[..DEP_NODE_SIZE];
227raw = &raw[bytes_per_index..];
228let index = u32::from_le_bytes(index.try_into().unwrap()) & mask;
229SerializedDepNodeIndex::from_u32(index)
230 })
231 }
232233#[inline]
234pub fn index_to_node(&self, dep_node_index: SerializedDepNodeIndex) -> &DepNode {
235&self.nodes[dep_node_index]
236 }
237238#[inline]
239pub fn node_to_index_opt(&self, dep_node: &DepNode) -> Option<SerializedDepNodeIndex> {
240let kind = self.reverse_index.kinds.get(dep_node.kind.as_usize())?;
241let map = kind.fingerprint_map(
242dep_node.kind,
243&self.nodes,
244&self.reverse_index.nodes_by_kind,
245&self.profiler,
246 );
247map.get(&dep_node.key_fingerprint).copied()
248 }
249250#[inline]
251pub fn value_fingerprint_for_index(
252&self,
253 dep_node_index: SerializedDepNodeIndex,
254 ) -> Fingerprint {
255self.value_fingerprints[dep_node_index]
256 }
257258/// The number of dep-node indices, counting those that hold no node.
259#[inline]
260pub fn index_space_len(&self) -> usize {
261self.nodes.len()
262 }
263264#[inline]
265pub fn live_node_count(&self) -> usize {
266self.live_node_count
267 }
268269#[inline]
270pub fn session_count(&self) -> u64 {
271self.session_count
272 }
273}
274275/// A packed representation of an edge's start index and byte width.
276///
277/// This is packed by stealing 2 bits from the start index, which means we only accommodate edge
278/// data arrays up to a quarter of our address space. Which seems fine.
279#[derive(#[automatically_derived]
impl ::core::fmt::Debug for EdgeHeader {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "EdgeHeader",
"repr", &self.repr, "num_edges", &&self.num_edges)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for EdgeHeader {
#[inline]
fn clone(&self) -> EdgeHeader {
let _: ::core::clone::AssertParamIsClone<usize>;
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for EdgeHeader { }Copy)]
280struct EdgeHeader {
281 repr: usize,
282 num_edges: u32,
283}
284285impl EdgeHeader {
286#[inline]
287fn start(self) -> usize {
288self.repr >> DEP_NODE_WIDTH_BITS289 }
290291#[inline]
292fn bytes_per_index(self) -> usize {
293 (self.repr & mask(DEP_NODE_WIDTH_BITS)) + 1
294}
295296#[inline]
297fn mask(self) -> u32 {
298mask(self.bytes_per_index() * 8) as u32299 }
300}
301302#[inline]
303fn mask(bits: usize) -> usize {
304usize::MAX >> ((size_of::<usize>() * 8) - bits)
305}
306307impl SerializedDepGraph {
308#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("decode",
"rustc_middle::dep_graph::serialized",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
::tracing_core::__macro_support::Option::Some(308u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Arc<SerializedDepGraph> = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/serialized.rs:311",
"rustc_middle::dep_graph::serialized",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
::tracing_core::__macro_support::Option::Some(311u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
d.position()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let (node_max, node_count, edge_count) =
d.with_position(d.len() -
3 * IntEncodedWithFixedSize::ENCODED_SIZE,
|d|
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/serialized.rs:317",
"rustc_middle::dep_graph::serialized",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
::tracing_core::__macro_support::Option::Some(317u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
d.position()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let node_max =
IntEncodedWithFixedSize::decode(d).0 as usize;
let node_count =
IntEncodedWithFixedSize::decode(d).0 as usize;
let edge_count =
IntEncodedWithFixedSize::decode(d).0 as usize;
(node_max, node_count, edge_count)
});
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/serialized.rs:323",
"rustc_middle::dep_graph::serialized",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
::tracing_core::__macro_support::Option::Some(323u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
d.position()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/serialized.rs:325",
"rustc_middle::dep_graph::serialized",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
::tracing_core::__macro_support::Option::Some(325u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("node_count")
}> =
::tracing::__macro_support::FieldName::new("node_count");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("edge_count")
}> =
::tracing::__macro_support::FieldName::new("edge_count");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_count)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&edge_count)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let graph_bytes =
d.len() - (3 * IntEncodedWithFixedSize::ENCODED_SIZE) -
d.position();
let mut nodes =
IndexVec::from_elem_n(DepNode {
kind: DepKind::Null,
key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
}, node_max);
let mut value_fingerprints =
IndexVec::from_elem_n(Fingerprint::ZERO, node_max);
let mut edge_list_indices =
IndexVec::from_elem_n(EdgeHeader { repr: 0, num_edges: 0 },
node_max);
let mut edge_list_data =
Vec::with_capacity(graph_bytes -
node_count * size_of::<SerializedNodeHeader>());
for _ in 0..node_count {
let node_header =
SerializedNodeHeader { bytes: d.read_array() };
let index = node_header.index();
let node = &mut nodes[index];
if !(node_header.node().kind != DepKind::Null &&
node.kind == DepKind::Null) {
::core::panicking::panic("assertion failed: node_header.node().kind != DepKind::Null && node.kind == DepKind::Null")
};
*node = node_header.node();
value_fingerprints[index] = node_header.value_fingerprint();
let num_edges =
node_header.len().unwrap_or_else(|| d.read_u32());
let edges_len_bytes =
node_header.bytes_per_index() * (num_edges as usize);
let edges_header =
node_header.edges_header(&edge_list_data, num_edges);
edge_list_data.extend(d.read_raw_bytes(edges_len_bytes));
edge_list_indices[index] = edges_header;
}
edge_list_data.extend(&[0u8; DEP_NODE_PAD]);
let mut kinds = Vec::with_capacity(DepKind::MAX as usize + 1);
let mut offset = 0u32;
for _ in 0..(DepKind::MAX + 1) {
let len = d.read_u32();
kinds.push(LazyKindIndex {
start: offset,
len,
map: OnceLock::new(),
});
offset += len;
}
if true {
{
match (&(offset as usize), &node_count) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};
let session_count = d.read_u64();
let mut nodes_by_kind = ::alloc::vec::from_elem(None, node_count);
let mut fill: Vec<u32> = kinds.iter().map(|k| k.start).collect();
for (idx, node) in nodes.iter_enumerated() {
if node.kind == DepKind::Null { continue; }
let k = node.kind.as_usize();
nodes_by_kind[fill[k] as usize] = Some(idx);
fill[k] += 1;
}
if true {
if !kinds.iter().zip(&fill).all(|(k, &f)|
f == k.start + k.len) {
::core::panicking::panic("assertion failed: kinds.iter().zip(&fill).all(|(k, &f)| f == k.start + k.len)")
};
};
let reverse_index = LazyNodeIndex { nodes_by_kind, kinds };
Arc::new(SerializedDepGraph {
nodes,
value_fingerprints,
edge_list_indices,
edge_list_data,
reverse_index,
live_node_count: node_count,
session_count,
profiler: Some(profiler.clone()),
})
}
}
}#[instrument(level = "debug", skip(d, profiler))]309pub fn decode(d: &mut MemDecoder<'_>, profiler: &SelfProfilerRef) -> Arc<SerializedDepGraph> {
310// The last 16 bytes are the node count and edge count.
311debug!("position: {:?}", d.position());
312313// `node_max` is the number of indices including empty nodes while `node_count`
314 // is the number of actually encoded nodes.
315let (node_max, node_count, edge_count) =
316 d.with_position(d.len() - 3 * IntEncodedWithFixedSize::ENCODED_SIZE, |d| {
317debug!("position: {:?}", d.position());
318let node_max = IntEncodedWithFixedSize::decode(d).0 as usize;
319let node_count = IntEncodedWithFixedSize::decode(d).0 as usize;
320let edge_count = IntEncodedWithFixedSize::decode(d).0 as usize;
321 (node_max, node_count, edge_count)
322 });
323debug!("position: {:?}", d.position());
324325debug!(?node_count, ?edge_count);
326327let graph_bytes = d.len() - (3 * IntEncodedWithFixedSize::ENCODED_SIZE) - d.position();
328329let mut nodes = IndexVec::from_elem_n(
330 DepNode {
331 kind: DepKind::Null,
332 key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
333 },
334 node_max,
335 );
336let mut value_fingerprints = IndexVec::from_elem_n(Fingerprint::ZERO, node_max);
337let mut edge_list_indices =
338 IndexVec::from_elem_n(EdgeHeader { repr: 0, num_edges: 0 }, node_max);
339340// This estimation assumes that all of the encoded bytes are for the edge lists or for the
341 // fixed-size node headers. But that's not necessarily true; if any edge list has a length
342 // that spills out of the size we can bit-pack into SerializedNodeHeader then some of the
343 // total serialized size is also used by leb128-encoded edge list lengths. Neglecting that
344 // contribution to graph_bytes means our estimation of the bytes needed for edge_list_data
345 // slightly overshoots. But it cannot overshoot by much; consider that the worse case is
346 // for a node with length 64, which means the spilled 1-byte leb128 length is 1 byte of at
347 // least (34 byte header + 1 byte len + 64 bytes edge data), which is ~1%. A 2-byte leb128
348 // length is about the same fractional overhead and it amortizes for yet greater lengths.
349let mut edge_list_data =
350 Vec::with_capacity(graph_bytes - node_count * size_of::<SerializedNodeHeader>());
351352for _ in 0..node_count {
353// Decode the header for this edge; the header packs together as many of the fixed-size
354 // fields as possible to limit the number of times we update decoder state.
355let node_header = SerializedNodeHeader { bytes: d.read_array() };
356357let index = node_header.index();
358359let node = &mut nodes[index];
360// Make sure there's no duplicate indices in the dep graph.
361assert!(node_header.node().kind != DepKind::Null && node.kind == DepKind::Null);
362*node = node_header.node();
363364 value_fingerprints[index] = node_header.value_fingerprint();
365366// If the length of this node's edge list is small, the length is stored in the header.
367 // If it is not, we fall back to another decoder call.
368let num_edges = node_header.len().unwrap_or_else(|| d.read_u32());
369370// The edges index list uses the same varint strategy as rmeta tables; we select the
371 // number of byte elements per-array not per-element. This lets us read the whole edge
372 // list for a node with one decoder call and also use the on-disk format in memory.
373let edges_len_bytes = node_header.bytes_per_index() * (num_edges as usize);
374// The in-memory structure for the edges list stores the byte width of the edges on
375 // this node with the offset into the global edge data array.
376let edges_header = node_header.edges_header(&edge_list_data, num_edges);
377378 edge_list_data.extend(d.read_raw_bytes(edges_len_bytes));
379380 edge_list_indices[index] = edges_header;
381 }
382383// When we access the edge list data, we do a fixed-size read from the edge list data then
384 // mask off the bytes that aren't for that edge index, so the last read may dangle off the
385 // end of the array. This padding ensure it doesn't.
386edge_list_data.extend(&[0u8; DEP_NODE_PAD]);
387388// Read the number of nodes of each dep kind, and perform
389 // counting sort for `LazyNodeIndex`.
390let mut kinds = Vec::with_capacity(DepKind::MAX as usize + 1);
391let mut offset = 0u32;
392for _ in 0..(DepKind::MAX + 1) {
393let len = d.read_u32();
394 kinds.push(LazyKindIndex { start: offset, len, map: OnceLock::new() });
395 offset += len;
396 }
397debug_assert_eq!(offset as usize, node_count);
398399let session_count = d.read_u64();
400401// Counting sort: place each node index into its kind's range. `fill[k]`
402 // points at the next free slot in kind `k`'s range, so a kind's nodes end
403 // up contiguous. Slots start as `None` and are each filled exactly once
404 // (the counts sum to the number of non-`Null` nodes).
405let mut nodes_by_kind = vec![None; node_count];
406let mut fill: Vec<u32> = kinds.iter().map(|k| k.start).collect();
407for (idx, node) in nodes.iter_enumerated() {
408// Unused indices from batch allocation stay `Null`; they carry no
409 // encoded node and are never looked up by fingerprint, so skip them.
410if node.kind == DepKind::Null {
411continue;
412 }
413let k = node.kind.as_usize();
414 nodes_by_kind[fill[k] as usize] = Some(idx);
415 fill[k] += 1;
416 }
417// Each kind's range was filled exactly to its end.
418debug_assert!(kinds.iter().zip(&fill).all(|(k, &f)| f == k.start + k.len));
419let reverse_index = LazyNodeIndex { nodes_by_kind, kinds };
420421 Arc::new(SerializedDepGraph {
422 nodes,
423 value_fingerprints,
424 edge_list_indices,
425 edge_list_data,
426 reverse_index,
427 live_node_count: node_count,
428 session_count,
429 profiler: Some(profiler.clone()),
430 })
431 }
432}
433434/// A packed representation of all the fixed-size fields in a `NodeInfo`.
435///
436/// This stores in one byte array:
437/// * The value `Fingerprint` in the `NodeInfo`
438/// * The key `Fingerprint` in `DepNode` that is in this `NodeInfo`
439/// * The `DepKind`'s discriminant (a u16, but not all bits are used...)
440/// * The byte width of the encoded edges for this node
441/// * In whatever bits remain, the length of the edge list for this node, if it fits
442struct SerializedNodeHeader {
443// 2 bytes for the DepNode
444 // 4 bytes for the index
445 // 16 for Fingerprint in DepNode
446 // 16 for Fingerprint in NodeInfo
447bytes: [u8; 38],
448}
449450// The fields of a `SerializedNodeHeader`, this struct is an implementation detail and exists only
451// to make the implementation of `SerializedNodeHeader` simpler.
452struct Unpacked {
453 len: Option<u32>,
454 bytes_per_index: usize,
455 kind: DepKind,
456 index: SerializedDepNodeIndex,
457 key_fingerprint: PackedFingerprint,
458 value_fingerprint: Fingerprint,
459}
460461// Bit fields, where
462// M: bits used to store the length of a node's edge list
463// N: bits used to store the byte width of elements of the edge list
464// are
465// 0..M length of the edge
466// M..M+N bytes per index
467// M+N..16 kind
468impl SerializedNodeHeader {
469const TOTAL_BITS: usize = size_of::<DepKind>() * 8;
470const LEN_BITS: usize = Self::TOTAL_BITS - Self::KIND_BITS - Self::WIDTH_BITS;
471const WIDTH_BITS: usize = DEP_NODE_WIDTH_BITS;
472const KIND_BITS: usize = Self::TOTAL_BITS - DepKind::MAX.leading_zeros() as usize;
473const MAX_INLINE_LEN: usize = (u16::MAXas usize >> (Self::TOTAL_BITS - Self::LEN_BITS)) - 1;
474475#[inline]
476fn new(
477 node: &DepNode,
478 index: DepNodeIndex,
479 value_fingerprint: Fingerprint,
480 edge_max_index: u32,
481 edge_count: usize,
482 ) -> Self {
483if 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);
484485let mut head = node.kind.as_u16();
486487let free_bytes = edge_max_index.leading_zeros() as usize / 8;
488let bytes_per_index = (DEP_NODE_SIZE - free_bytes).saturating_sub(1);
489head |= (bytes_per_indexas u16) << Self::KIND_BITS;
490491// Encode number of edges + 1 so that we can reserve 0 to indicate that the len doesn't fit
492 // in this bitfield.
493if edge_count <= Self::MAX_INLINE_LEN {
494head |= (edge_countas u16 + 1) << (Self::KIND_BITS + Self::WIDTH_BITS);
495 }
496497let hash: Fingerprint = node.key_fingerprint.into();
498499// Using half-open ranges ensures an unconditional panic if we get the magic numbers wrong.
500let mut bytes = [0u8; 38];
501bytes[..2].copy_from_slice(&head.to_le_bytes());
502bytes[2..6].copy_from_slice(&index.as_u32().to_le_bytes());
503bytes[6..22].copy_from_slice(&hash.to_le_bytes());
504bytes[22..].copy_from_slice(&value_fingerprint.to_le_bytes());
505506#[cfg(debug_assertions)]
507{
508let res = Self { bytes };
509{
match (&value_fingerprint, &res.value_fingerprint()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(value_fingerprint, res.value_fingerprint());
510{
match (&*node, &res.node()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(*node, res.node());
511if let Some(len) = res.len() {
512{
match (&edge_count, &(len as usize)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(edge_count, len as usize);
513 }
514 }
515Self { bytes }
516 }
517518#[inline]
519fn unpack(&self) -> Unpacked {
520let head = u16::from_le_bytes(self.bytes[..2].try_into().unwrap());
521let index = u32::from_le_bytes(self.bytes[2..6].try_into().unwrap());
522let key_fingerprint = self.bytes[6..22].try_into().unwrap();
523let value_fingerprint = self.bytes[22..].try_into().unwrap();
524525let kind = head & mask(Self::KIND_BITS) as u16;
526let bytes_per_index = (head >> Self::KIND_BITS) & mask(Self::WIDTH_BITS) as u16;
527let len = (headas u32) >> (Self::WIDTH_BITS + Self::KIND_BITS);
528529Unpacked {
530 len: len.checked_sub(1),
531 bytes_per_index: bytes_per_indexas usize + 1,
532 kind: DepKind::from_u16(kind),
533 index: SerializedDepNodeIndex::from_u32(index),
534 key_fingerprint: Fingerprint::from_le_bytes(key_fingerprint).into(),
535 value_fingerprint: Fingerprint::from_le_bytes(value_fingerprint),
536 }
537 }
538539#[inline]
540fn len(&self) -> Option<u32> {
541self.unpack().len
542 }
543544#[inline]
545fn bytes_per_index(&self) -> usize {
546self.unpack().bytes_per_index
547 }
548549#[inline]
550fn index(&self) -> SerializedDepNodeIndex {
551self.unpack().index
552 }
553554#[inline]
555fn value_fingerprint(&self) -> Fingerprint {
556self.unpack().value_fingerprint
557 }
558559#[inline]
560fn node(&self) -> DepNode {
561let Unpacked { kind, key_fingerprint, .. } = self.unpack();
562DepNode { kind, key_fingerprint }
563 }
564565#[inline]
566fn edges_header(&self, edge_list_data: &[u8], num_edges: u32) -> EdgeHeader {
567EdgeHeader {
568 repr: (edge_list_data.len() << DEP_NODE_WIDTH_BITS) | (self.bytes_per_index() - 1),
569num_edges,
570 }
571 }
572}
573574#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for NodeInfo<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "NodeInfo",
"node", &self.node, "value_fingerprint", &self.value_fingerprint,
"edges", &&self.edges)
}
}Debug)]
575struct NodeInfo<'a> {
576 node: DepNode,
577 value_fingerprint: Fingerprint,
578 edges: &'a [DepNodeIndex],
579}
580581impl NodeInfo<'_> {
582fn encode(&self, e: &mut MemEncoder, index: DepNodeIndex) {
583let NodeInfo { ref node, value_fingerprint, edges } = *self;
584// The largest index picks the byte width of the edge list.
585let edge_max = edges.iter().map(|e| e.as_u32()).max().unwrap_or(0);
586let header =
587SerializedNodeHeader::new(node, index, value_fingerprint, edge_max, edges.len());
588e.write_array(header.bytes);
589590if header.len().is_none() {
591// The edges are all unique and the number of unique indices is less than u32::MAX.
592e.emit_u32(edges.len().try_into().unwrap());
593 }
594595let bytes_per_index = header.bytes_per_index();
596for node_index in edges.iter() {
597 e.write_with(|dest| {
598*dest = node_index.as_u32().to_le_bytes();
599 bytes_per_index
600 });
601 }
602 }
603}
604605struct Stat {
606 kind: DepKind,
607 node_counter: u64,
608 edge_counter: u64,
609}
610611struct LocalEncoderState {
612 next_node_index: u32,
613 remaining_node_index: u32,
614 encoder: MemEncoder,
615 node_count: usize,
616 edge_count: usize,
617618/// Stores the number of times we've encoded each dep kind.
619kind_stats: Vec<u32>,
620}
621622struct LocalEncoderResult {
623 node_max: u32,
624 node_count: usize,
625 edge_count: usize,
626627/// Stores the number of times we've encoded each dep kind.
628kind_stats: Vec<u32>,
629}
630631struct EncoderState {
632 next_node_index: AtomicU64,
633 previous: Arc<SerializedDepGraph>,
634 file: Lock<Option<FileEncoder<'static>>>,
635 local: WorkerLocal<RefCell<LocalEncoderState>>,
636 stats: Option<Lock<FxHashMap<DepKind, Stat>>>,
637}
638639impl EncoderState {
640fn new(
641 encoder: FileEncoder<'static>,
642 record_stats: bool,
643 previous: Arc<SerializedDepGraph>,
644 ) -> Self {
645Self {
646previous,
647 next_node_index: AtomicU64::new(0),
648 stats: record_stats.then(|| Lock::new(FxHashMap::default())),
649 file: Lock::new(Some(encoder)),
650 local: WorkerLocal::new(|_| {
651RefCell::new(LocalEncoderState {
652 next_node_index: 0,
653 remaining_node_index: 0,
654 edge_count: 0,
655 node_count: 0,
656 encoder: MemEncoder::new(),
657 kind_stats: iter::repeat_n(0, DepKind::MAXas usize + 1).collect(),
658 })
659 }),
660 }
661 }
662663#[inline]
664fn next_index(&self, local: &mut LocalEncoderState) -> DepNodeIndex {
665if local.remaining_node_index == 0 {
666const COUNT: u32 = 256;
667668// We assume that there won't be enough active threads to overflow `u64` from `u32::MAX` here.
669 // This can exceed u32::MAX by at most `N` * `COUNT` where `N` is the thread pool count since
670 // `try_into().unwrap()` will make threads panic when `self.next_node_index` exceeds u32::MAX.
671local.next_node_index =
672self.next_node_index.fetch_add(COUNTas u64, Ordering::Relaxed).try_into().unwrap();
673674// Check that we'll stay within `u32`
675local.next_node_index.checked_add(COUNT).unwrap();
676677local.remaining_node_index = COUNT;
678 }
679680DepNodeIndex::from_u32(local.next_node_index)
681 }
682683/// Marks the index previously returned by `next_index` as used.
684#[inline]
685fn bump_index(&self, local: &mut LocalEncoderState) {
686local.remaining_node_index -= 1;
687local.next_node_index += 1;
688local.node_count += 1;
689 }
690691#[inline]
692fn record(
693&self,
694 node: &DepNode,
695 index: DepNodeIndex,
696 edge_count: usize,
697 edges: &[DepNodeIndex],
698 retained_graph: &Option<Lock<RetainedDepGraph>>,
699 local: &mut LocalEncoderState,
700 ) {
701local.kind_stats[node.kind.as_usize()] += 1;
702local.edge_count += edge_count;
703704if let Some(retained_graph) = &retained_graph {
705// Outline the build of the full dep graph as it's typically disabled and cold.
706outline(move || {
707// Block on the lock rather than using `try_lock`: under the parallel frontend
708 // several threads record nodes concurrently, and dropping a node on lock
709 // contention would make the retained graph nondeterministic. Readers take a
710 // clone of the graph (`retained_dep_graph`) rather than holding the lock, so
711 // this never deadlocks against a reentrant `record`.
712retained_graph.lock().push(index, *node, edges);
713 });
714 }
715716if let Some(stats) = &self.stats {
717let kind = node.kind;
718719// Outline the stats code as it's typically disabled and cold.
720outline(move || {
721let mut stats = stats.lock();
722let stat =
723stats.entry(kind).or_insert(Stat { kind, node_counter: 0, edge_counter: 0 });
724stat.node_counter += 1;
725stat.edge_counter += edge_countas u64;
726 });
727 }
728 }
729730#[inline]
731fn flush_mem_encoder(&self, local: &mut LocalEncoderState) {
732let data = &mut local.encoder.data;
733if data.len() > 64 * 1024 {
734self.file.lock().as_mut().unwrap().emit_raw_bytes(&data[..]);
735data.clear();
736 }
737 }
738739/// Encodes a node to the current graph.
740fn encode_node(
741&self,
742 index: DepNodeIndex,
743 node: &NodeInfo<'_>,
744 retained_graph: &Option<Lock<RetainedDepGraph>>,
745 local: &mut LocalEncoderState,
746 ) {
747node.encode(&mut local.encoder, index);
748self.flush_mem_encoder(&mut *local);
749self.record(&node.node, index, node.edges.len(), node.edges, retained_graph, &mut *local);
750 }
751752/// Encodes a node that was promoted from the previous graph, reading the node and its
753 /// fingerprint directly from the previous dep graph. It expects all edges to already
754 /// have a new dep node index assigned.
755#[inline]
756fn encode_promoted_node(
757&self,
758 index: DepNodeIndex,
759 prev_index: SerializedDepNodeIndex,
760 retained_graph: &Option<Lock<RetainedDepGraph>>,
761 local: &mut LocalEncoderState,
762 edges: &[DepNodeIndex],
763 ) {
764let node = NodeInfo {
765 node: *self.previous.index_to_node(prev_index),
766 value_fingerprint: self.previous.value_fingerprint_for_index(prev_index),
767edges,
768 };
769self.encode_node(index, &node, retained_graph, local);
770 }
771772fn finish(&self, profiler: &SelfProfilerRef, current: &CurrentDepGraph) -> FileEncodeResult {
773// Prevent more indices from being allocated.
774self.next_node_index.store(u32::MAXas u64 + 1, Ordering::SeqCst);
775776let results = broadcast(|_| {
777let mut local = self.local.borrow_mut();
778779// Prevent more indices from being allocated on this thread.
780local.remaining_node_index = 0;
781782let data = mem::take(&mut local.encoder.data);
783self.file.lock().as_mut().unwrap().emit_raw_bytes(&data);
784785LocalEncoderResult {
786 kind_stats: local.kind_stats.clone(),
787 node_max: local.next_node_index,
788 node_count: local.node_count,
789 edge_count: local.edge_count,
790 }
791 });
792793let mut encoder = self.file.lock().take().unwrap();
794795let mut kind_stats: Vec<u32> = iter::repeat_n(0, DepKind::MAXas usize + 1).collect();
796797let mut node_max = 0;
798let mut node_count = 0;
799let mut edge_count = 0;
800801for result in results {
802 node_max = max(node_max, result.node_max);
803 node_count += result.node_count;
804 edge_count += result.edge_count;
805for (i, stat) in result.kind_stats.iter().enumerate() {
806 kind_stats[i] += stat;
807 }
808 }
809810// Encode the number of each dep kind encountered
811for count in kind_stats.iter() {
812 count.encode(&mut encoder);
813 }
814815self.previous.session_count.checked_add(1).unwrap().encode(&mut encoder);
816817{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/serialized.rs:817",
"rustc_middle::dep_graph::serialized",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
::tracing_core::__macro_support::Option::Some(817u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("node_max")
}> =
::tracing::__macro_support::FieldName::new("node_max");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("node_count")
}> =
::tracing::__macro_support::FieldName::new("node_count");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("edge_count")
}> =
::tracing::__macro_support::FieldName::new("edge_count");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_max)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_count)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&edge_count)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?node_max, ?node_count, ?edge_count);
818{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/serialized.rs:818",
"rustc_middle::dep_graph::serialized",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
::tracing_core::__macro_support::Option::Some(818u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
encoder.position()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("position: {:?}", encoder.position());
819IntEncodedWithFixedSize(node_max.try_into().unwrap()).encode(&mut encoder);
820IntEncodedWithFixedSize(node_count.try_into().unwrap()).encode(&mut encoder);
821IntEncodedWithFixedSize(edge_count.try_into().unwrap()).encode(&mut encoder);
822{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/serialized.rs:822",
"rustc_middle::dep_graph::serialized",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/serialized.rs"),
::tracing_core::__macro_support::Option::Some(822u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
encoder.position()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("position: {:?}", encoder.position());
823// Drop the encoder so that nothing is written after the counts.
824let result = encoder.finish();
825if let Ok(position) = result {
826// FIXME(rylev): we hardcode the dep graph file name so we
827 // don't need a dependency on rustc_incremental just for that.
828profiler.artifact_size("dep_graph", "dep-graph.bin", positionas u64);
829 }
830831self.print_incremental_info(current, node_count, edge_count);
832833result834 }
835836fn print_incremental_info(
837&self,
838 current: &CurrentDepGraph,
839 total_node_count: usize,
840 total_edge_count: usize,
841 ) {
842if let Some(record_stats) = &self.stats {
843let record_stats = record_stats.lock();
844// `stats` is sorted below so we can allow this lint here.
845#[allow(rustc::potential_query_instability)]
846let mut stats: Vec<_> = record_stats.values().collect();
847stats.sort_by_key(|s| -(s.node_counter as i64));
848849const SEPARATOR: &str = "[incremental] --------------------------------\
850 ----------------------------------------------\
851 ------------";
852853{ ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
854{ ::std::io::_eprint(format_args!("[incremental] DepGraph Statistics\n")); };eprintln!("[incremental] DepGraph Statistics");
855{ ::std::io::_eprint(format_args!("{0}\n", SEPARATOR)); };eprintln!("{SEPARATOR}");
856{ ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
857{
::std::io::_eprint(format_args!("[incremental] Total Node Count: {0}\n",
total_node_count));
};eprintln!("[incremental] Total Node Count: {}", total_node_count);
858{
::std::io::_eprint(format_args!("[incremental] Total Edge Count: {0}\n",
total_edge_count));
};eprintln!("[incremental] Total Edge Count: {}", total_edge_count);
859860if truecfg!(debug_assertions) {
861let total_read_count = current.total_read_count.load(Ordering::Relaxed);
862let total_duplicate_read_count =
863current.total_duplicate_read_count.load(Ordering::Relaxed);
864{
::std::io::_eprint(format_args!("[incremental] Total Edge Reads: {0}\n",
total_read_count));
};eprintln!("[incremental] Total Edge Reads: {total_read_count}");
865{
::std::io::_eprint(format_args!("[incremental] Total Duplicate Edge Reads: {0}\n",
total_duplicate_read_count));
};eprintln!("[incremental] Total Duplicate Edge Reads: {total_duplicate_read_count}");
866 }
867868{ ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
869{
::std::io::_eprint(format_args!("[incremental] {0:<36}| {1:<17}| {2:<12}| {3:<17}|\n",
"Node Kind", "Node Frequency", "Node Count", "Avg. Edge Count"));
};eprintln!(
870"[incremental] {:<36}| {:<17}| {:<12}| {:<17}|",
871"Node Kind", "Node Frequency", "Node Count", "Avg. Edge Count"
872);
873{ ::std::io::_eprint(format_args!("{0}\n", SEPARATOR)); };eprintln!("{SEPARATOR}");
874875for stat in stats {
876let node_kind_ratio =
877 (100.0 * (stat.node_counter as f64)) / (total_node_count as f64);
878let node_kind_avg_edges = (stat.edge_counter as f64) / (stat.node_counter as f64);
879880{
::std::io::_eprint(format_args!("[incremental] {0:<36}|{1:>16.1}% |{2:>12} |{3:>17.1} |\n",
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", stat.kind))
}), node_kind_ratio, stat.node_counter, node_kind_avg_edges));
};eprintln!(
881"[incremental] {:<36}|{:>16.1}% |{:>12} |{:>17.1} |",
882format!("{:?}", stat.kind),
883 node_kind_ratio,
884 stat.node_counter,
885 node_kind_avg_edges,
886 );
887 }
888889{ ::std::io::_eprint(format_args!("{0}\n", SEPARATOR)); };eprintln!("{SEPARATOR}");
890{ ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
891 }
892 }
893}
894895pub(crate) struct GraphEncoder {
896 profiler: SelfProfilerRef,
897 status: EncoderState,
898/// In-memory copy of the dep graph; only present if `-Zquery-dep-graph` is set.
899retained_graph: Option<Lock<RetainedDepGraph>>,
900}
901902impl GraphEncoder {
903pub(crate) fn new(
904 sess: &Session,
905 encoder: FileEncoder<'static>,
906 prev_index_space_len: usize,
907 previous: Arc<SerializedDepGraph>,
908 ) -> Self {
909let retained_graph = sess910 .opts
911 .unstable_opts
912 .query_dep_graph
913 .then(|| Lock::new(RetainedDepGraph::new(prev_index_space_len)));
914let status = EncoderState::new(encoder, sess.opts.unstable_opts.incremental_info, previous);
915GraphEncoder { status, retained_graph, profiler: sess.prof.clone() }
916 }
917918pub(crate) fn retained_dep_graph(&self) -> Option<RetainedDepGraph> {
919self.retained_graph.as_ref().map(|retained_graph| retained_graph.lock().clone())
920 }
921922/// Encodes a node that does not exists in the previous graph.
923pub(crate) fn send_new(
924&self,
925 node: DepNode,
926 value_fingerprint: Fingerprint,
927 edges: &[DepNodeIndex],
928 ) -> DepNodeIndex {
929let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
930let node = NodeInfo { node, value_fingerprint, edges };
931let mut local = self.status.local.borrow_mut();
932let index = self.status.next_index(&mut *local);
933self.status.bump_index(&mut *local);
934self.status.encode_node(index, &node, &self.retained_graph, &mut *local);
935index936 }
937938/// Encodes a node that exists in the previous graph, but was re-executed.
939 ///
940 /// This will also ensure the dep node is colored either red or green.
941pub(crate) fn send_and_color(
942&self,
943 prev_index: SerializedDepNodeIndex,
944 colors: &DepNodeColorMap,
945 node: DepNode,
946 value_fingerprint: Fingerprint,
947 edges: &[DepNodeIndex],
948 is_green: bool,
949 ) -> DepNodeIndex {
950let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
951let node = NodeInfo { node, value_fingerprint, edges };
952953let mut local = self.status.local.borrow_mut();
954955let index = self.status.next_index(&mut *local);
956let color = if is_green { DesiredColor::Green { index } } else { DesiredColor::Red };
957958// Use `try_set_color` to avoid racing when `send_promoted` is called concurrently
959 // on the same index.
960match colors.try_set_color(prev_index, color) {
961 TrySetColorResult::Success => {}
962 TrySetColorResult::AlreadyRed => {
::core::panicking::panic_fmt(format_args!("dep node {0:?} is unexpectedly red",
prev_index));
}panic!("dep node {prev_index:?} is unexpectedly red"),
963 TrySetColorResult::AlreadyGreen { index } => return index,
964 }
965966self.status.bump_index(&mut *local);
967self.status.encode_node(index, &node, &self.retained_graph, &mut *local);
968index969 }
970971/// Encodes a node that was promoted from the previous graph. It reads the information directly
972 /// from the previous dep graph and expects all edges to already have a new dep node index
973 /// assigned.
974 ///
975 /// Tries to mark the dep node green, and returns Some if it is now green,
976 /// or None if had already been concurrently marked red.
977#[inline]
978pub(crate) fn send_promoted(
979&self,
980 prev_index: SerializedDepNodeIndex,
981 colors: &DepNodeColorMap,
982 edges: &[DepNodeIndex],
983 ) -> Option<DepNodeIndex> {
984let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
985986let mut local = self.status.local.borrow_mut();
987let index = self.status.next_index(&mut *local);
988989// Use `try_set_color` to avoid racing when `send_promoted` or `send_and_color`
990 // is called concurrently on the same index.
991match colors.try_set_color(prev_index, DesiredColor::Green { index }) {
992 TrySetColorResult::Success => {
993self.status.bump_index(&mut *local);
994self.status.encode_promoted_node(
995index,
996prev_index,
997&self.retained_graph,
998&mut *local,
999edges,
1000 );
1001Some(index)
1002 }
1003 TrySetColorResult::AlreadyRed => None,
1004 TrySetColorResult::AlreadyGreen { index } => Some(index),
1005 }
1006 }
10071008pub(crate) fn finish(&self, current: &CurrentDepGraph) -> FileEncodeResult {
1009let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph_finish");
10101011self.status.finish(&self.profiler, current)
1012 }
1013}