rustc_query_system/dep_graph/graph.rs
1use std::assert_matches::assert_matches;
2use std::fmt::Debug;
3use std::hash::Hash;
4use std::marker::PhantomData;
5use std::sync::Arc;
6use std::sync::atomic::{AtomicU32, Ordering};
7
8use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint};
9use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10use rustc_data_structures::outline;
11use rustc_data_structures::profiling::QueryInvocationId;
12use rustc_data_structures::sharded::{self, ShardedHashMap};
13use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
14use rustc_data_structures::sync::{AtomicU64, Lock};
15use rustc_data_structures::unord::UnordMap;
16use rustc_errors::DiagInner;
17use rustc_index::IndexVec;
18use rustc_macros::{Decodable, Encodable};
19use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
20use rustc_session::Session;
21use tracing::{debug, instrument};
22#[cfg(debug_assertions)]
23use {super::debug::EdgeFilter, std::env};
24
25use super::query::DepGraphQuery;
26use super::serialized::{GraphEncoder, SerializedDepGraph, SerializedDepNodeIndex};
27use super::{DepContext, DepKind, DepNode, Deps, HasDepContext, WorkProductId};
28use crate::dep_graph::edges::EdgesVec;
29use crate::ich::StableHashingContext;
30use crate::query::{QueryContext, QuerySideEffect};
31
32#[derive(Clone)]
33pub struct DepGraph<D: Deps> {
34 data: Option<Arc<DepGraphData<D>>>,
35
36 /// This field is used for assigning DepNodeIndices when running in
37 /// non-incremental mode. Even in non-incremental mode we make sure that
38 /// each task has a `DepNodeIndex` that uniquely identifies it. This unique
39 /// ID is used for self-profiling.
40 virtual_dep_node_index: Arc<AtomicU32>,
41}
42
43rustc_index::newtype_index! {
44 pub struct DepNodeIndex {}
45}
46
47// We store a large collection of these in `prev_index_to_index` during
48// non-full incremental builds, and want to ensure that the element size
49// doesn't inadvertently increase.
50rustc_data_structures::static_assert_size!(Option<DepNodeIndex>, 4);
51
52impl DepNodeIndex {
53 const SINGLETON_ZERO_DEPS_ANON_NODE: DepNodeIndex = DepNodeIndex::ZERO;
54 pub const FOREVER_RED_NODE: DepNodeIndex = DepNodeIndex::from_u32(1);
55}
56
57impl From<DepNodeIndex> for QueryInvocationId {
58 #[inline(always)]
59 fn from(dep_node_index: DepNodeIndex) -> Self {
60 QueryInvocationId(dep_node_index.as_u32())
61 }
62}
63
64pub struct MarkFrame<'a> {
65 index: SerializedDepNodeIndex,
66 parent: Option<&'a MarkFrame<'a>>,
67}
68
69#[derive(Debug)]
70pub(super) enum DepNodeColor {
71 Green(DepNodeIndex),
72 Red,
73 Unknown,
74}
75
76pub(crate) struct DepGraphData<D: Deps> {
77 /// The new encoding of the dependency graph, optimized for red/green
78 /// tracking. The `current` field is the dependency graph of only the
79 /// current compilation session: We don't merge the previous dep-graph into
80 /// current one anymore, but we do reference shared data to save space.
81 current: CurrentDepGraph<D>,
82
83 /// The dep-graph from the previous compilation session. It contains all
84 /// nodes and edges as well as all fingerprints of nodes that have them.
85 previous: Arc<SerializedDepGraph>,
86
87 colors: DepNodeColorMap,
88
89 /// When we load, there may be `.o` files, cached MIR, or other such
90 /// things available to us. If we find that they are not dirty, we
91 /// load the path to the file storing those work-products here into
92 /// this map. We can later look for and extract that data.
93 previous_work_products: WorkProductMap,
94
95 dep_node_debug: Lock<FxHashMap<DepNode, String>>,
96
97 /// Used by incremental compilation tests to assert that
98 /// a particular query result was decoded from disk
99 /// (not just marked green)
100 debug_loaded_from_disk: Lock<FxHashSet<DepNode>>,
101}
102
103pub fn hash_result<R>(hcx: &mut StableHashingContext<'_>, result: &R) -> Fingerprint
104where
105 R: for<'a> HashStable<StableHashingContext<'a>>,
106{
107 let mut stable_hasher = StableHasher::new();
108 result.hash_stable(hcx, &mut stable_hasher);
109 stable_hasher.finish()
110}
111
112impl<D: Deps> DepGraph<D> {
113 pub fn new(
114 session: &Session,
115 prev_graph: Arc<SerializedDepGraph>,
116 prev_work_products: WorkProductMap,
117 encoder: FileEncoder,
118 ) -> DepGraph<D> {
119 let prev_graph_node_count = prev_graph.node_count();
120
121 let current =
122 CurrentDepGraph::new(session, prev_graph_node_count, encoder, Arc::clone(&prev_graph));
123
124 let colors = DepNodeColorMap::new(prev_graph_node_count);
125
126 // Instantiate a node with zero dependencies only once for anonymous queries.
127 let _green_node_index = current.alloc_new_node(
128 DepNode { kind: D::DEP_KIND_ANON_ZERO_DEPS, hash: current.anon_id_seed.into() },
129 EdgesVec::new(),
130 Fingerprint::ZERO,
131 );
132 assert_eq!(_green_node_index, DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE);
133
134 // Instantiate a dependy-less red node only once for anonymous queries.
135 let red_node_index = current.alloc_new_node(
136 DepNode { kind: D::DEP_KIND_RED, hash: Fingerprint::ZERO.into() },
137 EdgesVec::new(),
138 Fingerprint::ZERO,
139 );
140 assert_eq!(red_node_index, DepNodeIndex::FOREVER_RED_NODE);
141 if prev_graph_node_count > 0 {
142 colors.insert_red(SerializedDepNodeIndex::from_u32(
143 DepNodeIndex::FOREVER_RED_NODE.as_u32(),
144 ));
145 }
146
147 DepGraph {
148 data: Some(Arc::new(DepGraphData {
149 previous_work_products: prev_work_products,
150 dep_node_debug: Default::default(),
151 current,
152 previous: prev_graph,
153 colors,
154 debug_loaded_from_disk: Default::default(),
155 })),
156 virtual_dep_node_index: Arc::new(AtomicU32::new(0)),
157 }
158 }
159
160 pub fn new_disabled() -> DepGraph<D> {
161 DepGraph { data: None, virtual_dep_node_index: Arc::new(AtomicU32::new(0)) }
162 }
163
164 #[inline]
165 pub(crate) fn data(&self) -> Option<&DepGraphData<D>> {
166 self.data.as_deref()
167 }
168
169 /// Returns `true` if we are actually building the full dep-graph, and `false` otherwise.
170 #[inline]
171 pub fn is_fully_enabled(&self) -> bool {
172 self.data.is_some()
173 }
174
175 pub fn with_query(&self, f: impl Fn(&DepGraphQuery)) {
176 if let Some(data) = &self.data {
177 data.current.encoder.with_query(f)
178 }
179 }
180
181 pub fn assert_ignored(&self) {
182 if let Some(..) = self.data {
183 D::read_deps(|task_deps| {
184 assert_matches!(
185 task_deps,
186 TaskDepsRef::Ignore,
187 "expected no task dependency tracking"
188 );
189 })
190 }
191 }
192
193 pub fn with_ignore<OP, R>(&self, op: OP) -> R
194 where
195 OP: FnOnce() -> R,
196 {
197 D::with_deps(TaskDepsRef::Ignore, op)
198 }
199
200 /// Used to wrap the deserialization of a query result from disk,
201 /// This method enforces that no new `DepNodes` are created during
202 /// query result deserialization.
203 ///
204 /// Enforcing this makes the query dep graph simpler - all nodes
205 /// must be created during the query execution, and should be
206 /// created from inside the 'body' of a query (the implementation
207 /// provided by a particular compiler crate).
208 ///
209 /// Consider the case of three queries `A`, `B`, and `C`, where
210 /// `A` invokes `B` and `B` invokes `C`:
211 ///
212 /// `A -> B -> C`
213 ///
214 /// Suppose that decoding the result of query `B` required re-computing
215 /// the query `C`. If we did not create a fresh `TaskDeps` when
216 /// decoding `B`, we would still be using the `TaskDeps` for query `A`
217 /// (if we needed to re-execute `A`). This would cause us to create
218 /// a new edge `A -> C`. If this edge did not previously
219 /// exist in the `DepGraph`, then we could end up with a different
220 /// `DepGraph` at the end of compilation, even if there were no
221 /// meaningful changes to the overall program (e.g. a newline was added).
222 /// In addition, this edge might cause a subsequent compilation run
223 /// to try to force `C` before marking other necessary nodes green. If
224 /// `C` did not exist in the new compilation session, then we could
225 /// get an ICE. Normally, we would have tried (and failed) to mark
226 /// some other query green (e.g. `item_children`) which was used
227 /// to obtain `C`, which would prevent us from ever trying to force
228 /// a nonexistent `D`.
229 ///
230 /// It might be possible to enforce that all `DepNode`s read during
231 /// deserialization already exist in the previous `DepGraph`. In
232 /// the above example, we would invoke `D` during the deserialization
233 /// of `B`. Since we correctly create a new `TaskDeps` from the decoding
234 /// of `B`, this would result in an edge `B -> D`. If that edge already
235 /// existed (with the same `DepPathHash`es), then it should be correct
236 /// to allow the invocation of the query to proceed during deserialization
237 /// of a query result. We would merely assert that the dep-graph fragment
238 /// that would have been added by invoking `C` while decoding `B`
239 /// is equivalent to the dep-graph fragment that we already instantiated for B
240 /// (at the point where we successfully marked B as green).
241 ///
242 /// However, this would require additional complexity
243 /// in the query infrastructure, and is not currently needed by the
244 /// decoding of any query results. Should the need arise in the future,
245 /// we should consider extending the query system with this functionality.
246 pub fn with_query_deserialization<OP, R>(&self, op: OP) -> R
247 where
248 OP: FnOnce() -> R,
249 {
250 D::with_deps(TaskDepsRef::Forbid, op)
251 }
252
253 #[inline(always)]
254 pub fn with_task<Ctxt: HasDepContext<Deps = D>, A: Debug, R>(
255 &self,
256 key: DepNode,
257 cx: Ctxt,
258 arg: A,
259 task: fn(Ctxt, A) -> R,
260 hash_result: Option<fn(&mut StableHashingContext<'_>, &R) -> Fingerprint>,
261 ) -> (R, DepNodeIndex) {
262 match self.data() {
263 Some(data) => data.with_task(key, cx, arg, task, hash_result),
264 None => (task(cx, arg), self.next_virtual_depnode_index()),
265 }
266 }
267
268 pub fn with_anon_task<Tcx: DepContext<Deps = D>, OP, R>(
269 &self,
270 cx: Tcx,
271 dep_kind: DepKind,
272 op: OP,
273 ) -> (R, DepNodeIndex)
274 where
275 OP: FnOnce() -> R,
276 {
277 match self.data() {
278 Some(data) => {
279 let (result, index) = data.with_anon_task_inner(cx, dep_kind, op);
280 self.read_index(index);
281 (result, index)
282 }
283 None => (op(), self.next_virtual_depnode_index()),
284 }
285 }
286}
287
288impl<D: Deps> DepGraphData<D> {
289 /// Starts a new dep-graph task. Dep-graph tasks are specified
290 /// using a free function (`task`) and **not** a closure -- this
291 /// is intentional because we want to exercise tight control over
292 /// what state they have access to. In particular, we want to
293 /// prevent implicit 'leaks' of tracked state into the task (which
294 /// could then be read without generating correct edges in the
295 /// dep-graph -- see the [rustc dev guide] for more details on
296 /// the dep-graph). To this end, the task function gets exactly two
297 /// pieces of state: the context `cx` and an argument `arg`. Both
298 /// of these bits of state must be of some type that implements
299 /// `DepGraphSafe` and hence does not leak.
300 ///
301 /// The choice of two arguments is not fundamental. One argument
302 /// would work just as well, since multiple values can be
303 /// collected using tuples. However, using two arguments works out
304 /// to be quite convenient, since it is common to need a context
305 /// (`cx`) and some argument (e.g., a `DefId` identifying what
306 /// item to process).
307 ///
308 /// For cases where you need some other number of arguments:
309 ///
310 /// - If you only need one argument, just use `()` for the `arg`
311 /// parameter.
312 /// - If you need 3+ arguments, use a tuple for the
313 /// `arg` parameter.
314 ///
315 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/queries/incremental-compilation.html
316 #[inline(always)]
317 pub(crate) fn with_task<Ctxt: HasDepContext<Deps = D>, A: Debug, R>(
318 &self,
319 key: DepNode,
320 cx: Ctxt,
321 arg: A,
322 task: fn(Ctxt, A) -> R,
323 hash_result: Option<fn(&mut StableHashingContext<'_>, &R) -> Fingerprint>,
324 ) -> (R, DepNodeIndex) {
325 // If the following assertion triggers, it can have two reasons:
326 // 1. Something is wrong with DepNode creation, either here or
327 // in `DepGraph::try_mark_green()`.
328 // 2. Two distinct query keys get mapped to the same `DepNode`
329 // (see for example #48923).
330 self.assert_dep_node_not_yet_allocated_in_current_session(&key, || {
331 format!(
332 "forcing query with already existing `DepNode`\n\
333 - query-key: {arg:?}\n\
334 - dep-node: {key:?}"
335 )
336 });
337
338 let with_deps = |task_deps| D::with_deps(task_deps, || task(cx, arg));
339 let (result, edges) = if cx.dep_context().is_eval_always(key.kind) {
340 (with_deps(TaskDepsRef::EvalAlways), EdgesVec::new())
341 } else {
342 let task_deps = Lock::new(TaskDeps::new(
343 #[cfg(debug_assertions)]
344 Some(key),
345 0,
346 ));
347 (with_deps(TaskDepsRef::Allow(&task_deps)), task_deps.into_inner().reads)
348 };
349
350 let dcx = cx.dep_context();
351 let dep_node_index = self.hash_result_and_alloc_node(dcx, key, edges, &result, hash_result);
352
353 (result, dep_node_index)
354 }
355
356 /// Executes something within an "anonymous" task, that is, a task the
357 /// `DepNode` of which is determined by the list of inputs it read from.
358 ///
359 /// NOTE: this does not actually count as a read of the DepNode here.
360 /// Using the result of this task without reading the DepNode will result
361 /// in untracked dependencies which may lead to ICEs as nodes are
362 /// incorrectly marked green.
363 ///
364 /// FIXME: This could perhaps return a `WithDepNode` to ensure that the
365 /// user of this function actually performs the read; we'll have to see
366 /// how to make that work with `anon` in `execute_job_incr`, though.
367 pub(crate) fn with_anon_task_inner<Tcx: DepContext<Deps = D>, OP, R>(
368 &self,
369 cx: Tcx,
370 dep_kind: DepKind,
371 op: OP,
372 ) -> (R, DepNodeIndex)
373 where
374 OP: FnOnce() -> R,
375 {
376 debug_assert!(!cx.is_eval_always(dep_kind));
377
378 // Large numbers of reads are common enough here that pre-sizing `read_set`
379 // to 128 actually helps perf on some benchmarks.
380 let task_deps = Lock::new(TaskDeps::new(
381 #[cfg(debug_assertions)]
382 None,
383 128,
384 ));
385 let result = D::with_deps(TaskDepsRef::Allow(&task_deps), op);
386 let task_deps = task_deps.into_inner();
387 let reads = task_deps.reads;
388
389 let dep_node_index = match reads.len() {
390 0 => {
391 // Because the dep-node id of anon nodes is computed from the sets of its
392 // dependencies we already know what the ID of this dependency-less node is
393 // going to be (i.e. equal to the precomputed
394 // `SINGLETON_DEPENDENCYLESS_ANON_NODE`). As a consequence we can skip creating
395 // a `StableHasher` and sending the node through interning.
396 DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE
397 }
398 1 => {
399 // When there is only one dependency, don't bother creating a node.
400 reads[0]
401 }
402 _ => {
403 // The dep node indices are hashed here instead of hashing the dep nodes of the
404 // dependencies. These indices may refer to different nodes per session, but this isn't
405 // a problem here because we that ensure the final dep node hash is per session only by
406 // combining it with the per session random number `anon_id_seed`. This hash only need
407 // to map the dependencies to a single value on a per session basis.
408 let mut hasher = StableHasher::new();
409 reads.hash(&mut hasher);
410
411 let target_dep_node = DepNode {
412 kind: dep_kind,
413 // Fingerprint::combine() is faster than sending Fingerprint
414 // through the StableHasher (at least as long as StableHasher
415 // is so slow).
416 hash: self.current.anon_id_seed.combine(hasher.finish()).into(),
417 };
418
419 // The DepNodes generated by the process above are not unique. 2 queries could
420 // have exactly the same dependencies. However, deserialization does not handle
421 // duplicated nodes, so we do the deduplication here directly.
422 //
423 // As anonymous nodes are a small quantity compared to the full dep-graph, the
424 // memory impact of this `anon_node_to_index` map remains tolerable, and helps
425 // us avoid useless growth of the graph with almost-equivalent nodes.
426 self.current.anon_node_to_index.get_or_insert_with(target_dep_node, || {
427 self.current.alloc_new_node(target_dep_node, reads, Fingerprint::ZERO)
428 })
429 }
430 };
431
432 (result, dep_node_index)
433 }
434
435 /// Intern the new `DepNode` with the dependencies up-to-now.
436 fn hash_result_and_alloc_node<Ctxt: DepContext<Deps = D>, R>(
437 &self,
438 cx: &Ctxt,
439 node: DepNode,
440 edges: EdgesVec,
441 result: &R,
442 hash_result: Option<fn(&mut StableHashingContext<'_>, &R) -> Fingerprint>,
443 ) -> DepNodeIndex {
444 let hashing_timer = cx.profiler().incr_result_hashing();
445 let current_fingerprint = hash_result.map(|hash_result| {
446 cx.with_stable_hashing_context(|mut hcx| hash_result(&mut hcx, result))
447 });
448 let dep_node_index = self.alloc_and_color_node(node, edges, current_fingerprint);
449 hashing_timer.finish_with_query_invocation_id(dep_node_index.into());
450 dep_node_index
451 }
452}
453
454impl<D: Deps> DepGraph<D> {
455 #[inline]
456 pub fn read_index(&self, dep_node_index: DepNodeIndex) {
457 if let Some(ref data) = self.data {
458 D::read_deps(|task_deps| {
459 let mut task_deps = match task_deps {
460 TaskDepsRef::Allow(deps) => deps.lock(),
461 TaskDepsRef::EvalAlways => {
462 // We don't need to record dependencies of eval_always
463 // queries. They are re-evaluated unconditionally anyway.
464 return;
465 }
466 TaskDepsRef::Ignore => return,
467 TaskDepsRef::Forbid => {
468 // Reading is forbidden in this context. ICE with a useful error message.
469 panic_on_forbidden_read(data, dep_node_index)
470 }
471 };
472 let task_deps = &mut *task_deps;
473
474 if cfg!(debug_assertions) {
475 data.current.total_read_count.fetch_add(1, Ordering::Relaxed);
476 }
477
478 // Has `dep_node_index` been seen before? Use either a linear scan or a hashset
479 // lookup to determine this. See `TaskDeps::read_set` for details.
480 let new_read = if task_deps.reads.len() <= TaskDeps::LINEAR_SCAN_MAX {
481 !task_deps.reads.contains(&dep_node_index)
482 } else {
483 task_deps.read_set.insert(dep_node_index)
484 };
485 if new_read {
486 task_deps.reads.push(dep_node_index);
487 if task_deps.reads.len() == TaskDeps::LINEAR_SCAN_MAX + 1 {
488 // Fill `read_set` with what we have so far. Future lookups will use it.
489 task_deps.read_set.extend(task_deps.reads.iter().copied());
490 }
491
492 #[cfg(debug_assertions)]
493 {
494 if let Some(target) = task_deps.node
495 && let Some(ref forbidden_edge) = data.current.forbidden_edge
496 {
497 let src = forbidden_edge.index_to_node.lock()[&dep_node_index];
498 if forbidden_edge.test(&src, &target) {
499 panic!("forbidden edge {:?} -> {:?} created", src, target)
500 }
501 }
502 }
503 } else if cfg!(debug_assertions) {
504 data.current.total_duplicate_read_count.fetch_add(1, Ordering::Relaxed);
505 }
506 })
507 }
508 }
509
510 /// This encodes a diagnostic by creating a node with an unique index and associating
511 /// `diagnostic` with it, for use in the next session.
512 #[inline]
513 pub fn record_diagnostic<Qcx: QueryContext>(&self, qcx: Qcx, diagnostic: &DiagInner) {
514 if let Some(ref data) = self.data {
515 D::read_deps(|task_deps| match task_deps {
516 TaskDepsRef::EvalAlways | TaskDepsRef::Ignore => return,
517 TaskDepsRef::Forbid | TaskDepsRef::Allow(..) => {
518 self.read_index(data.encode_diagnostic(qcx, diagnostic));
519 }
520 })
521 }
522 }
523 /// This forces a diagnostic node green by running its side effect. `prev_index` would
524 /// refer to a node created used `encode_diagnostic` in the previous session.
525 #[inline]
526 pub fn force_diagnostic_node<Qcx: QueryContext>(
527 &self,
528 qcx: Qcx,
529 prev_index: SerializedDepNodeIndex,
530 ) {
531 if let Some(ref data) = self.data {
532 data.force_diagnostic_node(qcx, prev_index);
533 }
534 }
535
536 /// Create a node when we force-feed a value into the query cache.
537 /// This is used to remove cycles during type-checking const generic parameters.
538 ///
539 /// As usual in the query system, we consider the current state of the calling query
540 /// only depends on the list of dependencies up to now. As a consequence, the value
541 /// that this query gives us can only depend on those dependencies too. Therefore,
542 /// it is sound to use the current dependency set for the created node.
543 ///
544 /// During replay, the order of the nodes is relevant in the dependency graph.
545 /// So the unchanged replay will mark the caller query before trying to mark this one.
546 /// If there is a change to report, the caller query will be re-executed before this one.
547 ///
548 /// FIXME: If the code is changed enough for this node to be marked before requiring the
549 /// caller's node, we suppose that those changes will be enough to mark this node red and
550 /// force a recomputation using the "normal" way.
551 pub fn with_feed_task<Ctxt: DepContext<Deps = D>, R: Debug>(
552 &self,
553 node: DepNode,
554 cx: Ctxt,
555 result: &R,
556 hash_result: Option<fn(&mut StableHashingContext<'_>, &R) -> Fingerprint>,
557 ) -> DepNodeIndex {
558 if let Some(data) = self.data.as_ref() {
559 // The caller query has more dependencies than the node we are creating. We may
560 // encounter a case where this created node is marked as green, but the caller query is
561 // subsequently marked as red or recomputed. In this case, we will end up feeding a
562 // value to an existing node.
563 //
564 // For sanity, we still check that the loaded stable hash and the new one match.
565 if let Some(prev_index) = data.previous.node_to_index_opt(&node) {
566 let dep_node_index = data.colors.current(prev_index);
567 if let Some(dep_node_index) = dep_node_index {
568 crate::query::incremental_verify_ich(
569 cx,
570 data,
571 result,
572 prev_index,
573 hash_result,
574 |value| format!("{value:?}"),
575 );
576
577 #[cfg(debug_assertions)]
578 if hash_result.is_some() {
579 data.current.record_edge(
580 dep_node_index,
581 node,
582 data.prev_fingerprint_of(prev_index),
583 );
584 }
585
586 return dep_node_index;
587 }
588 }
589
590 let mut edges = EdgesVec::new();
591 D::read_deps(|task_deps| match task_deps {
592 TaskDepsRef::Allow(deps) => edges.extend(deps.lock().reads.iter().copied()),
593 TaskDepsRef::EvalAlways => {
594 edges.push(DepNodeIndex::FOREVER_RED_NODE);
595 }
596 TaskDepsRef::Ignore => {}
597 TaskDepsRef::Forbid => {
598 panic!("Cannot summarize when dependencies are not recorded.")
599 }
600 });
601
602 data.hash_result_and_alloc_node(&cx, node, edges, result, hash_result)
603 } else {
604 // Incremental compilation is turned off. We just execute the task
605 // without tracking. We still provide a dep-node index that uniquely
606 // identifies the task so that we have a cheap way of referring to
607 // the query for self-profiling.
608 self.next_virtual_depnode_index()
609 }
610 }
611}
612
613impl<D: Deps> DepGraphData<D> {
614 fn assert_dep_node_not_yet_allocated_in_current_session<S: std::fmt::Display>(
615 &self,
616 dep_node: &DepNode,
617 msg: impl FnOnce() -> S,
618 ) {
619 if let Some(prev_index) = self.previous.node_to_index_opt(dep_node) {
620 let current = self.colors.get(prev_index);
621 assert_matches!(current, DepNodeColor::Unknown, "{}", msg())
622 } else if let Some(nodes_in_current_session) = &self.current.nodes_in_current_session {
623 outline(|| {
624 let seen = nodes_in_current_session.lock().contains_key(dep_node);
625 assert!(!seen, "{}", msg());
626 });
627 }
628 }
629
630 fn node_color(&self, dep_node: &DepNode) -> DepNodeColor {
631 if let Some(prev_index) = self.previous.node_to_index_opt(dep_node) {
632 self.colors.get(prev_index)
633 } else {
634 // This is a node that did not exist in the previous compilation session.
635 DepNodeColor::Unknown
636 }
637 }
638
639 /// Returns true if the given node has been marked as green during the
640 /// current compilation session. Used in various assertions
641 #[inline]
642 pub(crate) fn is_index_green(&self, prev_index: SerializedDepNodeIndex) -> bool {
643 matches!(self.colors.get(prev_index), DepNodeColor::Green(_))
644 }
645
646 #[inline]
647 pub(crate) fn prev_fingerprint_of(&self, prev_index: SerializedDepNodeIndex) -> Fingerprint {
648 self.previous.fingerprint_by_index(prev_index)
649 }
650
651 #[inline]
652 pub(crate) fn prev_node_of(&self, prev_index: SerializedDepNodeIndex) -> DepNode {
653 self.previous.index_to_node(prev_index)
654 }
655
656 pub(crate) fn mark_debug_loaded_from_disk(&self, dep_node: DepNode) {
657 self.debug_loaded_from_disk.lock().insert(dep_node);
658 }
659
660 /// This encodes a diagnostic by creating a node with an unique index and associating
661 /// `diagnostic` with it, for use in the next session.
662 #[inline]
663 fn encode_diagnostic<Qcx: QueryContext>(
664 &self,
665 qcx: Qcx,
666 diagnostic: &DiagInner,
667 ) -> DepNodeIndex {
668 // Use `send_new` so we get an unique index, even though the dep node is not.
669 let dep_node_index = self.current.encoder.send_new(
670 DepNode {
671 kind: D::DEP_KIND_SIDE_EFFECT,
672 hash: PackedFingerprint::from(Fingerprint::ZERO),
673 },
674 Fingerprint::ZERO,
675 // We want the side effect node to always be red so it will be forced and emit the
676 // diagnostic.
677 std::iter::once(DepNodeIndex::FOREVER_RED_NODE).collect(),
678 );
679 let side_effect = QuerySideEffect::Diagnostic(diagnostic.clone());
680 qcx.store_side_effect(dep_node_index, side_effect);
681 dep_node_index
682 }
683
684 /// This forces a diagnostic node green by running its side effect. `prev_index` would
685 /// refer to a node created used `encode_diagnostic` in the previous session.
686 #[inline]
687 fn force_diagnostic_node<Qcx: QueryContext>(
688 &self,
689 qcx: Qcx,
690 prev_index: SerializedDepNodeIndex,
691 ) {
692 D::with_deps(TaskDepsRef::Ignore, || {
693 let side_effect = qcx.load_side_effect(prev_index).unwrap();
694
695 match &side_effect {
696 QuerySideEffect::Diagnostic(diagnostic) => {
697 qcx.dep_context().sess().dcx().emit_diagnostic(diagnostic.clone());
698 }
699 }
700
701 // Use `send_and_color` as `promote_node_and_deps_to_current` expects all
702 // green dependencies. `send_and_color` will also prevent multiple nodes
703 // being encoded for concurrent calls.
704 let dep_node_index = self.current.encoder.send_and_color(
705 prev_index,
706 &self.colors,
707 DepNode {
708 kind: D::DEP_KIND_SIDE_EFFECT,
709 hash: PackedFingerprint::from(Fingerprint::ZERO),
710 },
711 Fingerprint::ZERO,
712 std::iter::once(DepNodeIndex::FOREVER_RED_NODE).collect(),
713 true,
714 );
715 // This will just overwrite the same value for concurrent calls.
716 qcx.store_side_effect(dep_node_index, side_effect);
717 })
718 }
719
720 fn alloc_and_color_node(
721 &self,
722 key: DepNode,
723 edges: EdgesVec,
724 fingerprint: Option<Fingerprint>,
725 ) -> DepNodeIndex {
726 if let Some(prev_index) = self.previous.node_to_index_opt(&key) {
727 // Determine the color and index of the new `DepNode`.
728 let is_green = if let Some(fingerprint) = fingerprint {
729 if fingerprint == self.previous.fingerprint_by_index(prev_index) {
730 // This is a green node: it existed in the previous compilation,
731 // its query was re-executed, and it has the same result as before.
732 true
733 } else {
734 // This is a red node: it existed in the previous compilation, its query
735 // was re-executed, but it has a different result from before.
736 false
737 }
738 } else {
739 // This is a red node, effectively: it existed in the previous compilation
740 // session, its query was re-executed, but it doesn't compute a result hash
741 // (i.e. it represents a `no_hash` query), so we have no way of determining
742 // whether or not the result was the same as before.
743 false
744 };
745
746 let fingerprint = fingerprint.unwrap_or(Fingerprint::ZERO);
747
748 let dep_node_index = self.current.encoder.send_and_color(
749 prev_index,
750 &self.colors,
751 key,
752 fingerprint,
753 edges,
754 is_green,
755 );
756
757 self.current.record_node(dep_node_index, key, fingerprint);
758
759 dep_node_index
760 } else {
761 self.current.alloc_new_node(key, edges, fingerprint.unwrap_or(Fingerprint::ZERO))
762 }
763 }
764
765 fn promote_node_and_deps_to_current(&self, prev_index: SerializedDepNodeIndex) -> DepNodeIndex {
766 self.current.debug_assert_not_in_new_nodes(&self.previous, prev_index);
767
768 let dep_node_index = self.current.encoder.send_promoted(prev_index, &self.colors);
769
770 #[cfg(debug_assertions)]
771 self.current.record_edge(
772 dep_node_index,
773 self.previous.index_to_node(prev_index),
774 self.previous.fingerprint_by_index(prev_index),
775 );
776
777 dep_node_index
778 }
779}
780
781impl<D: Deps> DepGraph<D> {
782 /// Checks whether a previous work product exists for `v` and, if
783 /// so, return the path that leads to it. Used to skip doing work.
784 pub fn previous_work_product(&self, v: &WorkProductId) -> Option<WorkProduct> {
785 self.data.as_ref().and_then(|data| data.previous_work_products.get(v).cloned())
786 }
787
788 /// Access the map of work-products created during the cached run. Only
789 /// used during saving of the dep-graph.
790 pub fn previous_work_products(&self) -> &WorkProductMap {
791 &self.data.as_ref().unwrap().previous_work_products
792 }
793
794 pub fn debug_was_loaded_from_disk(&self, dep_node: DepNode) -> bool {
795 self.data.as_ref().unwrap().debug_loaded_from_disk.lock().contains(&dep_node)
796 }
797
798 #[cfg(debug_assertions)]
799 #[inline(always)]
800 pub(crate) fn register_dep_node_debug_str<F>(&self, dep_node: DepNode, debug_str_gen: F)
801 where
802 F: FnOnce() -> String,
803 {
804 let dep_node_debug = &self.data.as_ref().unwrap().dep_node_debug;
805
806 if dep_node_debug.borrow().contains_key(&dep_node) {
807 return;
808 }
809 let debug_str = self.with_ignore(debug_str_gen);
810 dep_node_debug.borrow_mut().insert(dep_node, debug_str);
811 }
812
813 pub fn dep_node_debug_str(&self, dep_node: DepNode) -> Option<String> {
814 self.data.as_ref()?.dep_node_debug.borrow().get(&dep_node).cloned()
815 }
816
817 fn node_color(&self, dep_node: &DepNode) -> DepNodeColor {
818 if let Some(ref data) = self.data {
819 return data.node_color(dep_node);
820 }
821
822 DepNodeColor::Unknown
823 }
824
825 pub fn try_mark_green<Qcx: QueryContext<Deps = D>>(
826 &self,
827 qcx: Qcx,
828 dep_node: &DepNode,
829 ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
830 self.data().and_then(|data| data.try_mark_green(qcx, dep_node))
831 }
832}
833
834impl<D: Deps> DepGraphData<D> {
835 /// Try to mark a node index for the node dep_node.
836 ///
837 /// A node will have an index, when it's already been marked green, or when we can mark it
838 /// green. This function will mark the current task as a reader of the specified node, when
839 /// a node index can be found for that node.
840 pub(crate) fn try_mark_green<Qcx: QueryContext<Deps = D>>(
841 &self,
842 qcx: Qcx,
843 dep_node: &DepNode,
844 ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
845 debug_assert!(!qcx.dep_context().is_eval_always(dep_node.kind));
846
847 // Return None if the dep node didn't exist in the previous session
848 let prev_index = self.previous.node_to_index_opt(dep_node)?;
849
850 match self.colors.get(prev_index) {
851 DepNodeColor::Green(dep_node_index) => Some((prev_index, dep_node_index)),
852 DepNodeColor::Red => None,
853 DepNodeColor::Unknown => {
854 // This DepNode and the corresponding query invocation existed
855 // in the previous compilation session too, so we can try to
856 // mark it as green by recursively marking all of its
857 // dependencies green.
858 self.try_mark_previous_green(qcx, prev_index, dep_node, None)
859 .map(|dep_node_index| (prev_index, dep_node_index))
860 }
861 }
862 }
863
864 #[instrument(skip(self, qcx, parent_dep_node_index, frame), level = "debug")]
865 fn try_mark_parent_green<Qcx: QueryContext<Deps = D>>(
866 &self,
867 qcx: Qcx,
868 parent_dep_node_index: SerializedDepNodeIndex,
869 frame: &MarkFrame<'_>,
870 ) -> Option<()> {
871 let get_dep_dep_node = || self.previous.index_to_node(parent_dep_node_index);
872
873 match self.colors.get(parent_dep_node_index) {
874 DepNodeColor::Green(_) => {
875 // This dependency has been marked as green before, we are
876 // still fine and can continue with checking the other
877 // dependencies.
878 //
879 // This path is extremely hot. We don't want to get the
880 // `dep_dep_node` unless it's necessary. Hence the
881 // `get_dep_dep_node` closure.
882 debug!("dependency {:?} was immediately green", get_dep_dep_node());
883 return Some(());
884 }
885 DepNodeColor::Red => {
886 // We found a dependency the value of which has changed
887 // compared to the previous compilation session. We cannot
888 // mark the DepNode as green and also don't need to bother
889 // with checking any of the other dependencies.
890 debug!("dependency {:?} was immediately red", get_dep_dep_node());
891 return None;
892 }
893 DepNodeColor::Unknown => {}
894 }
895
896 let dep_dep_node = &get_dep_dep_node();
897
898 // We don't know the state of this dependency. If it isn't
899 // an eval_always node, let's try to mark it green recursively.
900 if !qcx.dep_context().is_eval_always(dep_dep_node.kind) {
901 debug!(
902 "state of dependency {:?} ({}) is unknown, trying to mark it green",
903 dep_dep_node, dep_dep_node.hash,
904 );
905
906 let node_index =
907 self.try_mark_previous_green(qcx, parent_dep_node_index, dep_dep_node, Some(frame));
908
909 if node_index.is_some() {
910 debug!("managed to MARK dependency {dep_dep_node:?} as green");
911 return Some(());
912 }
913 }
914
915 // We failed to mark it green, so we try to force the query.
916 debug!("trying to force dependency {dep_dep_node:?}");
917 if !qcx.dep_context().try_force_from_dep_node(*dep_dep_node, parent_dep_node_index, frame) {
918 // The DepNode could not be forced.
919 debug!("dependency {dep_dep_node:?} could not be forced");
920 return None;
921 }
922
923 match self.colors.get(parent_dep_node_index) {
924 DepNodeColor::Green(_) => {
925 debug!("managed to FORCE dependency {dep_dep_node:?} to green");
926 return Some(());
927 }
928 DepNodeColor::Red => {
929 debug!("dependency {dep_dep_node:?} was red after forcing");
930 return None;
931 }
932 DepNodeColor::Unknown => {}
933 }
934
935 if let None = qcx.dep_context().sess().dcx().has_errors_or_delayed_bugs() {
936 panic!("try_mark_previous_green() - Forcing the DepNode should have set its color")
937 }
938
939 // If the query we just forced has resulted in
940 // some kind of compilation error, we cannot rely on
941 // the dep-node color having been properly updated.
942 // This means that the query system has reached an
943 // invalid state. We let the compiler continue (by
944 // returning `None`) so it can emit error messages
945 // and wind down, but rely on the fact that this
946 // invalid state will not be persisted to the
947 // incremental compilation cache because of
948 // compilation errors being present.
949 debug!("dependency {dep_dep_node:?} resulted in compilation error");
950 return None;
951 }
952
953 /// Try to mark a dep-node which existed in the previous compilation session as green.
954 #[instrument(skip(self, qcx, prev_dep_node_index, frame), level = "debug")]
955 fn try_mark_previous_green<Qcx: QueryContext<Deps = D>>(
956 &self,
957 qcx: Qcx,
958 prev_dep_node_index: SerializedDepNodeIndex,
959 dep_node: &DepNode,
960 frame: Option<&MarkFrame<'_>>,
961 ) -> Option<DepNodeIndex> {
962 let frame = MarkFrame { index: prev_dep_node_index, parent: frame };
963
964 // We never try to mark eval_always nodes as green
965 debug_assert!(!qcx.dep_context().is_eval_always(dep_node.kind));
966
967 debug_assert_eq!(self.previous.index_to_node(prev_dep_node_index), *dep_node);
968
969 let prev_deps = self.previous.edge_targets_from(prev_dep_node_index);
970
971 for dep_dep_node_index in prev_deps {
972 self.try_mark_parent_green(qcx, dep_dep_node_index, &frame)?;
973 }
974
975 // If we got here without hitting a `return` that means that all
976 // dependencies of this DepNode could be marked as green. Therefore we
977 // can also mark this DepNode as green.
978
979 // There may be multiple threads trying to mark the same dep node green concurrently
980
981 // We allocating an entry for the node in the current dependency graph and
982 // adding all the appropriate edges imported from the previous graph
983 let dep_node_index = self.promote_node_and_deps_to_current(prev_dep_node_index);
984
985 // ... and finally storing a "Green" entry in the color map.
986 // Multiple threads can all write the same color here
987
988 debug!("successfully marked {dep_node:?} as green");
989 Some(dep_node_index)
990 }
991}
992
993impl<D: Deps> DepGraph<D> {
994 /// Returns true if the given node has been marked as red during the
995 /// current compilation session. Used in various assertions
996 pub fn is_red(&self, dep_node: &DepNode) -> bool {
997 matches!(self.node_color(dep_node), DepNodeColor::Red)
998 }
999
1000 /// Returns true if the given node has been marked as green during the
1001 /// current compilation session. Used in various assertions
1002 pub fn is_green(&self, dep_node: &DepNode) -> bool {
1003 matches!(self.node_color(dep_node), DepNodeColor::Green(_))
1004 }
1005
1006 pub fn assert_dep_node_not_yet_allocated_in_current_session<S: std::fmt::Display>(
1007 &self,
1008 dep_node: &DepNode,
1009 msg: impl FnOnce() -> S,
1010 ) {
1011 if let Some(data) = &self.data {
1012 data.assert_dep_node_not_yet_allocated_in_current_session(dep_node, msg)
1013 }
1014 }
1015
1016 /// This method loads all on-disk cacheable query results into memory, so
1017 /// they can be written out to the new cache file again. Most query results
1018 /// will already be in memory but in the case where we marked something as
1019 /// green but then did not need the value, that value will never have been
1020 /// loaded from disk.
1021 ///
1022 /// This method will only load queries that will end up in the disk cache.
1023 /// Other queries will not be executed.
1024 pub fn exec_cache_promotions<Tcx: DepContext>(&self, tcx: Tcx) {
1025 let _prof_timer = tcx.profiler().generic_activity("incr_comp_query_cache_promotion");
1026
1027 let data = self.data.as_ref().unwrap();
1028 for prev_index in data.colors.values.indices() {
1029 match data.colors.get(prev_index) {
1030 DepNodeColor::Green(_) => {
1031 let dep_node = data.previous.index_to_node(prev_index);
1032 tcx.try_load_from_on_disk_cache(dep_node);
1033 }
1034 DepNodeColor::Unknown | DepNodeColor::Red => {
1035 // We can skip red nodes because a node can only be marked
1036 // as red if the query result was recomputed and thus is
1037 // already in memory.
1038 }
1039 }
1040 }
1041 }
1042
1043 pub fn finish_encoding(&self) -> FileEncodeResult {
1044 if let Some(data) = &self.data { data.current.encoder.finish(&data.current) } else { Ok(0) }
1045 }
1046
1047 pub(crate) fn next_virtual_depnode_index(&self) -> DepNodeIndex {
1048 debug_assert!(self.data.is_none());
1049 let index = self.virtual_dep_node_index.fetch_add(1, Ordering::Relaxed);
1050 DepNodeIndex::from_u32(index)
1051 }
1052}
1053
1054/// A "work product" is an intermediate result that we save into the
1055/// incremental directory for later re-use. The primary example are
1056/// the object files that we save for each partition at code
1057/// generation time.
1058///
1059/// Each work product is associated with a dep-node, representing the
1060/// process that produced the work-product. If that dep-node is found
1061/// to be dirty when we load up, then we will delete the work-product
1062/// at load time. If the work-product is found to be clean, then we
1063/// will keep a record in the `previous_work_products` list.
1064///
1065/// In addition, work products have an associated hash. This hash is
1066/// an extra hash that can be used to decide if the work-product from
1067/// a previous compilation can be re-used (in addition to the dirty
1068/// edges check).
1069///
1070/// As the primary example, consider the object files we generate for
1071/// each partition. In the first run, we create partitions based on
1072/// the symbols that need to be compiled. For each partition P, we
1073/// hash the symbols in P and create a `WorkProduct` record associated
1074/// with `DepNode::CodegenUnit(P)`; the hash is the set of symbols
1075/// in P.
1076///
1077/// The next time we compile, if the `DepNode::CodegenUnit(P)` is
1078/// judged to be clean (which means none of the things we read to
1079/// generate the partition were found to be dirty), it will be loaded
1080/// into previous work products. We will then regenerate the set of
1081/// symbols in the partition P and hash them (note that new symbols
1082/// may be added -- for example, new monomorphizations -- even if
1083/// nothing in P changed!). We will compare that hash against the
1084/// previous hash. If it matches up, we can reuse the object file.
1085#[derive(Clone, Debug, Encodable, Decodable)]
1086pub struct WorkProduct {
1087 pub cgu_name: String,
1088 /// Saved files associated with this CGU. In each key/value pair, the value is the path to the
1089 /// saved file and the key is some identifier for the type of file being saved.
1090 ///
1091 /// By convention, file extensions are currently used as identifiers, i.e. the key "o" maps to
1092 /// the object file's path, and "dwo" to the dwarf object file's path.
1093 pub saved_files: UnordMap<String, String>,
1094}
1095
1096pub type WorkProductMap = UnordMap<WorkProductId, WorkProduct>;
1097
1098// Index type for `DepNodeData`'s edges.
1099rustc_index::newtype_index! {
1100 struct EdgeIndex {}
1101}
1102
1103/// `CurrentDepGraph` stores the dependency graph for the current session. It
1104/// will be populated as we run queries or tasks. We never remove nodes from the
1105/// graph: they are only added.
1106///
1107/// The nodes in it are identified by a `DepNodeIndex`. We avoid keeping the nodes
1108/// in memory. This is important, because these graph structures are some of the
1109/// largest in the compiler.
1110///
1111/// For this reason, we avoid storing `DepNode`s more than once as map
1112/// keys. The `anon_node_to_index` map only contains nodes of anonymous queries not in the previous
1113/// graph, and we map nodes in the previous graph to indices via a two-step
1114/// mapping. `SerializedDepGraph` maps from `DepNode` to `SerializedDepNodeIndex`,
1115/// and the `prev_index_to_index` vector (which is more compact and faster than
1116/// using a map) maps from `SerializedDepNodeIndex` to `DepNodeIndex`.
1117///
1118/// This struct uses three locks internally. The `data`, `anon_node_to_index`,
1119/// and `prev_index_to_index` fields are locked separately. Operations that take
1120/// a `DepNodeIndex` typically just access the `data` field.
1121///
1122/// We only need to manipulate at most two locks simultaneously:
1123/// `anon_node_to_index` and `data`, or `prev_index_to_index` and `data`. When
1124/// manipulating both, we acquire `anon_node_to_index` or `prev_index_to_index`
1125/// first, and `data` second.
1126pub(super) struct CurrentDepGraph<D: Deps> {
1127 encoder: GraphEncoder<D>,
1128 anon_node_to_index: ShardedHashMap<DepNode, DepNodeIndex>,
1129
1130 /// This is used to verify that fingerprints do not change between the creation of a node
1131 /// and its recomputation.
1132 #[cfg(debug_assertions)]
1133 fingerprints: Lock<IndexVec<DepNodeIndex, Option<Fingerprint>>>,
1134
1135 /// Used to trap when a specific edge is added to the graph.
1136 /// This is used for debug purposes and is only active with `debug_assertions`.
1137 #[cfg(debug_assertions)]
1138 forbidden_edge: Option<EdgeFilter>,
1139
1140 /// Used to verify the absence of hash collisions among DepNodes.
1141 /// This field is only `Some` if the `-Z incremental_verify_ich` option is present
1142 /// or if `debug_assertions` are enabled.
1143 ///
1144 /// The map contains all DepNodes that have been allocated in the current session so far.
1145 nodes_in_current_session: Option<Lock<FxHashMap<DepNode, DepNodeIndex>>>,
1146
1147 /// Anonymous `DepNode`s are nodes whose IDs we compute from the list of
1148 /// their edges. This has the beneficial side-effect that multiple anonymous
1149 /// nodes can be coalesced into one without changing the semantics of the
1150 /// dependency graph. However, the merging of nodes can lead to a subtle
1151 /// problem during red-green marking: The color of an anonymous node from
1152 /// the current session might "shadow" the color of the node with the same
1153 /// ID from the previous session. In order to side-step this problem, we make
1154 /// sure that anonymous `NodeId`s allocated in different sessions don't overlap.
1155 /// This is implemented by mixing a session-key into the ID fingerprint of
1156 /// each anon node. The session-key is a hash of the number of previous sessions.
1157 anon_id_seed: Fingerprint,
1158
1159 /// These are simple counters that are for profiling and
1160 /// debugging and only active with `debug_assertions`.
1161 pub(super) total_read_count: AtomicU64,
1162 pub(super) total_duplicate_read_count: AtomicU64,
1163}
1164
1165impl<D: Deps> CurrentDepGraph<D> {
1166 fn new(
1167 session: &Session,
1168 prev_graph_node_count: usize,
1169 encoder: FileEncoder,
1170 previous: Arc<SerializedDepGraph>,
1171 ) -> Self {
1172 let mut stable_hasher = StableHasher::new();
1173 previous.session_count().hash(&mut stable_hasher);
1174 let anon_id_seed = stable_hasher.finish();
1175
1176 #[cfg(debug_assertions)]
1177 let forbidden_edge = match env::var("RUST_FORBID_DEP_GRAPH_EDGE") {
1178 Ok(s) => match EdgeFilter::new(&s) {
1179 Ok(f) => Some(f),
1180 Err(err) => panic!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {}", err),
1181 },
1182 Err(_) => None,
1183 };
1184
1185 let new_node_count_estimate = 102 * prev_graph_node_count / 100 + 200;
1186
1187 let new_node_dbg =
1188 session.opts.unstable_opts.incremental_verify_ich || cfg!(debug_assertions);
1189
1190 CurrentDepGraph {
1191 encoder: GraphEncoder::new(session, encoder, prev_graph_node_count, previous),
1192 anon_node_to_index: ShardedHashMap::with_capacity(
1193 // FIXME: The count estimate is off as anon nodes are only a portion of the nodes.
1194 new_node_count_estimate / sharded::shards(),
1195 ),
1196 anon_id_seed,
1197 #[cfg(debug_assertions)]
1198 forbidden_edge,
1199 #[cfg(debug_assertions)]
1200 fingerprints: Lock::new(IndexVec::from_elem_n(None, new_node_count_estimate)),
1201 nodes_in_current_session: new_node_dbg.then(|| {
1202 Lock::new(FxHashMap::with_capacity_and_hasher(
1203 new_node_count_estimate,
1204 Default::default(),
1205 ))
1206 }),
1207 total_read_count: AtomicU64::new(0),
1208 total_duplicate_read_count: AtomicU64::new(0),
1209 }
1210 }
1211
1212 #[cfg(debug_assertions)]
1213 fn record_edge(&self, dep_node_index: DepNodeIndex, key: DepNode, fingerprint: Fingerprint) {
1214 if let Some(forbidden_edge) = &self.forbidden_edge {
1215 forbidden_edge.index_to_node.lock().insert(dep_node_index, key);
1216 }
1217 let previous = *self.fingerprints.lock().get_or_insert_with(dep_node_index, || fingerprint);
1218 assert_eq!(previous, fingerprint, "Unstable fingerprints for {:?}", key);
1219 }
1220
1221 #[inline(always)]
1222 fn record_node(
1223 &self,
1224 dep_node_index: DepNodeIndex,
1225 key: DepNode,
1226 _current_fingerprint: Fingerprint,
1227 ) {
1228 #[cfg(debug_assertions)]
1229 self.record_edge(dep_node_index, key, _current_fingerprint);
1230
1231 if let Some(ref nodes_in_current_session) = self.nodes_in_current_session {
1232 outline(|| {
1233 if nodes_in_current_session.lock().insert(key, dep_node_index).is_some() {
1234 panic!("Found duplicate dep-node {key:?}");
1235 }
1236 });
1237 }
1238 }
1239
1240 /// Writes the node to the current dep-graph and allocates a `DepNodeIndex` for it.
1241 /// Assumes that this is a node that has no equivalent in the previous dep-graph.
1242 #[inline(always)]
1243 fn alloc_new_node(
1244 &self,
1245 key: DepNode,
1246 edges: EdgesVec,
1247 current_fingerprint: Fingerprint,
1248 ) -> DepNodeIndex {
1249 let dep_node_index = self.encoder.send_new(key, current_fingerprint, edges);
1250
1251 self.record_node(dep_node_index, key, current_fingerprint);
1252
1253 dep_node_index
1254 }
1255
1256 #[inline]
1257 fn debug_assert_not_in_new_nodes(
1258 &self,
1259 prev_graph: &SerializedDepGraph,
1260 prev_index: SerializedDepNodeIndex,
1261 ) {
1262 if let Some(ref nodes_in_current_session) = self.nodes_in_current_session {
1263 debug_assert!(
1264 !nodes_in_current_session
1265 .lock()
1266 .contains_key(&prev_graph.index_to_node(prev_index)),
1267 "node from previous graph present in new node collection"
1268 );
1269 }
1270 }
1271}
1272
1273#[derive(Debug, Clone, Copy)]
1274pub enum TaskDepsRef<'a> {
1275 /// New dependencies can be added to the
1276 /// `TaskDeps`. This is used when executing a 'normal' query
1277 /// (no `eval_always` modifier)
1278 Allow(&'a Lock<TaskDeps>),
1279 /// This is used when executing an `eval_always` query. We don't
1280 /// need to track dependencies for a query that's always
1281 /// re-executed -- but we need to know that this is an `eval_always`
1282 /// query in order to emit dependencies to `DepNodeIndex::FOREVER_RED_NODE`
1283 /// when directly feeding other queries.
1284 EvalAlways,
1285 /// New dependencies are ignored. This is also used for `dep_graph.with_ignore`.
1286 Ignore,
1287 /// Any attempt to add new dependencies will cause a panic.
1288 /// This is used when decoding a query result from disk,
1289 /// to ensure that the decoding process doesn't itself
1290 /// require the execution of any queries.
1291 Forbid,
1292}
1293
1294#[derive(Debug)]
1295pub struct TaskDeps {
1296 #[cfg(debug_assertions)]
1297 node: Option<DepNode>,
1298
1299 /// A vector of `DepNodeIndex`, basically.
1300 reads: EdgesVec,
1301
1302 /// When adding new edges to `reads` in `DepGraph::read_index` we need to determine if the edge
1303 /// has been seen before. If the number of elements in `reads` is small, we just do a linear
1304 /// scan. If the number is higher, a hashset has better perf. This field is that hashset. It's
1305 /// only used if the number of elements in `reads` exceeds `LINEAR_SCAN_MAX`.
1306 read_set: FxHashSet<DepNodeIndex>,
1307
1308 phantom_data: PhantomData<DepNode>,
1309}
1310
1311impl TaskDeps {
1312 /// See `TaskDeps::read_set` above.
1313 const LINEAR_SCAN_MAX: usize = 16;
1314
1315 #[inline]
1316 fn new(#[cfg(debug_assertions)] node: Option<DepNode>, read_set_capacity: usize) -> Self {
1317 TaskDeps {
1318 #[cfg(debug_assertions)]
1319 node,
1320 reads: EdgesVec::new(),
1321 read_set: FxHashSet::with_capacity_and_hasher(read_set_capacity, Default::default()),
1322 phantom_data: PhantomData,
1323 }
1324 }
1325}
1326
1327// A data structure that stores Option<DepNodeColor> values as a contiguous
1328// array, using one u32 per entry.
1329pub(super) struct DepNodeColorMap {
1330 values: IndexVec<SerializedDepNodeIndex, AtomicU32>,
1331}
1332
1333// All values below `COMPRESSED_RED` are green.
1334const COMPRESSED_RED: u32 = u32::MAX - 1;
1335const COMPRESSED_UNKNOWN: u32 = u32::MAX;
1336
1337impl DepNodeColorMap {
1338 fn new(size: usize) -> DepNodeColorMap {
1339 debug_assert!(COMPRESSED_RED > DepNodeIndex::MAX_AS_U32);
1340 DepNodeColorMap { values: (0..size).map(|_| AtomicU32::new(COMPRESSED_UNKNOWN)).collect() }
1341 }
1342
1343 #[inline]
1344 pub(super) fn current(&self, index: SerializedDepNodeIndex) -> Option<DepNodeIndex> {
1345 let value = self.values[index].load(Ordering::Relaxed);
1346 if value <= DepNodeIndex::MAX_AS_U32 { Some(DepNodeIndex::from_u32(value)) } else { None }
1347 }
1348
1349 /// This tries to atomically mark a node green and assign `index` as the new
1350 /// index. This returns `Ok` if `index` gets assigned, otherwise it returns
1351 /// the already allocated index in `Err`.
1352 #[inline]
1353 pub(super) fn try_mark_green(
1354 &self,
1355 prev_index: SerializedDepNodeIndex,
1356 index: DepNodeIndex,
1357 ) -> Result<(), DepNodeIndex> {
1358 let value = &self.values[prev_index];
1359 match value.compare_exchange(
1360 COMPRESSED_UNKNOWN,
1361 index.as_u32(),
1362 Ordering::Relaxed,
1363 Ordering::Relaxed,
1364 ) {
1365 Ok(_) => Ok(()),
1366 Err(v) => Err(DepNodeIndex::from_u32(v)),
1367 }
1368 }
1369
1370 #[inline]
1371 pub(super) fn get(&self, index: SerializedDepNodeIndex) -> DepNodeColor {
1372 let value = self.values[index].load(Ordering::Acquire);
1373 // Green is by far the most common case. Check for that first so we can succeed with a
1374 // single comparison.
1375 if value < COMPRESSED_RED {
1376 DepNodeColor::Green(DepNodeIndex::from_u32(value))
1377 } else if value == COMPRESSED_RED {
1378 DepNodeColor::Red
1379 } else {
1380 debug_assert_eq!(value, COMPRESSED_UNKNOWN);
1381 DepNodeColor::Unknown
1382 }
1383 }
1384
1385 #[inline]
1386 pub(super) fn insert_red(&self, index: SerializedDepNodeIndex) {
1387 self.values[index].store(COMPRESSED_RED, Ordering::Release)
1388 }
1389}
1390
1391#[inline(never)]
1392#[cold]
1393pub(crate) fn print_markframe_trace<D: Deps>(graph: &DepGraph<D>, frame: &MarkFrame<'_>) {
1394 let data = graph.data.as_ref().unwrap();
1395
1396 eprintln!("there was a panic while trying to force a dep node");
1397 eprintln!("try_mark_green dep node stack:");
1398
1399 let mut i = 0;
1400 let mut current = Some(frame);
1401 while let Some(frame) = current {
1402 let node = data.previous.index_to_node(frame.index);
1403 eprintln!("#{i} {node:?}");
1404 current = frame.parent;
1405 i += 1;
1406 }
1407
1408 eprintln!("end of try_mark_green dep node stack");
1409}
1410
1411#[cold]
1412#[inline(never)]
1413fn panic_on_forbidden_read<D: Deps>(data: &DepGraphData<D>, dep_node_index: DepNodeIndex) -> ! {
1414 // We have to do an expensive reverse-lookup of the DepNode that
1415 // corresponds to `dep_node_index`, but that's OK since we are about
1416 // to ICE anyway.
1417 let mut dep_node = None;
1418
1419 // First try to find the dep node among those that already existed in the
1420 // previous session and has been marked green
1421 for prev_index in data.colors.values.indices() {
1422 if data.colors.current(prev_index) == Some(dep_node_index) {
1423 dep_node = Some(data.previous.index_to_node(prev_index));
1424 break;
1425 }
1426 }
1427
1428 if dep_node.is_none()
1429 && let Some(nodes) = &data.current.nodes_in_current_session
1430 {
1431 // Try to find it among the nodes allocated so far in this session
1432 // This is OK, there's only ever one node result possible so this is deterministic.
1433 #[allow(rustc::potential_query_instability)]
1434 if let Some((node, _)) = nodes.lock().iter().find(|&(_, index)| *index == dep_node_index) {
1435 dep_node = Some(*node);
1436 }
1437 }
1438
1439 let dep_node = dep_node.map_or_else(
1440 || format!("with index {:?}", dep_node_index),
1441 |dep_node| format!("`{:?}`", dep_node),
1442 );
1443
1444 panic!(
1445 "Error: trying to record dependency on DepNode {dep_node} in a \
1446 context that does not allow it (e.g. during query deserialization). \
1447 The most common case of recording a dependency on a DepNode `foo` is \
1448 when the corresponding query `foo` is invoked. Invoking queries is not \
1449 allowed as part of loading something from the incremental on-disk cache. \
1450 See <https://github.com/rust-lang/rust/pull/91919>."
1451 )
1452}