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};
78use 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};
2425use 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};
3132#[derive(#[automatically_derived]
impl<D: ::core::clone::Clone + Deps> ::core::clone::Clone for DepGraph<D> {
#[inline]
fn clone(&self) -> DepGraph<D> {
DepGraph {
data: ::core::clone::Clone::clone(&self.data),
virtual_dep_node_index: ::core::clone::Clone::clone(&self.virtual_dep_node_index),
}
}
}Clone)]
33pub struct DepGraph<D: Deps> {
34 data: Option<Arc<DepGraphData<D>>>,
3536/// 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.
40virtual_dep_node_index: Arc<AtomicU32>,
41}
4243impl ::std::fmt::Debug for DepNodeIndex {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("{0}", self.as_u32()))
}
}rustc_index::newtype_index! {
44pub struct DepNodeIndex {}
45}4647// 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.
50const _: [(); 4] = [(); ::std::mem::size_of::<Option<DepNodeIndex>>()];rustc_data_structures::static_assert_size!(Option<DepNodeIndex>, 4);
5152impl DepNodeIndex {
53const SINGLETON_ZERO_DEPS_ANON_NODE: DepNodeIndex = DepNodeIndex::ZERO;
54pub const FOREVER_RED_NODE: DepNodeIndex = DepNodeIndex::from_u32(1);
55}
5657impl From<DepNodeIndex> for QueryInvocationId {
58#[inline(always)]
59fn from(dep_node_index: DepNodeIndex) -> Self {
60QueryInvocationId(dep_node_index.as_u32())
61 }
62}
6364pub struct MarkFrame<'a> {
65 index: SerializedDepNodeIndex,
66 parent: Option<&'a MarkFrame<'a>>,
67}
6869#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DepNodeColor {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DepNodeColor::Green(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Green",
&__self_0),
DepNodeColor::Red => ::core::fmt::Formatter::write_str(f, "Red"),
DepNodeColor::Unknown =>
::core::fmt::Formatter::write_str(f, "Unknown"),
}
}
}Debug)]
70pub(super) enum DepNodeColor {
71 Green(DepNodeIndex),
72 Red,
73 Unknown,
74}
7576pub(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.
81current: CurrentDepGraph<D>,
8283/// 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.
85previous: Arc<SerializedDepGraph>,
8687 colors: DepNodeColorMap,
8889/// 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.
93previous_work_products: WorkProductMap,
9495 dep_node_debug: Lock<FxHashMap<DepNode, String>>,
9697/// Used by incremental compilation tests to assert that
98 /// a particular query result was decoded from disk
99 /// (not just marked green)
100debug_loaded_from_disk: Lock<FxHashSet<DepNode>>,
101}
102103pub fn hash_result<R>(hcx: &mut StableHashingContext<'_>, result: &R) -> Fingerprint104where
105R: for<'a> HashStable<StableHashingContext<'a>>,
106{
107let mut stable_hasher = StableHasher::new();
108result.hash_stable(hcx, &mut stable_hasher);
109stable_hasher.finish()
110}
111112impl<D: Deps> DepGraph<D> {
113pub fn new(
114 session: &Session,
115 prev_graph: Arc<SerializedDepGraph>,
116 prev_work_products: WorkProductMap,
117 encoder: FileEncoder,
118 ) -> DepGraph<D> {
119let prev_graph_node_count = prev_graph.node_count();
120121let current =
122CurrentDepGraph::new(session, prev_graph_node_count, encoder, Arc::clone(&prev_graph));
123124let colors = DepNodeColorMap::new(prev_graph_node_count);
125126// Instantiate a node with zero dependencies only once for anonymous queries.
127let _green_node_index = current.alloc_new_node(
128DepNode { kind: D::DEP_KIND_ANON_ZERO_DEPS, hash: current.anon_id_seed.into() },
129EdgesVec::new(),
130Fingerprint::ZERO,
131 );
132match (&_green_node_index, &DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_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!(_green_node_index, DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE);
133134// Instantiate a dependy-less red node only once for anonymous queries.
135let red_node_index = current.alloc_new_node(
136DepNode { kind: D::DEP_KIND_RED, hash: Fingerprint::ZERO.into() },
137EdgesVec::new(),
138Fingerprint::ZERO,
139 );
140match (&red_node_index, &DepNodeIndex::FOREVER_RED_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!(red_node_index, DepNodeIndex::FOREVER_RED_NODE);
141if prev_graph_node_count > 0 {
142colors.insert_red(SerializedDepNodeIndex::from_u32(
143DepNodeIndex::FOREVER_RED_NODE.as_u32(),
144 ));
145 }
146147DepGraph {
148 data: Some(Arc::new(DepGraphData {
149 previous_work_products: prev_work_products,
150 dep_node_debug: Default::default(),
151current,
152 previous: prev_graph,
153colors,
154 debug_loaded_from_disk: Default::default(),
155 })),
156 virtual_dep_node_index: Arc::new(AtomicU32::new(0)),
157 }
158 }
159160pub fn new_disabled() -> DepGraph<D> {
161DepGraph { data: None, virtual_dep_node_index: Arc::new(AtomicU32::new(0)) }
162 }
163164#[inline]
165pub(crate) fn data(&self) -> Option<&DepGraphData<D>> {
166self.data.as_deref()
167 }
168169/// Returns `true` if we are actually building the full dep-graph, and `false` otherwise.
170#[inline]
171pub fn is_fully_enabled(&self) -> bool {
172self.data.is_some()
173 }
174175pub fn with_query(&self, f: impl Fn(&DepGraphQuery)) {
176if let Some(data) = &self.data {
177data.current.encoder.with_query(f)
178 }
179 }
180181pub fn assert_ignored(&self) {
182if let Some(..) = self.data {
183 D::read_deps(|task_deps| {
184match task_deps {
TaskDepsRef::Ignore => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"TaskDepsRef::Ignore",
::core::option::Option::Some(format_args!("expected no task dependency tracking")));
}
};assert_matches!(
185 task_deps,
186 TaskDepsRef::Ignore,
187"expected no task dependency tracking"
188);
189 })
190 }
191 }
192193pub fn with_ignore<OP, R>(&self, op: OP) -> R
194where
195OP: FnOnce() -> R,
196 {
197 D::with_deps(TaskDepsRef::Ignore, op)
198 }
199200/// 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.
246pub fn with_query_deserialization<OP, R>(&self, op: OP) -> R
247where
248OP: FnOnce() -> R,
249 {
250 D::with_deps(TaskDepsRef::Forbid, op)
251 }
252253#[inline(always)]
254pub 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) {
262match self.data() {
263Some(data) => data.with_task(key, cx, arg, task, hash_result),
264None => (task(cx, arg), self.next_virtual_depnode_index()),
265 }
266 }
267268pub 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)
274where
275OP: FnOnce() -> R,
276 {
277match self.data() {
278Some(data) => {
279let (result, index) = data.with_anon_task_inner(cx, dep_kind, op);
280self.read_index(index);
281 (result, index)
282 }
283None => (op(), self.next_virtual_depnode_index()),
284 }
285 }
286}
287288impl<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)]
317pub(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).
330self.assert_dep_node_not_yet_allocated_in_current_session(&key, || {
331::alloc::__export::must_use({
::alloc::fmt::format(format_args!("forcing query with already existing `DepNode`\n- query-key: {0:?}\n- dep-node: {1:?}",
arg, key))
})format!(
332"forcing query with already existing `DepNode`\n\
333 - query-key: {arg:?}\n\
334 - dep-node: {key:?}"
335)336 });
337338let with_deps = |task_deps| D::with_deps(task_deps, || task(cx, arg));
339let (result, edges) = if cx.dep_context().is_eval_always(key.kind) {
340 (with_deps(TaskDepsRef::EvalAlways), EdgesVec::new())
341 } else {
342let task_deps = Lock::new(TaskDeps::new(
343#[cfg(debug_assertions)]
344Some(key),
3450,
346 ));
347 (with_deps(TaskDepsRef::Allow(&task_deps)), task_deps.into_inner().reads)
348 };
349350let dcx = cx.dep_context();
351let dep_node_index = self.hash_result_and_alloc_node(dcx, key, edges, &result, hash_result);
352353 (result, dep_node_index)
354 }
355356/// 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.
367pub(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)
373where
374OP: FnOnce() -> R,
375 {
376if true {
if !!cx.is_eval_always(dep_kind) {
::core::panicking::panic("assertion failed: !cx.is_eval_always(dep_kind)")
};
};debug_assert!(!cx.is_eval_always(dep_kind));
377378// Large numbers of reads are common enough here that pre-sizing `read_set`
379 // to 128 actually helps perf on some benchmarks.
380let task_deps = Lock::new(TaskDeps::new(
381#[cfg(debug_assertions)]
382None,
383128,
384 ));
385let result = D::with_deps(TaskDepsRef::Allow(&task_deps), op);
386let task_deps = task_deps.into_inner();
387let reads = task_deps.reads;
388389let dep_node_index = match reads.len() {
3900 => {
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.
396DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE397 }
3981 => {
399// When there is only one dependency, don't bother creating a node.
400reads[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.
408let mut hasher = StableHasher::new();
409reads.hash(&mut hasher);
410411let 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).
416hash: self.current.anon_id_seed.combine(hasher.finish()).into(),
417 };
418419// 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.
426self.current.anon_node_to_index.get_or_insert_with(target_dep_node, || {
427self.current.alloc_new_node(target_dep_node, reads, Fingerprint::ZERO)
428 })
429 }
430 };
431432 (result, dep_node_index)
433 }
434435/// Intern the new `DepNode` with the dependencies up-to-now.
436fn 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 {
444let hashing_timer = cx.profiler().incr_result_hashing();
445let current_fingerprint = hash_result.map(|hash_result| {
446cx.with_stable_hashing_context(|mut hcx| hash_result(&mut hcx, result))
447 });
448let dep_node_index = self.alloc_and_color_node(node, edges, current_fingerprint);
449hashing_timer.finish_with_query_invocation_id(dep_node_index.into());
450dep_node_index451 }
452}
453454impl<D: Deps> DepGraph<D> {
455#[inline]
456pub fn read_index(&self, dep_node_index: DepNodeIndex) {
457if let Some(ref data) = self.data {
458 D::read_deps(|task_deps| {
459let 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.
464return;
465 }
466 TaskDepsRef::Ignore => return,
467 TaskDepsRef::Forbid => {
468// Reading is forbidden in this context. ICE with a useful error message.
469panic_on_forbidden_read(data, dep_node_index)
470 }
471 };
472let task_deps = &mut *task_deps;
473474if truecfg!(debug_assertions) {
475data.current.total_read_count.fetch_add(1, Ordering::Relaxed);
476 }
477478// 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.
480let new_read = if task_deps.reads.len() <= TaskDeps::LINEAR_SCAN_MAX {
481 !task_deps.reads.contains(&dep_node_index)
482 } else {
483task_deps.read_set.insert(dep_node_index)
484 };
485if new_read {
486task_deps.reads.push(dep_node_index);
487if task_deps.reads.len() == TaskDeps::LINEAR_SCAN_MAX + 1 {
488// Fill `read_set` with what we have so far. Future lookups will use it.
489task_deps.read_set.extend(task_deps.reads.iter().copied());
490 }
491492#[cfg(debug_assertions)]
493{
494if let Some(target) = task_deps.node
495 && let Some(ref forbidden_edge) = data.current.forbidden_edge
496 {
497let src = forbidden_edge.index_to_node.lock()[&dep_node_index];
498if forbidden_edge.test(&src, &target) {
499{
::core::panicking::panic_fmt(format_args!("forbidden edge {0:?} -> {1:?} created",
src, target));
}panic!("forbidden edge {:?} -> {:?} created", src, target)500 }
501 }
502 }
503 } else if truecfg!(debug_assertions) {
504data.current.total_duplicate_read_count.fetch_add(1, Ordering::Relaxed);
505 }
506 })
507 }
508 }
509510/// 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]
513pub fn record_diagnostic<Qcx: QueryContext>(&self, qcx: Qcx, diagnostic: &DiagInner) {
514if 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(..) => {
518self.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]
526pub fn force_diagnostic_node<Qcx: QueryContext>(
527&self,
528 qcx: Qcx,
529 prev_index: SerializedDepNodeIndex,
530 ) {
531if let Some(ref data) = self.data {
532data.force_diagnostic_node(qcx, prev_index);
533 }
534 }
535536/// 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.
551pub 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 {
558if 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.
565if let Some(prev_index) = data.previous.node_to_index_opt(&node) {
566let dep_node_index = data.colors.current(prev_index);
567if let Some(dep_node_index) = dep_node_index {
568crate::query::incremental_verify_ich(
569cx,
570data,
571result,
572prev_index,
573hash_result,
574 |value| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", value))
})format!("{value:?}"),
575 );
576577#[cfg(debug_assertions)]
578if hash_result.is_some() {
579data.current.record_edge(
580dep_node_index,
581node,
582data.prev_fingerprint_of(prev_index),
583 );
584 }
585586return dep_node_index;
587 }
588 }
589590let 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 => {
594edges.push(DepNodeIndex::FOREVER_RED_NODE);
595 }
596 TaskDepsRef::Ignore => {}
597 TaskDepsRef::Forbid => {
598{
::core::panicking::panic_fmt(format_args!("Cannot summarize when dependencies are not recorded."));
}panic!("Cannot summarize when dependencies are not recorded.")599 }
600 });
601602data.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.
608self.next_virtual_depnode_index()
609 }
610 }
611}
612613impl<D: Deps> DepGraphData<D> {
614fn 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 ) {
619if let Some(prev_index) = self.previous.node_to_index_opt(dep_node) {
620let current = self.colors.get(prev_index);
621match current {
DepNodeColor::Unknown => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DepNodeColor::Unknown",
::core::option::Option::Some(format_args!("{0}", msg())));
}
}assert_matches!(current, DepNodeColor::Unknown, "{}", msg())622 } else if let Some(nodes_in_current_session) = &self.current.nodes_in_current_session {
623outline(|| {
624let seen = nodes_in_current_session.lock().contains_key(dep_node);
625if !!seen { { ::core::panicking::panic_display(&msg()); } };assert!(!seen, "{}", msg());
626 });
627 }
628 }
629630fn node_color(&self, dep_node: &DepNode) -> DepNodeColor {
631if let Some(prev_index) = self.previous.node_to_index_opt(dep_node) {
632self.colors.get(prev_index)
633 } else {
634// This is a node that did not exist in the previous compilation session.
635DepNodeColor::Unknown636 }
637 }
638639/// Returns true if the given node has been marked as green during the
640 /// current compilation session. Used in various assertions
641#[inline]
642pub(crate) fn is_index_green(&self, prev_index: SerializedDepNodeIndex) -> bool {
643#[allow(non_exhaustive_omitted_patterns)] match self.colors.get(prev_index) {
DepNodeColor::Green(_) => true,
_ => false,
}matches!(self.colors.get(prev_index), DepNodeColor::Green(_))644 }
645646#[inline]
647pub(crate) fn prev_fingerprint_of(&self, prev_index: SerializedDepNodeIndex) -> Fingerprint {
648self.previous.fingerprint_by_index(prev_index)
649 }
650651#[inline]
652pub(crate) fn prev_node_of(&self, prev_index: SerializedDepNodeIndex) -> DepNode {
653self.previous.index_to_node(prev_index)
654 }
655656pub(crate) fn mark_debug_loaded_from_disk(&self, dep_node: DepNode) {
657self.debug_loaded_from_disk.lock().insert(dep_node);
658 }
659660/// 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]
663fn 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.
669let dep_node_index = self.current.encoder.send_new(
670DepNode {
671 kind: D::DEP_KIND_SIDE_EFFECT,
672 hash: PackedFingerprint::from(Fingerprint::ZERO),
673 },
674Fingerprint::ZERO,
675// We want the side effect node to always be red so it will be forced and emit the
676 // diagnostic.
677std::iter::once(DepNodeIndex::FOREVER_RED_NODE).collect(),
678 );
679let side_effect = QuerySideEffect::Diagnostic(diagnostic.clone());
680qcx.store_side_effect(dep_node_index, side_effect);
681dep_node_index682 }
683684/// 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]
687fn force_diagnostic_node<Qcx: QueryContext>(
688&self,
689 qcx: Qcx,
690 prev_index: SerializedDepNodeIndex,
691 ) {
692 D::with_deps(TaskDepsRef::Ignore, || {
693let side_effect = qcx.load_side_effect(prev_index).unwrap();
694695match &side_effect {
696 QuerySideEffect::Diagnostic(diagnostic) => {
697qcx.dep_context().sess().dcx().emit_diagnostic(diagnostic.clone());
698 }
699 }
700701// 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.
704let dep_node_index = self.current.encoder.send_and_color(
705prev_index,
706&self.colors,
707DepNode {
708 kind: D::DEP_KIND_SIDE_EFFECT,
709 hash: PackedFingerprint::from(Fingerprint::ZERO),
710 },
711Fingerprint::ZERO,
712 std::iter::once(DepNodeIndex::FOREVER_RED_NODE).collect(),
713true,
714 );
715// This will just overwrite the same value for concurrent calls.
716qcx.store_side_effect(dep_node_index, side_effect);
717 })
718 }
719720fn alloc_and_color_node(
721&self,
722 key: DepNode,
723 edges: EdgesVec,
724 fingerprint: Option<Fingerprint>,
725 ) -> DepNodeIndex {
726if let Some(prev_index) = self.previous.node_to_index_opt(&key) {
727// Determine the color and index of the new `DepNode`.
728let is_green = if let Some(fingerprint) = fingerprint {
729if 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.
732true
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.
736false
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.
743false
744};
745746let fingerprint = fingerprint.unwrap_or(Fingerprint::ZERO);
747748let dep_node_index = self.current.encoder.send_and_color(
749prev_index,
750&self.colors,
751key,
752fingerprint,
753edges,
754is_green,
755 );
756757self.current.record_node(dep_node_index, key, fingerprint);
758759dep_node_index760 } else {
761self.current.alloc_new_node(key, edges, fingerprint.unwrap_or(Fingerprint::ZERO))
762 }
763 }
764765fn promote_node_and_deps_to_current(&self, prev_index: SerializedDepNodeIndex) -> DepNodeIndex {
766self.current.debug_assert_not_in_new_nodes(&self.previous, prev_index);
767768let dep_node_index = self.current.encoder.send_promoted(prev_index, &self.colors);
769770#[cfg(debug_assertions)]
771self.current.record_edge(
772dep_node_index,
773self.previous.index_to_node(prev_index),
774self.previous.fingerprint_by_index(prev_index),
775 );
776777dep_node_index778 }
779}
780781impl<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.
784pub fn previous_work_product(&self, v: &WorkProductId) -> Option<WorkProduct> {
785self.data.as_ref().and_then(|data| data.previous_work_products.get(v).cloned())
786 }
787788/// Access the map of work-products created during the cached run. Only
789 /// used during saving of the dep-graph.
790pub fn previous_work_products(&self) -> &WorkProductMap {
791&self.data.as_ref().unwrap().previous_work_products
792 }
793794pub fn debug_was_loaded_from_disk(&self, dep_node: DepNode) -> bool {
795self.data.as_ref().unwrap().debug_loaded_from_disk.lock().contains(&dep_node)
796 }
797798pub fn debug_dep_kind_was_loaded_from_disk(&self, dep_kind: DepKind) -> bool {
799// We only check if we have a dep node corresponding to the given dep kind.
800#[allow(rustc::potential_query_instability)]
801self.data
802 .as_ref()
803 .unwrap()
804 .debug_loaded_from_disk
805 .lock()
806 .iter()
807 .any(|node| node.kind == dep_kind)
808 }
809810#[cfg(debug_assertions)]
811 #[inline(always)]
812pub(crate) fn register_dep_node_debug_str<F>(&self, dep_node: DepNode, debug_str_gen: F)
813where
814F: FnOnce() -> String,
815 {
816let dep_node_debug = &self.data.as_ref().unwrap().dep_node_debug;
817818if dep_node_debug.borrow().contains_key(&dep_node) {
819return;
820 }
821let debug_str = self.with_ignore(debug_str_gen);
822dep_node_debug.borrow_mut().insert(dep_node, debug_str);
823 }
824825pub fn dep_node_debug_str(&self, dep_node: DepNode) -> Option<String> {
826self.data.as_ref()?.dep_node_debug.borrow().get(&dep_node).cloned()
827 }
828829fn node_color(&self, dep_node: &DepNode) -> DepNodeColor {
830if let Some(ref data) = self.data {
831return data.node_color(dep_node);
832 }
833834 DepNodeColor::Unknown835 }
836837pub fn try_mark_green<Qcx: QueryContext<Deps = D>>(
838&self,
839 qcx: Qcx,
840 dep_node: &DepNode,
841 ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
842self.data().and_then(|data| data.try_mark_green(qcx, dep_node))
843 }
844}
845846impl<D: Deps> DepGraphData<D> {
847/// Try to mark a node index for the node dep_node.
848 ///
849 /// A node will have an index, when it's already been marked green, or when we can mark it
850 /// green. This function will mark the current task as a reader of the specified node, when
851 /// a node index can be found for that node.
852pub(crate) fn try_mark_green<Qcx: QueryContext<Deps = D>>(
853&self,
854 qcx: Qcx,
855 dep_node: &DepNode,
856 ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
857if true {
if !!qcx.dep_context().is_eval_always(dep_node.kind) {
::core::panicking::panic("assertion failed: !qcx.dep_context().is_eval_always(dep_node.kind)")
};
};debug_assert!(!qcx.dep_context().is_eval_always(dep_node.kind));
858859// Return None if the dep node didn't exist in the previous session
860let prev_index = self.previous.node_to_index_opt(dep_node)?;
861862match self.colors.get(prev_index) {
863 DepNodeColor::Green(dep_node_index) => Some((prev_index, dep_node_index)),
864 DepNodeColor::Red => None,
865 DepNodeColor::Unknown => {
866// This DepNode and the corresponding query invocation existed
867 // in the previous compilation session too, so we can try to
868 // mark it as green by recursively marking all of its
869 // dependencies green.
870self.try_mark_previous_green(qcx, prev_index, dep_node, None)
871 .map(|dep_node_index| (prev_index, dep_node_index))
872 }
873 }
874 }
875876#[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("try_mark_parent_green",
"rustc_query_system::dep_graph::graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_query_system/src/dep_graph/graph.rs"),
::tracing_core::__macro_support::Option::Some(876u32),
::tracing_core::__macro_support::Option::Some("rustc_query_system::dep_graph::graph"),
::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: Option<()> = loop {};
return __tracing_attr_fake_return;
}
{
let get_dep_dep_node =
|| self.previous.index_to_node(parent_dep_node_index);
match self.colors.get(parent_dep_node_index) {
DepNodeColor::Green(_) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_query_system/src/dep_graph/graph.rs:894",
"rustc_query_system::dep_graph::graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_query_system/src/dep_graph/graph.rs"),
::tracing_core::__macro_support::Option::Some(894u32),
::tracing_core::__macro_support::Option::Some("rustc_query_system::dep_graph::graph"),
::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!("dependency {0:?} was immediately green",
get_dep_dep_node()) as &dyn Value))])
});
} else { ; }
};
return Some(());
}
DepNodeColor::Red => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_query_system/src/dep_graph/graph.rs:902",
"rustc_query_system::dep_graph::graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_query_system/src/dep_graph/graph.rs"),
::tracing_core::__macro_support::Option::Some(902u32),
::tracing_core::__macro_support::Option::Some("rustc_query_system::dep_graph::graph"),
::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!("dependency {0:?} was immediately red",
get_dep_dep_node()) as &dyn Value))])
});
} else { ; }
};
return None;
}
DepNodeColor::Unknown => {}
}
let dep_dep_node = &get_dep_dep_node();
if !qcx.dep_context().is_eval_always(dep_dep_node.kind) {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_query_system/src/dep_graph/graph.rs:913",
"rustc_query_system::dep_graph::graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_query_system/src/dep_graph/graph.rs"),
::tracing_core::__macro_support::Option::Some(913u32),
::tracing_core::__macro_support::Option::Some("rustc_query_system::dep_graph::graph"),
::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!("state of dependency {0:?} ({1}) is unknown, trying to mark it green",
dep_dep_node, dep_dep_node.hash) as &dyn Value))])
});
} else { ; }
};
let node_index =
self.try_mark_previous_green(qcx, parent_dep_node_index,
dep_dep_node, Some(frame));
if node_index.is_some() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_query_system/src/dep_graph/graph.rs:922",
"rustc_query_system::dep_graph::graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_query_system/src/dep_graph/graph.rs"),
::tracing_core::__macro_support::Option::Some(922u32),
::tracing_core::__macro_support::Option::Some("rustc_query_system::dep_graph::graph"),
::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!("managed to MARK dependency {0:?} as green",
dep_dep_node) as &dyn Value))])
});
} else { ; }
};
return Some(());
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_query_system/src/dep_graph/graph.rs:928",
"rustc_query_system::dep_graph::graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_query_system/src/dep_graph/graph.rs"),
::tracing_core::__macro_support::Option::Some(928u32),
::tracing_core::__macro_support::Option::Some("rustc_query_system::dep_graph::graph"),
::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!("trying to force dependency {0:?}",
dep_dep_node) as &dyn Value))])
});
} else { ; }
};
if !qcx.dep_context().try_force_from_dep_node(*dep_dep_node,
parent_dep_node_index, frame) {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_query_system/src/dep_graph/graph.rs:931",
"rustc_query_system::dep_graph::graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_query_system/src/dep_graph/graph.rs"),
::tracing_core::__macro_support::Option::Some(931u32),
::tracing_core::__macro_support::Option::Some("rustc_query_system::dep_graph::graph"),
::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!("dependency {0:?} could not be forced",
dep_dep_node) as &dyn Value))])
});
} else { ; }
};
return None;
}
match self.colors.get(parent_dep_node_index) {
DepNodeColor::Green(_) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_query_system/src/dep_graph/graph.rs:937",
"rustc_query_system::dep_graph::graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_query_system/src/dep_graph/graph.rs"),
::tracing_core::__macro_support::Option::Some(937u32),
::tracing_core::__macro_support::Option::Some("rustc_query_system::dep_graph::graph"),
::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!("managed to FORCE dependency {0:?} to green",
dep_dep_node) as &dyn Value))])
});
} else { ; }
};
return Some(());
}
DepNodeColor::Red => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_query_system/src/dep_graph/graph.rs:941",
"rustc_query_system::dep_graph::graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_query_system/src/dep_graph/graph.rs"),
::tracing_core::__macro_support::Option::Some(941u32),
::tracing_core::__macro_support::Option::Some("rustc_query_system::dep_graph::graph"),
::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!("dependency {0:?} was red after forcing",
dep_dep_node) as &dyn Value))])
});
} else { ; }
};
return None;
}
DepNodeColor::Unknown => {}
}
if let None =
qcx.dep_context().sess().dcx().has_errors_or_delayed_bugs()
{
{
::core::panicking::panic_fmt(format_args!("try_mark_previous_green() - Forcing the DepNode should have set its color"));
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_query_system/src/dep_graph/graph.rs:961",
"rustc_query_system::dep_graph::graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_query_system/src/dep_graph/graph.rs"),
::tracing_core::__macro_support::Option::Some(961u32),
::tracing_core::__macro_support::Option::Some("rustc_query_system::dep_graph::graph"),
::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!("dependency {0:?} resulted in compilation error",
dep_dep_node) as &dyn Value))])
});
} else { ; }
};
return None;
}
}
}#[instrument(skip(self, qcx, parent_dep_node_index, frame), level = "debug")]877fn try_mark_parent_green<Qcx: QueryContext<Deps = D>>(
878&self,
879 qcx: Qcx,
880 parent_dep_node_index: SerializedDepNodeIndex,
881 frame: &MarkFrame<'_>,
882 ) -> Option<()> {
883let get_dep_dep_node = || self.previous.index_to_node(parent_dep_node_index);
884885match self.colors.get(parent_dep_node_index) {
886 DepNodeColor::Green(_) => {
887// This dependency has been marked as green before, we are
888 // still fine and can continue with checking the other
889 // dependencies.
890 //
891 // This path is extremely hot. We don't want to get the
892 // `dep_dep_node` unless it's necessary. Hence the
893 // `get_dep_dep_node` closure.
894debug!("dependency {:?} was immediately green", get_dep_dep_node());
895return Some(());
896 }
897 DepNodeColor::Red => {
898// We found a dependency the value of which has changed
899 // compared to the previous compilation session. We cannot
900 // mark the DepNode as green and also don't need to bother
901 // with checking any of the other dependencies.
902debug!("dependency {:?} was immediately red", get_dep_dep_node());
903return None;
904 }
905 DepNodeColor::Unknown => {}
906 }
907908let dep_dep_node = &get_dep_dep_node();
909910// We don't know the state of this dependency. If it isn't
911 // an eval_always node, let's try to mark it green recursively.
912if !qcx.dep_context().is_eval_always(dep_dep_node.kind) {
913debug!(
914"state of dependency {:?} ({}) is unknown, trying to mark it green",
915 dep_dep_node, dep_dep_node.hash,
916 );
917918let node_index =
919self.try_mark_previous_green(qcx, parent_dep_node_index, dep_dep_node, Some(frame));
920921if node_index.is_some() {
922debug!("managed to MARK dependency {dep_dep_node:?} as green");
923return Some(());
924 }
925 }
926927// We failed to mark it green, so we try to force the query.
928debug!("trying to force dependency {dep_dep_node:?}");
929if !qcx.dep_context().try_force_from_dep_node(*dep_dep_node, parent_dep_node_index, frame) {
930// The DepNode could not be forced.
931debug!("dependency {dep_dep_node:?} could not be forced");
932return None;
933 }
934935match self.colors.get(parent_dep_node_index) {
936 DepNodeColor::Green(_) => {
937debug!("managed to FORCE dependency {dep_dep_node:?} to green");
938return Some(());
939 }
940 DepNodeColor::Red => {
941debug!("dependency {dep_dep_node:?} was red after forcing");
942return None;
943 }
944 DepNodeColor::Unknown => {}
945 }
946947if let None = qcx.dep_context().sess().dcx().has_errors_or_delayed_bugs() {
948panic!("try_mark_previous_green() - Forcing the DepNode should have set its color")
949 }
950951// If the query we just forced has resulted in
952 // some kind of compilation error, we cannot rely on
953 // the dep-node color having been properly updated.
954 // This means that the query system has reached an
955 // invalid state. We let the compiler continue (by
956 // returning `None`) so it can emit error messages
957 // and wind down, but rely on the fact that this
958 // invalid state will not be persisted to the
959 // incremental compilation cache because of
960 // compilation errors being present.
961debug!("dependency {dep_dep_node:?} resulted in compilation error");
962return None;
963 }
964965/// Try to mark a dep-node which existed in the previous compilation session as green.
966#[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("try_mark_previous_green",
"rustc_query_system::dep_graph::graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_query_system/src/dep_graph/graph.rs"),
::tracing_core::__macro_support::Option::Some(966u32),
::tracing_core::__macro_support::Option::Some("rustc_query_system::dep_graph::graph"),
::tracing_core::field::FieldSet::new(&["dep_node"],
::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,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dep_node)
as &dyn Value))])
})
} 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: Option<DepNodeIndex> = loop {};
return __tracing_attr_fake_return;
}
{
let frame =
MarkFrame { index: prev_dep_node_index, parent: frame };
if true {
if !!qcx.dep_context().is_eval_always(dep_node.kind) {
::core::panicking::panic("assertion failed: !qcx.dep_context().is_eval_always(dep_node.kind)")
};
};
if true {
match (&self.previous.index_to_node(prev_dep_node_index),
&*dep_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);
}
}
};
};
let prev_deps =
self.previous.edge_targets_from(prev_dep_node_index);
for dep_dep_node_index in prev_deps {
self.try_mark_parent_green(qcx, dep_dep_node_index, &frame)?;
}
let dep_node_index =
self.promote_node_and_deps_to_current(prev_dep_node_index);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_query_system/src/dep_graph/graph.rs:1000",
"rustc_query_system::dep_graph::graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_query_system/src/dep_graph/graph.rs"),
::tracing_core::__macro_support::Option::Some(1000u32),
::tracing_core::__macro_support::Option::Some("rustc_query_system::dep_graph::graph"),
::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!("successfully marked {0:?} as green",
dep_node) as &dyn Value))])
});
} else { ; }
};
Some(dep_node_index)
}
}
}#[instrument(skip(self, qcx, prev_dep_node_index, frame), level = "debug")]967fn try_mark_previous_green<Qcx: QueryContext<Deps = D>>(
968&self,
969 qcx: Qcx,
970 prev_dep_node_index: SerializedDepNodeIndex,
971 dep_node: &DepNode,
972 frame: Option<&MarkFrame<'_>>,
973 ) -> Option<DepNodeIndex> {
974let frame = MarkFrame { index: prev_dep_node_index, parent: frame };
975976// We never try to mark eval_always nodes as green
977debug_assert!(!qcx.dep_context().is_eval_always(dep_node.kind));
978979debug_assert_eq!(self.previous.index_to_node(prev_dep_node_index), *dep_node);
980981let prev_deps = self.previous.edge_targets_from(prev_dep_node_index);
982983for dep_dep_node_index in prev_deps {
984self.try_mark_parent_green(qcx, dep_dep_node_index, &frame)?;
985 }
986987// If we got here without hitting a `return` that means that all
988 // dependencies of this DepNode could be marked as green. Therefore we
989 // can also mark this DepNode as green.
990991 // There may be multiple threads trying to mark the same dep node green concurrently
992993 // We allocating an entry for the node in the current dependency graph and
994 // adding all the appropriate edges imported from the previous graph
995let dep_node_index = self.promote_node_and_deps_to_current(prev_dep_node_index);
996997// ... and finally storing a "Green" entry in the color map.
998 // Multiple threads can all write the same color here
9991000debug!("successfully marked {dep_node:?} as green");
1001Some(dep_node_index)
1002 }
1003}
10041005impl<D: Deps> DepGraph<D> {
1006/// Returns true if the given node has been marked as red during the
1007 /// current compilation session. Used in various assertions
1008pub fn is_red(&self, dep_node: &DepNode) -> bool {
1009#[allow(non_exhaustive_omitted_patterns)] match self.node_color(dep_node) {
DepNodeColor::Red => true,
_ => false,
}matches!(self.node_color(dep_node), DepNodeColor::Red)1010 }
10111012/// Returns true if the given node has been marked as green during the
1013 /// current compilation session. Used in various assertions
1014pub fn is_green(&self, dep_node: &DepNode) -> bool {
1015#[allow(non_exhaustive_omitted_patterns)] match self.node_color(dep_node) {
DepNodeColor::Green(_) => true,
_ => false,
}matches!(self.node_color(dep_node), DepNodeColor::Green(_))1016 }
10171018pub fn assert_dep_node_not_yet_allocated_in_current_session<S: std::fmt::Display>(
1019&self,
1020 dep_node: &DepNode,
1021 msg: impl FnOnce() -> S,
1022 ) {
1023if let Some(data) = &self.data {
1024data.assert_dep_node_not_yet_allocated_in_current_session(dep_node, msg)
1025 }
1026 }
10271028/// This method loads all on-disk cacheable query results into memory, so
1029 /// they can be written out to the new cache file again. Most query results
1030 /// will already be in memory but in the case where we marked something as
1031 /// green but then did not need the value, that value will never have been
1032 /// loaded from disk.
1033 ///
1034 /// This method will only load queries that will end up in the disk cache.
1035 /// Other queries will not be executed.
1036pub fn exec_cache_promotions<Tcx: DepContext>(&self, tcx: Tcx) {
1037let _prof_timer = tcx.profiler().generic_activity("incr_comp_query_cache_promotion");
10381039let data = self.data.as_ref().unwrap();
1040for prev_index in data.colors.values.indices() {
1041match data.colors.get(prev_index) {
1042 DepNodeColor::Green(_) => {
1043let dep_node = data.previous.index_to_node(prev_index);
1044 tcx.try_load_from_on_disk_cache(dep_node);
1045 }
1046 DepNodeColor::Unknown | DepNodeColor::Red => {
1047// We can skip red nodes because a node can only be marked
1048 // as red if the query result was recomputed and thus is
1049 // already in memory.
1050}
1051 }
1052 }
1053 }
10541055pub fn finish_encoding(&self) -> FileEncodeResult {
1056if let Some(data) = &self.data { data.current.encoder.finish(&data.current) } else { Ok(0) }
1057 }
10581059pub(crate) fn next_virtual_depnode_index(&self) -> DepNodeIndex {
1060if true {
if !self.data.is_none() {
::core::panicking::panic("assertion failed: self.data.is_none()")
};
};debug_assert!(self.data.is_none());
1061let index = self.virtual_dep_node_index.fetch_add(1, Ordering::Relaxed);
1062DepNodeIndex::from_u32(index)
1063 }
1064}
10651066/// A "work product" is an intermediate result that we save into the
1067/// incremental directory for later re-use. The primary example are
1068/// the object files that we save for each partition at code
1069/// generation time.
1070///
1071/// Each work product is associated with a dep-node, representing the
1072/// process that produced the work-product. If that dep-node is found
1073/// to be dirty when we load up, then we will delete the work-product
1074/// at load time. If the work-product is found to be clean, then we
1075/// will keep a record in the `previous_work_products` list.
1076///
1077/// In addition, work products have an associated hash. This hash is
1078/// an extra hash that can be used to decide if the work-product from
1079/// a previous compilation can be re-used (in addition to the dirty
1080/// edges check).
1081///
1082/// As the primary example, consider the object files we generate for
1083/// each partition. In the first run, we create partitions based on
1084/// the symbols that need to be compiled. For each partition P, we
1085/// hash the symbols in P and create a `WorkProduct` record associated
1086/// with `DepNode::CodegenUnit(P)`; the hash is the set of symbols
1087/// in P.
1088///
1089/// The next time we compile, if the `DepNode::CodegenUnit(P)` is
1090/// judged to be clean (which means none of the things we read to
1091/// generate the partition were found to be dirty), it will be loaded
1092/// into previous work products. We will then regenerate the set of
1093/// symbols in the partition P and hash them (note that new symbols
1094/// may be added -- for example, new monomorphizations -- even if
1095/// nothing in P changed!). We will compare that hash against the
1096/// previous hash. If it matches up, we can reuse the object file.
1097#[derive(#[automatically_derived]
impl ::core::clone::Clone for WorkProduct {
#[inline]
fn clone(&self) -> WorkProduct {
WorkProduct {
cgu_name: ::core::clone::Clone::clone(&self.cgu_name),
saved_files: ::core::clone::Clone::clone(&self.saved_files),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for WorkProduct {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "WorkProduct",
"cgu_name", &self.cgu_name, "saved_files", &&self.saved_files)
}
}Debug, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for WorkProduct {
fn encode(&self, __encoder: &mut __E) {
match *self {
WorkProduct {
cgu_name: ref __binding_0, saved_files: ref __binding_1 } =>
{
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for WorkProduct {
fn decode(__decoder: &mut __D) -> Self {
WorkProduct {
cgu_name: ::rustc_serialize::Decodable::decode(__decoder),
saved_files: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
1098pub struct WorkProduct {
1099pub cgu_name: String,
1100/// Saved files associated with this CGU. In each key/value pair, the value is the path to the
1101 /// saved file and the key is some identifier for the type of file being saved.
1102 ///
1103 /// By convention, file extensions are currently used as identifiers, i.e. the key "o" maps to
1104 /// the object file's path, and "dwo" to the dwarf object file's path.
1105pub saved_files: UnordMap<String, String>,
1106}
11071108pub type WorkProductMap = UnordMap<WorkProductId, WorkProduct>;
11091110// Index type for `DepNodeData`'s edges.
1111impl ::std::fmt::Debug for EdgeIndex {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("{0}", self.as_u32()))
}
}rustc_index::newtype_index! {
1112struct EdgeIndex {}
1113}11141115/// `CurrentDepGraph` stores the dependency graph for the current session. It
1116/// will be populated as we run queries or tasks. We never remove nodes from the
1117/// graph: they are only added.
1118///
1119/// The nodes in it are identified by a `DepNodeIndex`. We avoid keeping the nodes
1120/// in memory. This is important, because these graph structures are some of the
1121/// largest in the compiler.
1122///
1123/// For this reason, we avoid storing `DepNode`s more than once as map
1124/// keys. The `anon_node_to_index` map only contains nodes of anonymous queries not in the previous
1125/// graph, and we map nodes in the previous graph to indices via a two-step
1126/// mapping. `SerializedDepGraph` maps from `DepNode` to `SerializedDepNodeIndex`,
1127/// and the `prev_index_to_index` vector (which is more compact and faster than
1128/// using a map) maps from `SerializedDepNodeIndex` to `DepNodeIndex`.
1129///
1130/// This struct uses three locks internally. The `data`, `anon_node_to_index`,
1131/// and `prev_index_to_index` fields are locked separately. Operations that take
1132/// a `DepNodeIndex` typically just access the `data` field.
1133///
1134/// We only need to manipulate at most two locks simultaneously:
1135/// `anon_node_to_index` and `data`, or `prev_index_to_index` and `data`. When
1136/// manipulating both, we acquire `anon_node_to_index` or `prev_index_to_index`
1137/// first, and `data` second.
1138pub(super) struct CurrentDepGraph<D: Deps> {
1139 encoder: GraphEncoder<D>,
1140 anon_node_to_index: ShardedHashMap<DepNode, DepNodeIndex>,
11411142/// This is used to verify that fingerprints do not change between the creation of a node
1143 /// and its recomputation.
1144#[cfg(debug_assertions)]
1145fingerprints: Lock<IndexVec<DepNodeIndex, Option<Fingerprint>>>,
11461147/// Used to trap when a specific edge is added to the graph.
1148 /// This is used for debug purposes and is only active with `debug_assertions`.
1149#[cfg(debug_assertions)]
1150forbidden_edge: Option<EdgeFilter>,
11511152/// Used to verify the absence of hash collisions among DepNodes.
1153 /// This field is only `Some` if the `-Z incremental_verify_ich` option is present
1154 /// or if `debug_assertions` are enabled.
1155 ///
1156 /// The map contains all DepNodes that have been allocated in the current session so far.
1157nodes_in_current_session: Option<Lock<FxHashMap<DepNode, DepNodeIndex>>>,
11581159/// Anonymous `DepNode`s are nodes whose IDs we compute from the list of
1160 /// their edges. This has the beneficial side-effect that multiple anonymous
1161 /// nodes can be coalesced into one without changing the semantics of the
1162 /// dependency graph. However, the merging of nodes can lead to a subtle
1163 /// problem during red-green marking: The color of an anonymous node from
1164 /// the current session might "shadow" the color of the node with the same
1165 /// ID from the previous session. In order to side-step this problem, we make
1166 /// sure that anonymous `NodeId`s allocated in different sessions don't overlap.
1167 /// This is implemented by mixing a session-key into the ID fingerprint of
1168 /// each anon node. The session-key is a hash of the number of previous sessions.
1169anon_id_seed: Fingerprint,
11701171/// These are simple counters that are for profiling and
1172 /// debugging and only active with `debug_assertions`.
1173pub(super) total_read_count: AtomicU64,
1174pub(super) total_duplicate_read_count: AtomicU64,
1175}
11761177impl<D: Deps> CurrentDepGraph<D> {
1178fn new(
1179 session: &Session,
1180 prev_graph_node_count: usize,
1181 encoder: FileEncoder,
1182 previous: Arc<SerializedDepGraph>,
1183 ) -> Self {
1184let mut stable_hasher = StableHasher::new();
1185previous.session_count().hash(&mut stable_hasher);
1186let anon_id_seed = stable_hasher.finish();
11871188#[cfg(debug_assertions)]
1189let forbidden_edge = match env::var("RUST_FORBID_DEP_GRAPH_EDGE") {
1190Ok(s) => match EdgeFilter::new(&s) {
1191Ok(f) => Some(f),
1192Err(err) => {
::core::panicking::panic_fmt(format_args!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {0}",
err));
}panic!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {}", err),
1193 },
1194Err(_) => None,
1195 };
11961197let new_node_count_estimate = 102 * prev_graph_node_count / 100 + 200;
11981199let new_node_dbg =
1200session.opts.unstable_opts.incremental_verify_ich || truecfg!(debug_assertions);
12011202CurrentDepGraph {
1203 encoder: GraphEncoder::new(session, encoder, prev_graph_node_count, previous),
1204 anon_node_to_index: ShardedHashMap::with_capacity(
1205// FIXME: The count estimate is off as anon nodes are only a portion of the nodes.
1206new_node_count_estimate / sharded::shards(),
1207 ),
1208anon_id_seed,
1209#[cfg(debug_assertions)]
1210forbidden_edge,
1211#[cfg(debug_assertions)]
1212fingerprints: Lock::new(IndexVec::from_elem_n(None, new_node_count_estimate)),
1213 nodes_in_current_session: new_node_dbg.then(|| {
1214Lock::new(FxHashMap::with_capacity_and_hasher(
1215new_node_count_estimate,
1216 Default::default(),
1217 ))
1218 }),
1219 total_read_count: AtomicU64::new(0),
1220 total_duplicate_read_count: AtomicU64::new(0),
1221 }
1222 }
12231224#[cfg(debug_assertions)]
1225fn record_edge(&self, dep_node_index: DepNodeIndex, key: DepNode, fingerprint: Fingerprint) {
1226if let Some(forbidden_edge) = &self.forbidden_edge {
1227forbidden_edge.index_to_node.lock().insert(dep_node_index, key);
1228 }
1229let previous = *self.fingerprints.lock().get_or_insert_with(dep_node_index, || fingerprint);
1230match (&previous, &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::Some(format_args!("Unstable fingerprints for {0:?}",
key)));
}
}
};assert_eq!(previous, fingerprint, "Unstable fingerprints for {:?}", key);
1231 }
12321233#[inline(always)]
1234fn record_node(
1235&self,
1236 dep_node_index: DepNodeIndex,
1237 key: DepNode,
1238 _current_fingerprint: Fingerprint,
1239 ) {
1240#[cfg(debug_assertions)]
1241self.record_edge(dep_node_index, key, _current_fingerprint);
12421243if let Some(ref nodes_in_current_session) = self.nodes_in_current_session {
1244outline(|| {
1245if nodes_in_current_session.lock().insert(key, dep_node_index).is_some() {
1246{
::core::panicking::panic_fmt(format_args!("Found duplicate dep-node {0:?}",
key));
};panic!("Found duplicate dep-node {key:?}");
1247 }
1248 });
1249 }
1250 }
12511252/// Writes the node to the current dep-graph and allocates a `DepNodeIndex` for it.
1253 /// Assumes that this is a node that has no equivalent in the previous dep-graph.
1254#[inline(always)]
1255fn alloc_new_node(
1256&self,
1257 key: DepNode,
1258 edges: EdgesVec,
1259 current_fingerprint: Fingerprint,
1260 ) -> DepNodeIndex {
1261let dep_node_index = self.encoder.send_new(key, current_fingerprint, edges);
12621263self.record_node(dep_node_index, key, current_fingerprint);
12641265dep_node_index1266 }
12671268#[inline]
1269fn debug_assert_not_in_new_nodes(
1270&self,
1271 prev_graph: &SerializedDepGraph,
1272 prev_index: SerializedDepNodeIndex,
1273 ) {
1274if let Some(ref nodes_in_current_session) = self.nodes_in_current_session {
1275if true {
if !!nodes_in_current_session.lock().contains_key(&prev_graph.index_to_node(prev_index))
{
{
::core::panicking::panic_fmt(format_args!("node from previous graph present in new node collection"));
}
};
};debug_assert!(
1276 !nodes_in_current_session
1277 .lock()
1278 .contains_key(&prev_graph.index_to_node(prev_index)),
1279"node from previous graph present in new node collection"
1280);
1281 }
1282 }
1283}
12841285#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for TaskDepsRef<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TaskDepsRef::Allow(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Allow",
&__self_0),
TaskDepsRef::EvalAlways =>
::core::fmt::Formatter::write_str(f, "EvalAlways"),
TaskDepsRef::Ignore =>
::core::fmt::Formatter::write_str(f, "Ignore"),
TaskDepsRef::Forbid =>
::core::fmt::Formatter::write_str(f, "Forbid"),
}
}
}Debug, #[automatically_derived]
impl<'a> ::core::clone::Clone for TaskDepsRef<'a> {
#[inline]
fn clone(&self) -> TaskDepsRef<'a> {
let _: ::core::clone::AssertParamIsClone<&'a Lock<TaskDeps>>;
*self
}
}Clone, #[automatically_derived]
impl<'a> ::core::marker::Copy for TaskDepsRef<'a> { }Copy)]
1286pub enum TaskDepsRef<'a> {
1287/// New dependencies can be added to the
1288 /// `TaskDeps`. This is used when executing a 'normal' query
1289 /// (no `eval_always` modifier)
1290Allow(&'a Lock<TaskDeps>),
1291/// This is used when executing an `eval_always` query. We don't
1292 /// need to track dependencies for a query that's always
1293 /// re-executed -- but we need to know that this is an `eval_always`
1294 /// query in order to emit dependencies to `DepNodeIndex::FOREVER_RED_NODE`
1295 /// when directly feeding other queries.
1296EvalAlways,
1297/// New dependencies are ignored. This is also used for `dep_graph.with_ignore`.
1298Ignore,
1299/// Any attempt to add new dependencies will cause a panic.
1300 /// This is used when decoding a query result from disk,
1301 /// to ensure that the decoding process doesn't itself
1302 /// require the execution of any queries.
1303Forbid,
1304}
13051306#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TaskDeps {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "TaskDeps",
"node", &self.node, "reads", &self.reads, "read_set",
&self.read_set, "phantom_data", &&self.phantom_data)
}
}Debug)]
1307pub struct TaskDeps {
1308#[cfg(debug_assertions)]
1309node: Option<DepNode>,
13101311/// A vector of `DepNodeIndex`, basically.
1312reads: EdgesVec,
13131314/// When adding new edges to `reads` in `DepGraph::read_index` we need to determine if the edge
1315 /// has been seen before. If the number of elements in `reads` is small, we just do a linear
1316 /// scan. If the number is higher, a hashset has better perf. This field is that hashset. It's
1317 /// only used if the number of elements in `reads` exceeds `LINEAR_SCAN_MAX`.
1318read_set: FxHashSet<DepNodeIndex>,
13191320 phantom_data: PhantomData<DepNode>,
1321}
13221323impl TaskDeps {
1324/// See `TaskDeps::read_set` above.
1325const LINEAR_SCAN_MAX: usize = 16;
13261327#[inline]
1328fn new(#[cfg(debug_assertions)] node: Option<DepNode>, read_set_capacity: usize) -> Self {
1329TaskDeps {
1330#[cfg(debug_assertions)]
1331node,
1332 reads: EdgesVec::new(),
1333 read_set: FxHashSet::with_capacity_and_hasher(read_set_capacity, Default::default()),
1334 phantom_data: PhantomData,
1335 }
1336 }
1337}
13381339// A data structure that stores Option<DepNodeColor> values as a contiguous
1340// array, using one u32 per entry.
1341pub(super) struct DepNodeColorMap {
1342 values: IndexVec<SerializedDepNodeIndex, AtomicU32>,
1343}
13441345// All values below `COMPRESSED_RED` are green.
1346const COMPRESSED_RED: u32 = u32::MAX - 1;
1347const COMPRESSED_UNKNOWN: u32 = u32::MAX;
13481349impl DepNodeColorMap {
1350fn new(size: usize) -> DepNodeColorMap {
1351if true {
if !(COMPRESSED_RED > DepNodeIndex::MAX_AS_U32) {
::core::panicking::panic("assertion failed: COMPRESSED_RED > DepNodeIndex::MAX_AS_U32")
};
};debug_assert!(COMPRESSED_RED > DepNodeIndex::MAX_AS_U32);
1352DepNodeColorMap { values: (0..size).map(|_| AtomicU32::new(COMPRESSED_UNKNOWN)).collect() }
1353 }
13541355#[inline]
1356pub(super) fn current(&self, index: SerializedDepNodeIndex) -> Option<DepNodeIndex> {
1357let value = self.values[index].load(Ordering::Relaxed);
1358if value <= DepNodeIndex::MAX_AS_U32 { Some(DepNodeIndex::from_u32(value)) } else { None }
1359 }
13601361/// This tries to atomically mark a node green and assign `index` as the new
1362 /// index. This returns `Ok` if `index` gets assigned, otherwise it returns
1363 /// the already allocated index in `Err`.
1364#[inline]
1365pub(super) fn try_mark_green(
1366&self,
1367 prev_index: SerializedDepNodeIndex,
1368 index: DepNodeIndex,
1369 ) -> Result<(), DepNodeIndex> {
1370let value = &self.values[prev_index];
1371match value.compare_exchange(
1372COMPRESSED_UNKNOWN,
1373index.as_u32(),
1374 Ordering::Relaxed,
1375 Ordering::Relaxed,
1376 ) {
1377Ok(_) => Ok(()),
1378Err(v) => Err({
1379match (&(v), &(COMPRESSED_RED)) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::Some(format_args!("tried to mark a red node as green")));
}
}
};assert_ne!(v, COMPRESSED_RED, "tried to mark a red node as green");
1380DepNodeIndex::from_u32(v)
1381 }),
1382 }
1383 }
13841385#[inline]
1386pub(super) fn get(&self, index: SerializedDepNodeIndex) -> DepNodeColor {
1387let value = self.values[index].load(Ordering::Acquire);
1388// Green is by far the most common case. Check for that first so we can succeed with a
1389 // single comparison.
1390if value < COMPRESSED_RED {
1391 DepNodeColor::Green(DepNodeIndex::from_u32(value))
1392 } else if value == COMPRESSED_RED {
1393 DepNodeColor::Red1394 } else {
1395if true {
match (&value, &COMPRESSED_UNKNOWN) {
(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!(value, COMPRESSED_UNKNOWN);
1396 DepNodeColor::Unknown1397 }
1398 }
13991400#[inline]
1401pub(super) fn insert_red(&self, index: SerializedDepNodeIndex) {
1402let value = self.values[index].swap(COMPRESSED_RED, Ordering::Release);
1403// Sanity check for duplicate nodes
1404match (&value, &COMPRESSED_UNKNOWN) {
(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::Some(format_args!("trying to encode a dep node twice")));
}
}
};assert_eq!(value, COMPRESSED_UNKNOWN, "trying to encode a dep node twice");
1405 }
1406}
14071408#[inline(never)]
1409#[cold]
1410pub(crate) fn print_markframe_trace<D: Deps>(graph: &DepGraph<D>, frame: &MarkFrame<'_>) {
1411let data = graph.data.as_ref().unwrap();
14121413{
::std::io::_eprint(format_args!("there was a panic while trying to force a dep node\n"));
};eprintln!("there was a panic while trying to force a dep node");
1414{ ::std::io::_eprint(format_args!("try_mark_green dep node stack:\n")); };eprintln!("try_mark_green dep node stack:");
14151416let mut i = 0;
1417let mut current = Some(frame);
1418while let Some(frame) = current {
1419let node = data.previous.index_to_node(frame.index);
1420{ ::std::io::_eprint(format_args!("#{0} {1:?}\n", i, node)); };eprintln!("#{i} {node:?}");
1421 current = frame.parent;
1422 i += 1;
1423 }
14241425{
::std::io::_eprint(format_args!("end of try_mark_green dep node stack\n"));
};eprintln!("end of try_mark_green dep node stack");
1426}
14271428#[cold]
1429#[inline(never)]
1430fn panic_on_forbidden_read<D: Deps>(data: &DepGraphData<D>, dep_node_index: DepNodeIndex) -> ! {
1431// We have to do an expensive reverse-lookup of the DepNode that
1432 // corresponds to `dep_node_index`, but that's OK since we are about
1433 // to ICE anyway.
1434let mut dep_node = None;
14351436// First try to find the dep node among those that already existed in the
1437 // previous session and has been marked green
1438for prev_index in data.colors.values.indices() {
1439if data.colors.current(prev_index) == Some(dep_node_index) {
1440 dep_node = Some(data.previous.index_to_node(prev_index));
1441break;
1442 }
1443 }
14441445if dep_node.is_none()
1446 && let Some(nodes) = &data.current.nodes_in_current_session
1447 {
1448// Try to find it among the nodes allocated so far in this session
1449 // This is OK, there's only ever one node result possible so this is deterministic.
1450#[allow(rustc::potential_query_instability)]
1451if let Some((node, _)) = nodes.lock().iter().find(|&(_, index)| *index == dep_node_index) {
1452dep_node = Some(*node);
1453 }
1454 }
14551456let dep_node = dep_node.map_or_else(
1457 || ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("with index {0:?}", dep_node_index))
})format!("with index {:?}", dep_node_index),
1458 |dep_node| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0:?}`", dep_node))
})format!("`{:?}`", dep_node),
1459 );
14601461{
::core::panicking::panic_fmt(format_args!("Error: trying to record dependency on DepNode {0} in a context that does not allow it (e.g. during query deserialization). The most common case of recording a dependency on a DepNode `foo` is when the corresponding query `foo` is invoked. Invoking queries is not allowed as part of loading something from the incremental on-disk cache. See <https://github.com/rust-lang/rust/pull/91919>.",
dep_node));
}panic!(
1462"Error: trying to record dependency on DepNode {dep_node} in a \
1463 context that does not allow it (e.g. during query deserialization). \
1464 The most common case of recording a dependency on a DepNode `foo` is \
1465 when the corresponding query `foo` is invoked. Invoking queries is not \
1466 allowed as part of loading something from the incremental on-disk cache. \
1467 See <https://github.com/rust-lang/rust/pull/91919>."
1468)1469}