rustc_query_system/dep_graph/
serialized.rs1use std::iter;
39use std::marker::PhantomData;
40use std::sync::Arc;
41
42use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint};
43use rustc_data_structures::fx::FxHashMap;
44use rustc_data_structures::outline;
45use rustc_data_structures::profiling::SelfProfilerRef;
46use rustc_data_structures::sync::Lock;
47use rustc_data_structures::unhash::UnhashMap;
48use rustc_index::{Idx, IndexVec};
49use rustc_serialize::opaque::{FileEncodeResult, FileEncoder, IntEncodedWithFixedSize, MemDecoder};
50use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
51use tracing::{debug, instrument};
52
53use super::query::DepGraphQuery;
54use super::{DepKind, DepNode, DepNodeIndex, Deps};
55use crate::dep_graph::edges::EdgesVec;
56
57rustc_index::newtype_index! {
61 #[encodable]
62 #[max = 0x7FFF_FFFF]
63 pub struct SerializedDepNodeIndex {}
64}
65
66const DEP_NODE_SIZE: usize = size_of::<SerializedDepNodeIndex>();
67const DEP_NODE_PAD: usize = DEP_NODE_SIZE - 1;
70const DEP_NODE_WIDTH_BITS: usize = DEP_NODE_SIZE / 2;
75
76#[derive(Debug, Default)]
78pub struct SerializedDepGraph {
79 nodes: IndexVec<SerializedDepNodeIndex, DepNode>,
81 fingerprints: IndexVec<SerializedDepNodeIndex, Fingerprint>,
84 edge_list_indices: IndexVec<SerializedDepNodeIndex, EdgeHeader>,
88 edge_list_data: Vec<u8>,
91 index: Vec<UnhashMap<PackedFingerprint, SerializedDepNodeIndex>>,
94}
95
96impl SerializedDepGraph {
97 #[inline]
98 pub fn edge_targets_from(
99 &self,
100 source: SerializedDepNodeIndex,
101 ) -> impl Iterator<Item = SerializedDepNodeIndex> + Clone {
102 let header = self.edge_list_indices[source];
103 let mut raw = &self.edge_list_data[header.start()..];
104 let end = self
107 .edge_list_indices
108 .get(source + 1)
109 .map(|h| h.start())
110 .unwrap_or_else(|| self.edge_list_data.len() - DEP_NODE_PAD);
111
112 let bytes_per_index = header.bytes_per_index();
115 let len = (end - header.start()) / bytes_per_index;
116
117 let mask = header.mask();
119 (0..len).map(move |_| {
120 let index = &raw[..DEP_NODE_SIZE];
123 raw = &raw[bytes_per_index..];
124 let index = u32::from_le_bytes(index.try_into().unwrap()) & mask;
125 SerializedDepNodeIndex::from_u32(index)
126 })
127 }
128
129 #[inline]
130 pub fn index_to_node(&self, dep_node_index: SerializedDepNodeIndex) -> DepNode {
131 self.nodes[dep_node_index]
132 }
133
134 #[inline]
135 pub fn node_to_index_opt(&self, dep_node: &DepNode) -> Option<SerializedDepNodeIndex> {
136 self.index.get(dep_node.kind.as_usize())?.get(&dep_node.hash).cloned()
137 }
138
139 #[inline]
140 pub fn fingerprint_by_index(&self, dep_node_index: SerializedDepNodeIndex) -> Fingerprint {
141 self.fingerprints[dep_node_index]
142 }
143
144 #[inline]
145 pub fn node_count(&self) -> usize {
146 self.nodes.len()
147 }
148}
149
150#[derive(Debug, Clone, Copy)]
155struct EdgeHeader {
156 repr: usize,
157}
158
159impl EdgeHeader {
160 #[inline]
161 fn start(self) -> usize {
162 self.repr >> DEP_NODE_WIDTH_BITS
163 }
164
165 #[inline]
166 fn bytes_per_index(self) -> usize {
167 (self.repr & mask(DEP_NODE_WIDTH_BITS)) + 1
168 }
169
170 #[inline]
171 fn mask(self) -> u32 {
172 mask(self.bytes_per_index() * 8) as u32
173 }
174}
175
176#[inline]
177fn mask(bits: usize) -> usize {
178 usize::MAX >> ((size_of::<usize>() * 8) - bits)
179}
180
181impl SerializedDepGraph {
182 #[instrument(level = "debug", skip(d))]
183 pub fn decode<D: Deps>(d: &mut MemDecoder<'_>) -> Arc<SerializedDepGraph> {
184 debug!("position: {:?}", d.position());
186 let (node_count, edge_count) =
187 d.with_position(d.len() - 2 * IntEncodedWithFixedSize::ENCODED_SIZE, |d| {
188 debug!("position: {:?}", d.position());
189 let node_count = IntEncodedWithFixedSize::decode(d).0 as usize;
190 let edge_count = IntEncodedWithFixedSize::decode(d).0 as usize;
191 (node_count, edge_count)
192 });
193 debug!("position: {:?}", d.position());
194
195 debug!(?node_count, ?edge_count);
196
197 let graph_bytes = d.len() - (2 * IntEncodedWithFixedSize::ENCODED_SIZE) - d.position();
198
199 let mut nodes = IndexVec::with_capacity(node_count);
200 let mut fingerprints = IndexVec::with_capacity(node_count);
201 let mut edge_list_indices = IndexVec::with_capacity(node_count);
202 let mut edge_list_data =
212 Vec::with_capacity(graph_bytes - node_count * size_of::<SerializedNodeHeader<D>>());
213
214 for _index in 0..node_count {
215 let node_header =
218 SerializedNodeHeader::<D> { bytes: d.read_array(), _marker: PhantomData };
219
220 let _i: SerializedDepNodeIndex = nodes.push(node_header.node());
221 debug_assert_eq!(_i.index(), _index);
222
223 let _i: SerializedDepNodeIndex = fingerprints.push(node_header.fingerprint());
224 debug_assert_eq!(_i.index(), _index);
225
226 let num_edges = node_header.len().unwrap_or_else(|| d.read_usize());
229
230 let edges_len_bytes = node_header.bytes_per_index() * num_edges;
234 let edges_header = node_header.edges_header(&edge_list_data);
237
238 edge_list_data.extend(d.read_raw_bytes(edges_len_bytes));
239
240 let _i: SerializedDepNodeIndex = edge_list_indices.push(edges_header);
241 debug_assert_eq!(_i.index(), _index);
242 }
243
244 edge_list_data.extend(&[0u8; DEP_NODE_PAD]);
248
249 let mut index: Vec<_> = (0..(D::DEP_KIND_MAX + 1))
251 .map(|_| UnhashMap::with_capacity_and_hasher(d.read_u32() as usize, Default::default()))
252 .collect();
253
254 for (idx, node) in nodes.iter_enumerated() {
255 index[node.kind.as_usize()].insert(node.hash, idx);
256 }
257
258 Arc::new(SerializedDepGraph {
259 nodes,
260 fingerprints,
261 edge_list_indices,
262 edge_list_data,
263 index,
264 })
265 }
266}
267
268struct SerializedNodeHeader<D> {
277 bytes: [u8; 34],
281 _marker: PhantomData<D>,
282}
283
284struct Unpacked {
287 len: Option<usize>,
288 bytes_per_index: usize,
289 kind: DepKind,
290 hash: PackedFingerprint,
291 fingerprint: Fingerprint,
292}
293
294impl<D: Deps> SerializedNodeHeader<D> {
302 const TOTAL_BITS: usize = size_of::<DepKind>() * 8;
303 const LEN_BITS: usize = Self::TOTAL_BITS - Self::KIND_BITS - Self::WIDTH_BITS;
304 const WIDTH_BITS: usize = DEP_NODE_WIDTH_BITS;
305 const KIND_BITS: usize = Self::TOTAL_BITS - D::DEP_KIND_MAX.leading_zeros() as usize;
306 const MAX_INLINE_LEN: usize = (u16::MAX as usize >> (Self::TOTAL_BITS - Self::LEN_BITS)) - 1;
307
308 #[inline]
309 fn new(
310 node: DepNode,
311 fingerprint: Fingerprint,
312 edge_max_index: u32,
313 edge_count: usize,
314 ) -> Self {
315 debug_assert_eq!(Self::TOTAL_BITS, Self::LEN_BITS + Self::WIDTH_BITS + Self::KIND_BITS);
316
317 let mut head = node.kind.as_inner();
318
319 let free_bytes = edge_max_index.leading_zeros() as usize / 8;
320 let bytes_per_index = (DEP_NODE_SIZE - free_bytes).saturating_sub(1);
321 head |= (bytes_per_index as u16) << Self::KIND_BITS;
322
323 if edge_count <= Self::MAX_INLINE_LEN {
326 head |= (edge_count as u16 + 1) << (Self::KIND_BITS + Self::WIDTH_BITS);
327 }
328
329 let hash: Fingerprint = node.hash.into();
330
331 let mut bytes = [0u8; 34];
333 bytes[..2].copy_from_slice(&head.to_le_bytes());
334 bytes[2..18].copy_from_slice(&hash.to_le_bytes());
335 bytes[18..].copy_from_slice(&fingerprint.to_le_bytes());
336
337 #[cfg(debug_assertions)]
338 {
339 let res = Self { bytes, _marker: PhantomData };
340 assert_eq!(fingerprint, res.fingerprint());
341 assert_eq!(node, res.node());
342 if let Some(len) = res.len() {
343 assert_eq!(edge_count, len);
344 }
345 }
346 Self { bytes, _marker: PhantomData }
347 }
348
349 #[inline]
350 fn unpack(&self) -> Unpacked {
351 let head = u16::from_le_bytes(self.bytes[..2].try_into().unwrap());
352 let hash = self.bytes[2..18].try_into().unwrap();
353 let fingerprint = self.bytes[18..].try_into().unwrap();
354
355 let kind = head & mask(Self::KIND_BITS) as u16;
356 let bytes_per_index = (head >> Self::KIND_BITS) & mask(Self::WIDTH_BITS) as u16;
357 let len = (head as usize) >> (Self::WIDTH_BITS + Self::KIND_BITS);
358
359 Unpacked {
360 len: len.checked_sub(1),
361 bytes_per_index: bytes_per_index as usize + 1,
362 kind: DepKind::new(kind),
363 hash: Fingerprint::from_le_bytes(hash).into(),
364 fingerprint: Fingerprint::from_le_bytes(fingerprint),
365 }
366 }
367
368 #[inline]
369 fn len(&self) -> Option<usize> {
370 self.unpack().len
371 }
372
373 #[inline]
374 fn bytes_per_index(&self) -> usize {
375 self.unpack().bytes_per_index
376 }
377
378 #[inline]
379 fn fingerprint(&self) -> Fingerprint {
380 self.unpack().fingerprint
381 }
382
383 #[inline]
384 fn node(&self) -> DepNode {
385 let Unpacked { kind, hash, .. } = self.unpack();
386 DepNode { kind, hash }
387 }
388
389 #[inline]
390 fn edges_header(&self, edge_list_data: &[u8]) -> EdgeHeader {
391 EdgeHeader {
392 repr: (edge_list_data.len() << DEP_NODE_WIDTH_BITS) | (self.bytes_per_index() - 1),
393 }
394 }
395}
396
397#[derive(Debug)]
398struct NodeInfo {
399 node: DepNode,
400 fingerprint: Fingerprint,
401 edges: EdgesVec,
402}
403
404impl NodeInfo {
405 fn encode<D: Deps>(&self, e: &mut FileEncoder) {
406 let NodeInfo { node, fingerprint, ref edges } = *self;
407 let header =
408 SerializedNodeHeader::<D>::new(node, fingerprint, edges.max_index(), edges.len());
409 e.write_array(header.bytes);
410
411 if header.len().is_none() {
412 e.emit_usize(edges.len());
413 }
414
415 let bytes_per_index = header.bytes_per_index();
416 for node_index in edges.iter() {
417 e.write_with(|dest| {
418 *dest = node_index.as_u32().to_le_bytes();
419 bytes_per_index
420 });
421 }
422 }
423
424 #[inline]
428 fn encode_promoted<D: Deps>(
429 e: &mut FileEncoder,
430 node: DepNode,
431 fingerprint: Fingerprint,
432 prev_index: SerializedDepNodeIndex,
433 prev_index_to_index: &IndexVec<SerializedDepNodeIndex, Option<DepNodeIndex>>,
434 previous: &SerializedDepGraph,
435 ) -> usize {
436 let edges = previous.edge_targets_from(prev_index);
437 let edge_count = edges.size_hint().0;
438
439 let edge_max =
441 edges.clone().map(|i| prev_index_to_index[i].unwrap().as_u32()).max().unwrap_or(0);
442
443 let header = SerializedNodeHeader::<D>::new(node, fingerprint, edge_max, edge_count);
444 e.write_array(header.bytes);
445
446 if header.len().is_none() {
447 e.emit_usize(edge_count);
448 }
449
450 let bytes_per_index = header.bytes_per_index();
451 for node_index in edges {
452 let node_index = prev_index_to_index[node_index].unwrap();
453 e.write_with(|dest| {
454 *dest = node_index.as_u32().to_le_bytes();
455 bytes_per_index
456 });
457 }
458
459 edge_count
460 }
461}
462
463struct Stat {
464 kind: DepKind,
465 node_counter: u64,
466 edge_counter: u64,
467}
468
469struct EncoderState<D: Deps> {
470 previous: Arc<SerializedDepGraph>,
471 encoder: FileEncoder,
472 total_node_count: usize,
473 total_edge_count: usize,
474 stats: Option<FxHashMap<DepKind, Stat>>,
475
476 kind_stats: Vec<u32>,
478 marker: PhantomData<D>,
479}
480
481impl<D: Deps> EncoderState<D> {
482 fn new(encoder: FileEncoder, record_stats: bool, previous: Arc<SerializedDepGraph>) -> Self {
483 Self {
484 previous,
485 encoder,
486 total_edge_count: 0,
487 total_node_count: 0,
488 stats: record_stats.then(FxHashMap::default),
489 kind_stats: iter::repeat(0).take(D::DEP_KIND_MAX as usize + 1).collect(),
490 marker: PhantomData,
491 }
492 }
493
494 #[inline]
495 fn record(
496 &mut self,
497 node: DepNode,
498 edge_count: usize,
499 edges: impl FnOnce(&mut Self) -> Vec<DepNodeIndex>,
500 record_graph: &Option<Lock<DepGraphQuery>>,
501 ) -> DepNodeIndex {
502 let index = DepNodeIndex::new(self.total_node_count);
503
504 self.total_node_count += 1;
505 self.kind_stats[node.kind.as_usize()] += 1;
506 self.total_edge_count += edge_count;
507
508 if let Some(record_graph) = &record_graph {
509 let edges = edges(self);
511
512 outline(move || {
514 if let Some(record_graph) = &mut record_graph.try_lock() {
516 record_graph.push(index, node, &edges);
517 }
518 });
519 }
520
521 if let Some(stats) = &mut self.stats {
522 let kind = node.kind;
523
524 outline(move || {
526 let stat =
527 stats.entry(kind).or_insert(Stat { kind, node_counter: 0, edge_counter: 0 });
528 stat.node_counter += 1;
529 stat.edge_counter += edge_count as u64;
530 });
531 }
532
533 index
534 }
535
536 fn encode_node(
538 &mut self,
539 node: &NodeInfo,
540 record_graph: &Option<Lock<DepGraphQuery>>,
541 ) -> DepNodeIndex {
542 node.encode::<D>(&mut self.encoder);
543 self.record(node.node, node.edges.len(), |_| node.edges[..].to_vec(), record_graph)
544 }
545
546 #[inline]
553 fn encode_promoted_node(
554 &mut self,
555 prev_index: SerializedDepNodeIndex,
556 record_graph: &Option<Lock<DepGraphQuery>>,
557 prev_index_to_index: &IndexVec<SerializedDepNodeIndex, Option<DepNodeIndex>>,
558 ) -> DepNodeIndex {
559 let node = self.previous.index_to_node(prev_index);
560
561 let fingerprint = self.previous.fingerprint_by_index(prev_index);
562 let edge_count = NodeInfo::encode_promoted::<D>(
563 &mut self.encoder,
564 node,
565 fingerprint,
566 prev_index,
567 prev_index_to_index,
568 &self.previous,
569 );
570
571 self.record(
572 node,
573 edge_count,
574 |this| {
575 this.previous
576 .edge_targets_from(prev_index)
577 .map(|i| prev_index_to_index[i].unwrap())
578 .collect()
579 },
580 record_graph,
581 )
582 }
583
584 fn finish(self, profiler: &SelfProfilerRef) -> FileEncodeResult {
585 let Self {
586 mut encoder,
587 total_node_count,
588 total_edge_count,
589 stats: _,
590 kind_stats,
591 marker: _,
592 previous: _,
593 } = self;
594
595 let node_count = total_node_count.try_into().unwrap();
596 let edge_count = total_edge_count.try_into().unwrap();
597
598 for count in kind_stats.iter() {
600 count.encode(&mut encoder);
601 }
602
603 debug!(?node_count, ?edge_count);
604 debug!("position: {:?}", encoder.position());
605 IntEncodedWithFixedSize(node_count).encode(&mut encoder);
606 IntEncodedWithFixedSize(edge_count).encode(&mut encoder);
607 debug!("position: {:?}", encoder.position());
608 let result = encoder.finish();
610 if let Ok(position) = result {
611 profiler.artifact_size("dep_graph", "dep-graph.bin", position as u64);
614 }
615 result
616 }
617}
618
619pub(crate) struct GraphEncoder<D: Deps> {
620 profiler: SelfProfilerRef,
621 status: Lock<Option<EncoderState<D>>>,
622 record_graph: Option<Lock<DepGraphQuery>>,
623}
624
625impl<D: Deps> GraphEncoder<D> {
626 pub(crate) fn new(
627 encoder: FileEncoder,
628 prev_node_count: usize,
629 record_graph: bool,
630 record_stats: bool,
631 profiler: &SelfProfilerRef,
632 previous: Arc<SerializedDepGraph>,
633 ) -> Self {
634 let record_graph = record_graph.then(|| Lock::new(DepGraphQuery::new(prev_node_count)));
635 let status = Lock::new(Some(EncoderState::new(encoder, record_stats, previous)));
636 GraphEncoder { status, record_graph, profiler: profiler.clone() }
637 }
638
639 pub(crate) fn with_query(&self, f: impl Fn(&DepGraphQuery)) {
640 if let Some(record_graph) = &self.record_graph {
641 f(&record_graph.lock())
642 }
643 }
644
645 pub(crate) fn print_incremental_info(
646 &self,
647 total_read_count: u64,
648 total_duplicate_read_count: u64,
649 ) {
650 let mut status = self.status.lock();
651 let status = status.as_mut().unwrap();
652 if let Some(record_stats) = &status.stats {
653 let mut stats: Vec<_> = record_stats.values().collect();
654 stats.sort_by_key(|s| -(s.node_counter as i64));
655
656 const SEPARATOR: &str = "[incremental] --------------------------------\
657 ----------------------------------------------\
658 ------------";
659
660 eprintln!("[incremental]");
661 eprintln!("[incremental] DepGraph Statistics");
662 eprintln!("{SEPARATOR}");
663 eprintln!("[incremental]");
664 eprintln!("[incremental] Total Node Count: {}", status.total_node_count);
665 eprintln!("[incremental] Total Edge Count: {}", status.total_edge_count);
666
667 if cfg!(debug_assertions) {
668 eprintln!("[incremental] Total Edge Reads: {total_read_count}");
669 eprintln!("[incremental] Total Duplicate Edge Reads: {total_duplicate_read_count}");
670 }
671
672 eprintln!("[incremental]");
673 eprintln!(
674 "[incremental] {:<36}| {:<17}| {:<12}| {:<17}|",
675 "Node Kind", "Node Frequency", "Node Count", "Avg. Edge Count"
676 );
677 eprintln!("{SEPARATOR}");
678
679 for stat in stats {
680 let node_kind_ratio =
681 (100.0 * (stat.node_counter as f64)) / (status.total_node_count as f64);
682 let node_kind_avg_edges = (stat.edge_counter as f64) / (stat.node_counter as f64);
683
684 eprintln!(
685 "[incremental] {:<36}|{:>16.1}% |{:>12} |{:>17.1} |",
686 format!("{:?}", stat.kind),
687 node_kind_ratio,
688 stat.node_counter,
689 node_kind_avg_edges,
690 );
691 }
692
693 eprintln!("{SEPARATOR}");
694 eprintln!("[incremental]");
695 }
696 }
697
698 pub(crate) fn send(
699 &self,
700 node: DepNode,
701 fingerprint: Fingerprint,
702 edges: EdgesVec,
703 ) -> DepNodeIndex {
704 let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
705 let node = NodeInfo { node, fingerprint, edges };
706 self.status.lock().as_mut().unwrap().encode_node(&node, &self.record_graph)
707 }
708
709 #[inline]
712 pub(crate) fn send_promoted(
713 &self,
714 prev_index: SerializedDepNodeIndex,
715 prev_index_to_index: &IndexVec<SerializedDepNodeIndex, Option<DepNodeIndex>>,
716 ) -> DepNodeIndex {
717 let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
718 self.status.lock().as_mut().unwrap().encode_promoted_node(
719 prev_index,
720 &self.record_graph,
721 prev_index_to_index,
722 )
723 }
724
725 pub(crate) fn finish(&self) -> FileEncodeResult {
726 let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph_finish");
727
728 self.status.lock().take().unwrap().finish(&self.profiler)
729 }
730}