1//! The data that we will serialize and deserialize.
2//!
3//! Notionally, the dep-graph is a sequence of NodeInfo with the dependencies
4//! specified inline. The total number of nodes and edges are stored as the last
5//! 16 bytes of the file, so we can find them easily at decoding time.
6//!
7//! The serialisation is performed on-demand when each node is emitted. Using this
8//! scheme, we do not need to keep the current graph in memory.
9//!
10//! The deserialization is performed manually, in order to convert from the stored
11//! sequence of NodeInfos to the different arrays in SerializedDepGraph. Since the
12//! node and edge count are stored at the end of the file, all the arrays can be
13//! pre-allocated with the right length.
14//!
15//! The encoding of the dep-graph is generally designed around the fact that fixed-size
16//! reads of encoded data are generally faster than variable-sized reads. Ergo we adopt
17//! essentially the same varint encoding scheme used in the rmeta format; the edge lists
18//! for each node on the graph store a 2-bit integer which is the number of bytes per edge
19//! index in that node's edge list. We effectively ignore that an edge index of 0 could be
20//! encoded with 0 bytes in order to not require 3 bits to store the byte width of the edges.
21//! The overhead of calculating the correct byte width for each edge is mitigated by
22//! building edge lists with [`EdgesVec`] which keeps a running max of the edges in a node.
23//!
24//! When we decode this data, we do not immediately create [`SerializedDepNodeIndex`] and
25//! instead keep the data in its denser serialized form which lets us turn our on-disk size
26//! efficiency directly into a peak memory reduction. When we convert these encoded-in-memory
27//! values into their fully-deserialized type, we use a fixed-size read of the encoded array
28//! then mask off any errant bytes we read. The array of edge index bytes is padded to permit this.
29//!
30//! We also encode and decode the entire rest of each node using [`SerializedNodeHeader`]
31//! to let this encoding and decoding be done in one fixed-size operation. These headers contain
32//! two [`Fingerprint`]s along with the serialized [`DepKind`], and the number of edge indices
33//! in the node and the number of bytes used to encode the edge indices for this node. The
34//! [`DepKind`], number of edges, and bytes per edge are all bit-packed together, if they fit.
35//! If the number of edges in this node does not fit in the bits available in the header, we
36//! store it directly after the header with leb128.
37//!
38//! Dep-graph indices are bulk allocated to threads inside `LocalEncoderState`. Having threads
39//! own these indices helps avoid races when they are conditionally used when marking nodes green.
40//! It also reduces congestion on the shared index count.
4142use std::cell::RefCell;
43use std::cmp::max;
44use std::sync::Arc;
45use std::sync::atomic::Ordering;
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::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};
64use crate::dep_graph::edges::EdgesVec;
6566// The maximum value of `SerializedDepNodeIndex` leaves the upper two bits
67// unused so that we can store multiple index types in `CompressedHybridIndex`,
68// and use those bits to encode which index type it contains.
69impl ::std::fmt::Debug for SerializedDepNodeIndex {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("{0}", self.as_u32()))
}
}rustc_index::newtype_index! {
70#[encodable]
71 #[max = 0x7FFF_FFFF]
72pub struct SerializedDepNodeIndex {}
73}7475impl SerializedDepNodeIndex {
76/// Converts a current-session dep node index to a "serialized" index,
77 /// for the purpose of serializing data to be loaded by future sessions.
78#[inline(always)]
79pub fn from_curr_for_serialization(index: DepNodeIndex) -> Self {
80SerializedDepNodeIndex::from_u32(index.as_u32())
81 }
82}
8384const DEP_NODE_SIZE: usize = size_of::<SerializedDepNodeIndex>();
85/// Amount of padding we need to add to the edge list data so that we can retrieve every
86/// SerializedDepNodeIndex with a fixed-size read then mask.
87const DEP_NODE_PAD: usize = DEP_NODE_SIZE - 1;
88/// Number of bits we need to store the number of used bytes in a SerializedDepNodeIndex.
89/// Note that wherever we encode byte widths like this we actually store the number of bytes used
90/// minus 1; for a 4-byte value we technically would have 5 widths to store, but using one byte to
91/// store zeroes (which are relatively rare) is a decent tradeoff to save a bit in our bitfields.
92const DEP_NODE_WIDTH_BITS: usize = DEP_NODE_SIZE / 2;
9394/// Data for use when recompiling the **current crate**.
95///
96/// There may be unused indices with DepKind::Null in this graph due to batch allocation of
97/// indices to threads.
98#[derive(#[automatically_derived]
impl ::core::fmt::Debug for SerializedDepGraph {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["nodes", "value_fingerprints", "edge_list_indices",
"edge_list_data", "index", "session_count"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.nodes, &self.value_fingerprints, &self.edge_list_indices,
&self.edge_list_data, &self.index, &&self.session_count];
::core::fmt::Formatter::debug_struct_fields_finish(f,
"SerializedDepGraph", names, values)
}
}Debug, #[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(),
index: ::core::default::Default::default(),
session_count: ::core::default::Default::default(),
}
}
}Default)]
99pub struct SerializedDepGraph {
100/// The set of all DepNodes in the graph
101nodes: IndexVec<SerializedDepNodeIndex, DepNode>,
102/// A value fingerprint associated with each [`DepNode`] in [`Self::nodes`],
103 /// typically a hash of the value returned by the node's query in the
104 /// previous incremental-compilation session.
105 ///
106 /// Some nodes don't have a meaningful value hash (e.g. queries with `no_hash`),
107 /// so they store a dummy value here instead (e.g. [`Fingerprint::ZERO`]).
108value_fingerprints: IndexVec<SerializedDepNodeIndex, Fingerprint>,
109/// For each DepNode, stores the list of edges originating from that
110 /// DepNode. Encoded as a [start, end) pair indexing into edge_list_data,
111 /// which holds the actual DepNodeIndices of the target nodes.
112edge_list_indices: IndexVec<SerializedDepNodeIndex, EdgeHeader>,
113/// A flattened list of all edge targets in the graph, stored in the same
114 /// varint encoding that we use on disk. Edge sources are implicit in edge_list_indices.
115edge_list_data: Vec<u8>,
116/// For each dep kind, stores a map from key fingerprints back to the index
117 /// of the corresponding node. This is the inverse of `nodes`.
118index: Vec<UnhashMap<PackedFingerprint, SerializedDepNodeIndex>>,
119/// The number of previous compilation sessions. This is used to generate
120 /// unique anon dep nodes per session.
121session_count: u64,
122}
123124impl SerializedDepGraph {
125#[inline]
126pub fn edge_targets_from(
127&self,
128 source: SerializedDepNodeIndex,
129 ) -> impl Iterator<Item = SerializedDepNodeIndex> + Clone {
130let header = self.edge_list_indices[source];
131let mut raw = &self.edge_list_data[header.start()..];
132133let bytes_per_index = header.bytes_per_index();
134135// LLVM doesn't hoist EdgeHeader::mask so we do it ourselves.
136let mask = header.mask();
137 (0..header.num_edges).map(move |_| {
138// Doing this slicing in this order ensures that the first bounds check suffices for
139 // all the others.
140let index = &raw[..DEP_NODE_SIZE];
141raw = &raw[bytes_per_index..];
142let index = u32::from_le_bytes(index.try_into().unwrap()) & mask;
143SerializedDepNodeIndex::from_u32(index)
144 })
145 }
146147#[inline]
148pub fn index_to_node(&self, dep_node_index: SerializedDepNodeIndex) -> &DepNode {
149&self.nodes[dep_node_index]
150 }
151152#[inline]
153pub fn node_to_index_opt(&self, dep_node: &DepNode) -> Option<SerializedDepNodeIndex> {
154self.index.get(dep_node.kind.as_usize())?.get(&dep_node.key_fingerprint).copied()
155 }
156157#[inline]
158pub fn value_fingerprint_for_index(
159&self,
160 dep_node_index: SerializedDepNodeIndex,
161 ) -> Fingerprint {
162self.value_fingerprints[dep_node_index]
163 }
164165#[inline]
166pub fn node_count(&self) -> usize {
167self.nodes.len()
168 }
169170#[inline]
171pub fn session_count(&self) -> u64 {
172self.session_count
173 }
174}
175176/// A packed representation of an edge's start index and byte width.
177///
178/// This is packed by stealing 2 bits from the start index, which means we only accommodate edge
179/// data arrays up to a quarter of our address space. Which seems fine.
180#[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)]
181struct EdgeHeader {
182 repr: usize,
183 num_edges: u32,
184}
185186impl EdgeHeader {
187#[inline]
188fn start(self) -> usize {
189self.repr >> DEP_NODE_WIDTH_BITS190 }
191192#[inline]
193fn bytes_per_index(self) -> usize {
194 (self.repr & mask(DEP_NODE_WIDTH_BITS)) + 1
195}
196197#[inline]
198fn mask(self) -> u32 {
199mask(self.bytes_per_index() * 8) as u32200 }
201}
202203#[inline]
204fn mask(bits: usize) -> usize {
205usize::MAX >> ((size_of::<usize>() * 8) - bits)
206}
207208impl SerializedDepGraph {
209#[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(209u32),
::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:212",
"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(212u32),
::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:218",
"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(218u32),
::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:224",
"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(224u32),
::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:226",
"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(226u32),
::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 index: Vec<_> =
(0..(DepKind::MAX +
1)).map(|_|
UnhashMap::with_capacity_and_hasher(d.read_u32() as usize,
Default::default())).collect();
let session_count = d.read_u64();
for (idx, node) in nodes.iter_enumerated() {
if index[node.kind.as_usize()].insert(node.key_fingerprint,
idx).is_some() {
if node.kind != DepKind::Null &&
node.kind != DepKind::SideEffect {
let kind = node.kind;
{
::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));
}
}
}
}
Arc::new(SerializedDepGraph {
nodes,
value_fingerprints,
edge_list_indices,
edge_list_data,
index,
session_count,
})
}
}
}#[instrument(level = "debug", skip(d))]210pub fn decode(d: &mut MemDecoder<'_>) -> Arc<SerializedDepGraph> {
211// The last 16 bytes are the node count and edge count.
212debug!("position: {:?}", d.position());
213214// `node_max` is the number of indices including empty nodes while `node_count`
215 // is the number of actually encoded nodes.
216let (node_max, node_count, edge_count) =
217 d.with_position(d.len() - 3 * IntEncodedWithFixedSize::ENCODED_SIZE, |d| {
218debug!("position: {:?}", d.position());
219let node_max = IntEncodedWithFixedSize::decode(d).0 as usize;
220let node_count = IntEncodedWithFixedSize::decode(d).0 as usize;
221let edge_count = IntEncodedWithFixedSize::decode(d).0 as usize;
222 (node_max, node_count, edge_count)
223 });
224debug!("position: {:?}", d.position());
225226debug!(?node_count, ?edge_count);
227228let graph_bytes = d.len() - (3 * IntEncodedWithFixedSize::ENCODED_SIZE) - d.position();
229230let mut nodes = IndexVec::from_elem_n(
231 DepNode {
232 kind: DepKind::Null,
233 key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
234 },
235 node_max,
236 );
237let mut value_fingerprints = IndexVec::from_elem_n(Fingerprint::ZERO, node_max);
238let mut edge_list_indices =
239 IndexVec::from_elem_n(EdgeHeader { repr: 0, num_edges: 0 }, node_max);
240241// This estimation assumes that all of the encoded bytes are for the edge lists or for the
242 // fixed-size node headers. But that's not necessarily true; if any edge list has a length
243 // that spills out of the size we can bit-pack into SerializedNodeHeader then some of the
244 // total serialized size is also used by leb128-encoded edge list lengths. Neglecting that
245 // contribution to graph_bytes means our estimation of the bytes needed for edge_list_data
246 // slightly overshoots. But it cannot overshoot by much; consider that the worse case is
247 // for a node with length 64, which means the spilled 1-byte leb128 length is 1 byte of at
248 // least (34 byte header + 1 byte len + 64 bytes edge data), which is ~1%. A 2-byte leb128
249 // length is about the same fractional overhead and it amortizes for yet greater lengths.
250let mut edge_list_data =
251 Vec::with_capacity(graph_bytes - node_count * size_of::<SerializedNodeHeader>());
252253for _ in 0..node_count {
254// Decode the header for this edge; the header packs together as many of the fixed-size
255 // fields as possible to limit the number of times we update decoder state.
256let node_header = SerializedNodeHeader { bytes: d.read_array() };
257258let index = node_header.index();
259260let node = &mut nodes[index];
261// Make sure there's no duplicate indices in the dep graph.
262assert!(node_header.node().kind != DepKind::Null && node.kind == DepKind::Null);
263*node = node_header.node();
264265 value_fingerprints[index] = node_header.value_fingerprint();
266267// If the length of this node's edge list is small, the length is stored in the header.
268 // If it is not, we fall back to another decoder call.
269let num_edges = node_header.len().unwrap_or_else(|| d.read_u32());
270271// The edges index list uses the same varint strategy as rmeta tables; we select the
272 // number of byte elements per-array not per-element. This lets us read the whole edge
273 // list for a node with one decoder call and also use the on-disk format in memory.
274let edges_len_bytes = node_header.bytes_per_index() * (num_edges as usize);
275// The in-memory structure for the edges list stores the byte width of the edges on
276 // this node with the offset into the global edge data array.
277let edges_header = node_header.edges_header(&edge_list_data, num_edges);
278279 edge_list_data.extend(d.read_raw_bytes(edges_len_bytes));
280281 edge_list_indices[index] = edges_header;
282 }
283284// When we access the edge list data, we do a fixed-size read from the edge list data then
285 // mask off the bytes that aren't for that edge index, so the last read may dangle off the
286 // end of the array. This padding ensure it doesn't.
287edge_list_data.extend(&[0u8; DEP_NODE_PAD]);
288289// Read the number of each dep kind and use it to create an hash map with a suitable size.
290let mut index: Vec<_> = (0..(DepKind::MAX + 1))
291 .map(|_| UnhashMap::with_capacity_and_hasher(d.read_u32() as usize, Default::default()))
292 .collect();
293294let session_count = d.read_u64();
295296for (idx, node) in nodes.iter_enumerated() {
297if index[node.kind.as_usize()].insert(node.key_fingerprint, idx).is_some() {
298// Empty nodes and side effect nodes can have duplicates
299if node.kind != DepKind::Null && node.kind != DepKind::SideEffect {
300let kind = node.kind;
301panic!(
302"Error: A dep graph node ({kind:?}) does not have an unique index. \
303 Running a clean build on a nightly compiler with \
304 `-Z incremental-verify-ich` can help narrow down the issue for reporting. \
305 A clean build may also work around the issue.\n
306 DepNode: {node:?}"
307)
308 }
309 }
310 }
311312 Arc::new(SerializedDepGraph {
313 nodes,
314 value_fingerprints,
315 edge_list_indices,
316 edge_list_data,
317 index,
318 session_count,
319 })
320 }
321}
322323/// A packed representation of all the fixed-size fields in a `NodeInfo`.
324///
325/// This stores in one byte array:
326/// * The value `Fingerprint` in the `NodeInfo`
327/// * The key `Fingerprint` in `DepNode` that is in this `NodeInfo`
328/// * The `DepKind`'s discriminant (a u16, but not all bits are used...)
329/// * The byte width of the encoded edges for this node
330/// * In whatever bits remain, the length of the edge list for this node, if it fits
331struct SerializedNodeHeader {
332// 2 bytes for the DepNode
333 // 4 bytes for the index
334 // 16 for Fingerprint in DepNode
335 // 16 for Fingerprint in NodeInfo
336bytes: [u8; 38],
337}
338339// The fields of a `SerializedNodeHeader`, this struct is an implementation detail and exists only
340// to make the implementation of `SerializedNodeHeader` simpler.
341struct Unpacked {
342 len: Option<u32>,
343 bytes_per_index: usize,
344 kind: DepKind,
345 index: SerializedDepNodeIndex,
346 key_fingerprint: PackedFingerprint,
347 value_fingerprint: Fingerprint,
348}
349350// Bit fields, where
351// M: bits used to store the length of a node's edge list
352// N: bits used to store the byte width of elements of the edge list
353// are
354// 0..M length of the edge
355// M..M+N bytes per index
356// M+N..16 kind
357impl SerializedNodeHeader {
358const TOTAL_BITS: usize = size_of::<DepKind>() * 8;
359const LEN_BITS: usize = Self::TOTAL_BITS - Self::KIND_BITS - Self::WIDTH_BITS;
360const WIDTH_BITS: usize = DEP_NODE_WIDTH_BITS;
361const KIND_BITS: usize = Self::TOTAL_BITS - DepKind::MAX.leading_zeros() as usize;
362const MAX_INLINE_LEN: usize = (u16::MAXas usize >> (Self::TOTAL_BITS - Self::LEN_BITS)) - 1;
363364#[inline]
365fn new(
366 node: &DepNode,
367 index: DepNodeIndex,
368 value_fingerprint: Fingerprint,
369 edge_max_index: u32,
370 edge_count: usize,
371 ) -> Self {
372if 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);
373374let mut head = node.kind.as_u16();
375376let free_bytes = edge_max_index.leading_zeros() as usize / 8;
377let bytes_per_index = (DEP_NODE_SIZE - free_bytes).saturating_sub(1);
378head |= (bytes_per_indexas u16) << Self::KIND_BITS;
379380// Encode number of edges + 1 so that we can reserve 0 to indicate that the len doesn't fit
381 // in this bitfield.
382if edge_count <= Self::MAX_INLINE_LEN {
383head |= (edge_countas u16 + 1) << (Self::KIND_BITS + Self::WIDTH_BITS);
384 }
385386let hash: Fingerprint = node.key_fingerprint.into();
387388// Using half-open ranges ensures an unconditional panic if we get the magic numbers wrong.
389let mut bytes = [0u8; 38];
390bytes[..2].copy_from_slice(&head.to_le_bytes());
391bytes[2..6].copy_from_slice(&index.as_u32().to_le_bytes());
392bytes[6..22].copy_from_slice(&hash.to_le_bytes());
393bytes[22..].copy_from_slice(&value_fingerprint.to_le_bytes());
394395#[cfg(debug_assertions)]
396{
397let res = Self { bytes };
398match (&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());
399match (&*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());
400if let Some(len) = res.len() {
401match (&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);
402 }
403 }
404Self { bytes }
405 }
406407#[inline]
408fn unpack(&self) -> Unpacked {
409let head = u16::from_le_bytes(self.bytes[..2].try_into().unwrap());
410let index = u32::from_le_bytes(self.bytes[2..6].try_into().unwrap());
411let key_fingerprint = self.bytes[6..22].try_into().unwrap();
412let value_fingerprint = self.bytes[22..].try_into().unwrap();
413414let kind = head & mask(Self::KIND_BITS) as u16;
415let bytes_per_index = (head >> Self::KIND_BITS) & mask(Self::WIDTH_BITS) as u16;
416let len = (headas u32) >> (Self::WIDTH_BITS + Self::KIND_BITS);
417418Unpacked {
419 len: len.checked_sub(1),
420 bytes_per_index: bytes_per_indexas usize + 1,
421 kind: DepKind::from_u16(kind),
422 index: SerializedDepNodeIndex::from_u32(index),
423 key_fingerprint: Fingerprint::from_le_bytes(key_fingerprint).into(),
424 value_fingerprint: Fingerprint::from_le_bytes(value_fingerprint),
425 }
426 }
427428#[inline]
429fn len(&self) -> Option<u32> {
430self.unpack().len
431 }
432433#[inline]
434fn bytes_per_index(&self) -> usize {
435self.unpack().bytes_per_index
436 }
437438#[inline]
439fn index(&self) -> SerializedDepNodeIndex {
440self.unpack().index
441 }
442443#[inline]
444fn value_fingerprint(&self) -> Fingerprint {
445self.unpack().value_fingerprint
446 }
447448#[inline]
449fn node(&self) -> DepNode {
450let Unpacked { kind, key_fingerprint, .. } = self.unpack();
451DepNode { kind, key_fingerprint }
452 }
453454#[inline]
455fn edges_header(&self, edge_list_data: &[u8], num_edges: u32) -> EdgeHeader {
456EdgeHeader {
457 repr: (edge_list_data.len() << DEP_NODE_WIDTH_BITS) | (self.bytes_per_index() - 1),
458num_edges,
459 }
460 }
461}
462463#[derive(#[automatically_derived]
impl ::core::fmt::Debug for NodeInfo {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "NodeInfo",
"node", &self.node, "value_fingerprint", &self.value_fingerprint,
"edges", &&self.edges)
}
}Debug)]
464struct NodeInfo {
465 node: DepNode,
466 value_fingerprint: Fingerprint,
467 edges: EdgesVec,
468}
469470impl NodeInfo {
471fn encode(&self, e: &mut MemEncoder, index: DepNodeIndex) {
472let NodeInfo { ref node, value_fingerprint, ref edges } = *self;
473let header = SerializedNodeHeader::new(
474node,
475index,
476value_fingerprint,
477edges.max_index(),
478edges.len(),
479 );
480e.write_array(header.bytes);
481482if header.len().is_none() {
483// The edges are all unique and the number of unique indices is less than u32::MAX.
484e.emit_u32(edges.len().try_into().unwrap());
485 }
486487let bytes_per_index = header.bytes_per_index();
488for node_index in edges.iter() {
489 e.write_with(|dest| {
490*dest = node_index.as_u32().to_le_bytes();
491 bytes_per_index
492 });
493 }
494 }
495496/// Encode a node that was promoted from the previous graph. It reads the edges directly from
497 /// the previous dep graph and expects all edges to already have a new dep node index assigned.
498 /// This avoids the overhead of constructing `EdgesVec`, which would be needed to call `encode`.
499#[inline]
500fn encode_promoted(
501 e: &mut MemEncoder,
502 node: &DepNode,
503 index: DepNodeIndex,
504 value_fingerprint: Fingerprint,
505 prev_index: SerializedDepNodeIndex,
506 colors: &DepNodeColorMap,
507 previous: &SerializedDepGraph,
508 ) -> usize {
509let edges = previous.edge_targets_from(prev_index);
510let edge_count = edges.size_hint().0;
511512// Find the highest edge in the new dep node indices
513let edge_max =
514edges.clone().map(|i| colors.current(i).unwrap().as_u32()).max().unwrap_or(0);
515516let header =
517SerializedNodeHeader::new(node, index, value_fingerprint, edge_max, edge_count);
518e.write_array(header.bytes);
519520if header.len().is_none() {
521// The edges are all unique and the number of unique indices is less than u32::MAX.
522e.emit_u32(edge_count.try_into().unwrap());
523 }
524525let bytes_per_index = header.bytes_per_index();
526for node_index in edges {
527let node_index = colors.current(node_index).unwrap();
528 e.write_with(|dest| {
529*dest = node_index.as_u32().to_le_bytes();
530 bytes_per_index
531 });
532 }
533534edge_count535 }
536}
537538struct Stat {
539 kind: DepKind,
540 node_counter: u64,
541 edge_counter: u64,
542}
543544struct LocalEncoderState {
545 next_node_index: u32,
546 remaining_node_index: u32,
547 encoder: MemEncoder,
548 node_count: usize,
549 edge_count: usize,
550551/// Stores the number of times we've encoded each dep kind.
552kind_stats: Vec<u32>,
553}
554555struct LocalEncoderResult {
556 node_max: u32,
557 node_count: usize,
558 edge_count: usize,
559560/// Stores the number of times we've encoded each dep kind.
561kind_stats: Vec<u32>,
562}
563564struct EncoderState {
565 next_node_index: AtomicU64,
566 previous: Arc<SerializedDepGraph>,
567 file: Lock<Option<FileEncoder>>,
568 local: WorkerLocal<RefCell<LocalEncoderState>>,
569 stats: Option<Lock<FxHashMap<DepKind, Stat>>>,
570}
571572impl EncoderState {
573fn new(encoder: FileEncoder, record_stats: bool, previous: Arc<SerializedDepGraph>) -> Self {
574Self {
575previous,
576 next_node_index: AtomicU64::new(0),
577 stats: record_stats.then(|| Lock::new(FxHashMap::default())),
578 file: Lock::new(Some(encoder)),
579 local: WorkerLocal::new(|_| {
580RefCell::new(LocalEncoderState {
581 next_node_index: 0,
582 remaining_node_index: 0,
583 edge_count: 0,
584 node_count: 0,
585 encoder: MemEncoder::new(),
586 kind_stats: iter::repeat_n(0, DepKind::MAXas usize + 1).collect(),
587 })
588 }),
589 }
590 }
591592#[inline]
593fn next_index(&self, local: &mut LocalEncoderState) -> DepNodeIndex {
594if local.remaining_node_index == 0 {
595const COUNT: u32 = 256;
596597// We assume that there won't be enough active threads to overflow `u64` from `u32::MAX` here.
598 // This can exceed u32::MAX by at most `N` * `COUNT` where `N` is the thread pool count since
599 // `try_into().unwrap()` will make threads panic when `self.next_node_index` exceeds u32::MAX.
600local.next_node_index =
601self.next_node_index.fetch_add(COUNTas u64, Ordering::Relaxed).try_into().unwrap();
602603// Check that we'll stay within `u32`
604local.next_node_index.checked_add(COUNT).unwrap();
605606local.remaining_node_index = COUNT;
607 }
608609DepNodeIndex::from_u32(local.next_node_index)
610 }
611612/// Marks the index previously returned by `next_index` as used.
613#[inline]
614fn bump_index(&self, local: &mut LocalEncoderState) {
615local.remaining_node_index -= 1;
616local.next_node_index += 1;
617local.node_count += 1;
618 }
619620#[inline]
621fn record(
622&self,
623 node: &DepNode,
624 index: DepNodeIndex,
625 edge_count: usize,
626 edges: impl FnOnce(&Self) -> Vec<DepNodeIndex>,
627 retained_graph: &Option<Lock<RetainedDepGraph>>,
628 local: &mut LocalEncoderState,
629 ) {
630local.kind_stats[node.kind.as_usize()] += 1;
631local.edge_count += edge_count;
632633if let Some(retained_graph) = &retained_graph {
634// Call `edges` before the outlined code to allow the closure to be optimized out.
635let edges = edges(self);
636637// Outline the build of the full dep graph as it's typically disabled and cold.
638outline(move || {
639// Do not ICE when a query is called from within `with_query`.
640if let Some(retained_graph) = &mut retained_graph.try_lock() {
641retained_graph.push(index, *node, &edges);
642 }
643 });
644 }
645646if let Some(stats) = &self.stats {
647let kind = node.kind;
648649// Outline the stats code as it's typically disabled and cold.
650outline(move || {
651let mut stats = stats.lock();
652let stat =
653stats.entry(kind).or_insert(Stat { kind, node_counter: 0, edge_counter: 0 });
654stat.node_counter += 1;
655stat.edge_counter += edge_countas u64;
656 });
657 }
658 }
659660#[inline]
661fn flush_mem_encoder(&self, local: &mut LocalEncoderState) {
662let data = &mut local.encoder.data;
663if data.len() > 64 * 1024 {
664self.file.lock().as_mut().unwrap().emit_raw_bytes(&data[..]);
665data.clear();
666 }
667 }
668669/// Encodes a node to the current graph.
670fn encode_node(
671&self,
672 index: DepNodeIndex,
673 node: &NodeInfo,
674 retained_graph: &Option<Lock<RetainedDepGraph>>,
675 local: &mut LocalEncoderState,
676 ) {
677node.encode(&mut local.encoder, index);
678self.flush_mem_encoder(&mut *local);
679self.record(
680&node.node,
681index,
682node.edges.len(),
683 |_| node.edges[..].to_vec(),
684retained_graph,
685&mut *local,
686 );
687 }
688689/// Encodes a node that was promoted from the previous graph. It reads the information directly from
690 /// the previous dep graph for performance reasons.
691 ///
692 /// This differs from `encode_node` where you have to explicitly provide the relevant `NodeInfo`.
693 ///
694 /// It expects all edges to already have a new dep node index assigned.
695#[inline]
696fn encode_promoted_node(
697&self,
698 index: DepNodeIndex,
699 prev_index: SerializedDepNodeIndex,
700 retained_graph: &Option<Lock<RetainedDepGraph>>,
701 colors: &DepNodeColorMap,
702 local: &mut LocalEncoderState,
703 ) {
704let node = self.previous.index_to_node(prev_index);
705let value_fingerprint = self.previous.value_fingerprint_for_index(prev_index);
706let edge_count = NodeInfo::encode_promoted(
707&mut local.encoder,
708node,
709index,
710value_fingerprint,
711prev_index,
712colors,
713&self.previous,
714 );
715self.flush_mem_encoder(&mut *local);
716self.record(
717node,
718index,
719edge_count,
720 |this| {
721this.previous
722 .edge_targets_from(prev_index)
723 .map(|i| colors.current(i).unwrap())
724 .collect()
725 },
726retained_graph,
727&mut *local,
728 );
729 }
730731fn finish(&self, profiler: &SelfProfilerRef, current: &CurrentDepGraph) -> FileEncodeResult {
732// Prevent more indices from being allocated.
733self.next_node_index.store(u32::MAXas u64 + 1, Ordering::SeqCst);
734735let results = broadcast(|_| {
736let mut local = self.local.borrow_mut();
737738// Prevent more indices from being allocated on this thread.
739local.remaining_node_index = 0;
740741let data = mem::replace(&mut local.encoder.data, Vec::new());
742self.file.lock().as_mut().unwrap().emit_raw_bytes(&data);
743744LocalEncoderResult {
745 kind_stats: local.kind_stats.clone(),
746 node_max: local.next_node_index,
747 node_count: local.node_count,
748 edge_count: local.edge_count,
749 }
750 });
751752let mut encoder = self.file.lock().take().unwrap();
753754let mut kind_stats: Vec<u32> = iter::repeat_n(0, DepKind::MAXas usize + 1).collect();
755756let mut node_max = 0;
757let mut node_count = 0;
758let mut edge_count = 0;
759760for result in results {
761 node_max = max(node_max, result.node_max);
762 node_count += result.node_count;
763 edge_count += result.edge_count;
764for (i, stat) in result.kind_stats.iter().enumerate() {
765 kind_stats[i] += stat;
766 }
767 }
768769// Encode the number of each dep kind encountered
770for count in kind_stats.iter() {
771 count.encode(&mut encoder);
772 }
773774self.previous.session_count.checked_add(1).unwrap().encode(&mut encoder);
775776{
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:776",
"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(776u32),
::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);
777{
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:777",
"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(777u32),
::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());
778IntEncodedWithFixedSize(node_max.try_into().unwrap()).encode(&mut encoder);
779IntEncodedWithFixedSize(node_count.try_into().unwrap()).encode(&mut encoder);
780IntEncodedWithFixedSize(edge_count.try_into().unwrap()).encode(&mut encoder);
781{
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:781",
"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(781u32),
::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());
782// Drop the encoder so that nothing is written after the counts.
783let result = encoder.finish();
784if let Ok(position) = result {
785// FIXME(rylev): we hardcode the dep graph file name so we
786 // don't need a dependency on rustc_incremental just for that.
787profiler.artifact_size("dep_graph", "dep-graph.bin", positionas u64);
788 }
789790self.print_incremental_info(current, node_count, edge_count);
791792result793 }
794795fn print_incremental_info(
796&self,
797 current: &CurrentDepGraph,
798 total_node_count: usize,
799 total_edge_count: usize,
800 ) {
801if let Some(record_stats) = &self.stats {
802let record_stats = record_stats.lock();
803// `stats` is sorted below so we can allow this lint here.
804#[allow(rustc::potential_query_instability)]
805let mut stats: Vec<_> = record_stats.values().collect();
806stats.sort_by_key(|s| -(s.node_counter as i64));
807808const SEPARATOR: &str = "[incremental] --------------------------------\
809 ----------------------------------------------\
810 ------------";
811812{ ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
813{ ::std::io::_eprint(format_args!("[incremental] DepGraph Statistics\n")); };eprintln!("[incremental] DepGraph Statistics");
814{ ::std::io::_eprint(format_args!("{0}\n", SEPARATOR)); };eprintln!("{SEPARATOR}");
815{ ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
816{
::std::io::_eprint(format_args!("[incremental] Total Node Count: {0}\n",
total_node_count));
};eprintln!("[incremental] Total Node Count: {}", total_node_count);
817{
::std::io::_eprint(format_args!("[incremental] Total Edge Count: {0}\n",
total_edge_count));
};eprintln!("[incremental] Total Edge Count: {}", total_edge_count);
818819if truecfg!(debug_assertions) {
820let total_read_count = current.total_read_count.load(Ordering::Relaxed);
821let total_duplicate_read_count =
822current.total_duplicate_read_count.load(Ordering::Relaxed);
823{
::std::io::_eprint(format_args!("[incremental] Total Edge Reads: {0}\n",
total_read_count));
};eprintln!("[incremental] Total Edge Reads: {total_read_count}");
824{
::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}");
825 }
826827{ ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
828{
::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!(
829"[incremental] {:<36}| {:<17}| {:<12}| {:<17}|",
830"Node Kind", "Node Frequency", "Node Count", "Avg. Edge Count"
831);
832{ ::std::io::_eprint(format_args!("{0}\n", SEPARATOR)); };eprintln!("{SEPARATOR}");
833834for stat in stats {
835let node_kind_ratio =
836 (100.0 * (stat.node_counter as f64)) / (total_node_count as f64);
837let node_kind_avg_edges = (stat.edge_counter as f64) / (stat.node_counter as f64);
838839{
::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!(
840"[incremental] {:<36}|{:>16.1}% |{:>12} |{:>17.1} |",
841format!("{:?}", stat.kind),
842 node_kind_ratio,
843 stat.node_counter,
844 node_kind_avg_edges,
845 );
846 }
847848{ ::std::io::_eprint(format_args!("{0}\n", SEPARATOR)); };eprintln!("{SEPARATOR}");
849{ ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
850 }
851 }
852}
853854pub(crate) struct GraphEncoder {
855 profiler: SelfProfilerRef,
856 status: EncoderState,
857/// In-memory copy of the dep graph; only present if `-Zquery-dep-graph` is set.
858retained_graph: Option<Lock<RetainedDepGraph>>,
859}
860861impl GraphEncoder {
862pub(crate) fn new(
863 sess: &Session,
864 encoder: FileEncoder,
865 prev_node_count: usize,
866 previous: Arc<SerializedDepGraph>,
867 ) -> Self {
868let retained_graph = sess869 .opts
870 .unstable_opts
871 .query_dep_graph
872 .then(|| Lock::new(RetainedDepGraph::new(prev_node_count)));
873let status = EncoderState::new(encoder, sess.opts.unstable_opts.incremental_info, previous);
874GraphEncoder { status, retained_graph, profiler: sess.prof.clone() }
875 }
876877pub(crate) fn with_retained_dep_graph(&self, f: impl Fn(&RetainedDepGraph)) {
878if let Some(retained_graph) = &self.retained_graph {
879f(&retained_graph.lock())
880 }
881 }
882883/// Encodes a node that does not exists in the previous graph.
884pub(crate) fn send_new(
885&self,
886 node: DepNode,
887 value_fingerprint: Fingerprint,
888 edges: EdgesVec,
889 ) -> DepNodeIndex {
890let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
891let node = NodeInfo { node, value_fingerprint, edges };
892let mut local = self.status.local.borrow_mut();
893let index = self.status.next_index(&mut *local);
894self.status.bump_index(&mut *local);
895self.status.encode_node(index, &node, &self.retained_graph, &mut *local);
896index897 }
898899/// Encodes a node that exists in the previous graph, but was re-executed.
900 ///
901 /// This will also ensure the dep node is colored either red or green.
902pub(crate) fn send_and_color(
903&self,
904 prev_index: SerializedDepNodeIndex,
905 colors: &DepNodeColorMap,
906 node: DepNode,
907 value_fingerprint: Fingerprint,
908 edges: EdgesVec,
909 is_green: bool,
910 ) -> DepNodeIndex {
911let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
912let node = NodeInfo { node, value_fingerprint, edges };
913914let mut local = self.status.local.borrow_mut();
915916let index = self.status.next_index(&mut *local);
917let color = if is_green { DesiredColor::Green { index } } else { DesiredColor::Red };
918919// Use `try_set_color` to avoid racing when `send_promoted` is called concurrently
920 // on the same index.
921match colors.try_set_color(prev_index, color) {
922 TrySetColorResult::Success => {}
923 TrySetColorResult::AlreadyRed => {
::core::panicking::panic_fmt(format_args!("dep node {0:?} is unexpectedly red",
prev_index));
}panic!("dep node {prev_index:?} is unexpectedly red"),
924 TrySetColorResult::AlreadyGreen { index } => return index,
925 }
926927self.status.bump_index(&mut *local);
928self.status.encode_node(index, &node, &self.retained_graph, &mut *local);
929index930 }
931932/// Encodes a node that was promoted from the previous graph. It reads the information directly
933 /// from the previous dep graph and expects all edges to already have a new dep node index
934 /// assigned.
935 ///
936 /// Tries to mark the dep node green, and returns Some if it is now green,
937 /// or None if had already been concurrently marked red.
938#[inline]
939pub(crate) fn send_promoted(
940&self,
941 prev_index: SerializedDepNodeIndex,
942 colors: &DepNodeColorMap,
943 ) -> Option<DepNodeIndex> {
944let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
945946let mut local = self.status.local.borrow_mut();
947let index = self.status.next_index(&mut *local);
948949// Use `try_set_color` to avoid racing when `send_promoted` or `send_and_color`
950 // is called concurrently on the same index.
951match colors.try_set_color(prev_index, DesiredColor::Green { index }) {
952 TrySetColorResult::Success => {
953self.status.bump_index(&mut *local);
954self.status.encode_promoted_node(
955index,
956prev_index,
957&self.retained_graph,
958colors,
959&mut *local,
960 );
961Some(index)
962 }
963 TrySetColorResult::AlreadyRed => None,
964 TrySetColorResult::AlreadyGreen { index } => Some(index),
965 }
966 }
967968pub(crate) fn finish(&self, current: &CurrentDepGraph) -> FileEncodeResult {
969let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph_finish");
970971self.status.finish(&self.profiler, current)
972 }
973}