Skip to main content

rustc_incremental/
assert_dep_graph.rs

1//! This pass is only used for the UNIT TESTS and DEBUGGING NEEDS
2//! around dependency graph construction. It serves two purposes; it
3//! will dump graphs in graphviz form to disk, and it searches for
4//! `#[rustc_if_this_changed]` and `#[rustc_then_this_would_need]`
5//! annotations. These annotations can be used to test whether paths
6//! exist in the graph. These checks run after codegen, so they view the
7//! the final state of the dependency graph. Note that there are
8//! similar assertions found in `persist::clean` which check the
9//! **initial** state of the dependency graph, just after it has been
10//! loaded from disk.
11//!
12//! In this code, we report errors on each `rustc_if_this_changed`
13//! annotation. If a path exists in all cases, then we would report
14//! "all path(s) exist". Otherwise, we report: "no path to `foo`" for
15//! each case where no path exists. `ui` tests can then be
16//! used to check when paths exist or do not.
17//!
18//! The full form of the `rustc_if_this_changed` annotation is
19//! `#[rustc_if_this_changed("foo")]`, which will report a
20//! source node of `foo(def_id)`. The `"foo"` is optional and
21//! defaults to `"Hir"` if omitted.
22//!
23//! Example:
24//!
25//! ```ignore (needs flags)
26//! #[rustc_if_this_changed(Hir)]
27//! fn foo() { }
28//!
29//! #[rustc_then_this_would_need(codegen)] //~ ERROR no path from `foo`
30//! fn bar() { }
31//!
32//! #[rustc_then_this_would_need(codegen)] //~ ERROR OK
33//! fn baz() { foo(); }
34//! ```
35
36use std::env;
37use std::fs::{self, File};
38use std::io::Write;
39
40use rustc_data_structures::fx::FxIndexSet;
41use rustc_data_structures::graph::linked_graph::{Direction, INCOMING, NodeIndex, OUTGOING};
42use rustc_graphviz as dot;
43use rustc_hir as hir;
44use rustc_hir::Attribute;
45use rustc_hir::attrs::AttributeKind;
46use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
47use rustc_hir::intravisit::{self, Visitor};
48use rustc_middle::bug;
49use rustc_middle::dep_graph::{DepKind, DepNode, DepNodeFilter, EdgeFilter, RetainedDepGraph};
50use rustc_middle::hir::nested_filter;
51use rustc_middle::ty::TyCtxt;
52use rustc_span::{Span, Symbol, sym};
53use tracing::debug;
54
55use crate::errors;
56
57#[allow(missing_docs)]
58pub(crate) fn assert_dep_graph(tcx: TyCtxt<'_>) {
59    tcx.dep_graph.with_ignore(|| {
60        if tcx.sess.opts.unstable_opts.dump_dep_graph {
61            tcx.dep_graph.with_retained_dep_graph(dump_graph);
62        }
63
64        if !tcx.sess.opts.unstable_opts.query_dep_graph {
65            return;
66        }
67
68        // if the `rustc_attrs` feature is not enabled, then the
69        // attributes we are interested in cannot be present anyway, so
70        // skip the walk.
71        if !tcx.features().rustc_attrs() {
72            return;
73        }
74
75        // Find annotations supplied by user (if any).
76        let (if_this_changed, then_this_would_need) = {
77            let mut visitor =
78                IfThisChanged { tcx, if_this_changed: ::alloc::vec::Vec::new()vec![], then_this_would_need: ::alloc::vec::Vec::new()vec![] };
79            visitor.process_attrs(CRATE_DEF_ID);
80            tcx.hir_visit_all_item_likes_in_crate(&mut visitor);
81            (visitor.if_this_changed, visitor.then_this_would_need)
82        };
83
84        if !if_this_changed.is_empty() || !then_this_would_need.is_empty() {
85            if !tcx.sess.opts.unstable_opts.query_dep_graph {
    {
        ::core::panicking::panic_fmt(format_args!("cannot use the `#[{0}]` or `#[{1}]` annotations without supplying `-Z query-dep-graph`",
                sym::rustc_if_this_changed, sym::rustc_then_this_would_need));
    }
};assert!(
86                tcx.sess.opts.unstable_opts.query_dep_graph,
87                "cannot use the `#[{}]` or `#[{}]` annotations \
88                    without supplying `-Z query-dep-graph`",
89                sym::rustc_if_this_changed,
90                sym::rustc_then_this_would_need
91            );
92        }
93
94        // Check paths.
95        check_paths(tcx, &if_this_changed, &then_this_would_need);
96    })
97}
98
99type Sources = Vec<(Span, DefId, DepNode)>;
100type Targets = Vec<(Span, Symbol, hir::HirId, DepNode)>;
101
102struct IfThisChanged<'tcx> {
103    tcx: TyCtxt<'tcx>,
104    if_this_changed: Sources,
105    then_this_would_need: Targets,
106}
107
108impl<'tcx> IfThisChanged<'tcx> {
109    fn process_attrs(&mut self, def_id: LocalDefId) {
110        let def_path_hash = self.tcx.def_path_hash(def_id.to_def_id());
111        let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
112        let attrs = self.tcx.hir_attrs(hir_id);
113        for attr in attrs {
114            if let Attribute::Parsed(AttributeKind::RustcIfThisChanged(span, dep_node)) = *attr {
115                let dep_node = match dep_node {
116                    None => DepNode::from_def_path_hash(
117                        self.tcx,
118                        def_path_hash,
119                        DepKind::opt_hir_owner_nodes,
120                    ),
121                    Some(n) => {
122                        match DepNode::from_label_string(self.tcx, n.as_str(), def_path_hash) {
123                            Ok(n) => n,
124                            Err(()) => self
125                                .tcx
126                                .dcx()
127                                .emit_fatal(errors::UnrecognizedDepNode { span, name: n }),
128                        }
129                    }
130                };
131                self.if_this_changed.push((span, def_id.to_def_id(), dep_node));
132            } else if let Attribute::Parsed(AttributeKind::RustcThenThisWouldNeed(dep_nodes)) = attr
133            {
134                for &n in dep_nodes {
135                    let Ok(dep_node) =
136                        DepNode::from_label_string(self.tcx, n.as_str(), def_path_hash)
137                    else {
138                        self.tcx
139                            .dcx()
140                            .emit_fatal(errors::UnrecognizedDepNode { span: n.span, name: n.name });
141                    };
142                    self.then_this_would_need.push((n.span, n.name, hir_id, dep_node));
143                }
144            }
145        }
146    }
147}
148
149impl<'tcx> Visitor<'tcx> for IfThisChanged<'tcx> {
150    type NestedFilter = nested_filter::OnlyBodies;
151
152    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
153        self.tcx
154    }
155
156    fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
157        self.process_attrs(item.owner_id.def_id);
158        intravisit::walk_item(self, item);
159    }
160
161    fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
162        self.process_attrs(trait_item.owner_id.def_id);
163        intravisit::walk_trait_item(self, trait_item);
164    }
165
166    fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
167        self.process_attrs(impl_item.owner_id.def_id);
168        intravisit::walk_impl_item(self, impl_item);
169    }
170
171    fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
172        self.process_attrs(s.def_id);
173        intravisit::walk_field_def(self, s);
174    }
175}
176
177fn check_paths<'tcx>(tcx: TyCtxt<'tcx>, if_this_changed: &Sources, then_this_would_need: &Targets) {
178    // Return early here so as not to construct the query, which is not cheap.
179    if if_this_changed.is_empty() {
180        for &(target_span, _, _, _) in then_this_would_need {
181            tcx.dcx().emit_err(errors::MissingIfThisChanged { span: target_span });
182        }
183        return;
184    }
185    tcx.dep_graph.with_retained_dep_graph(|query| {
186        for &(_, source_def_id, ref source_dep_node) in if_this_changed {
187            let dependents = query.transitive_predecessors(source_dep_node);
188            for &(target_span, ref target_pass, _, ref target_dep_node) in then_this_would_need {
189                if !dependents.contains(&target_dep_node) {
190                    tcx.dcx().emit_err(errors::NoPath {
191                        span: target_span,
192                        source: tcx.def_path_str(source_def_id),
193                        target: *target_pass,
194                    });
195                } else {
196                    tcx.dcx().emit_err(errors::Ok { span: target_span });
197                }
198            }
199        }
200    });
201}
202
203fn dump_graph(graph: &RetainedDepGraph) {
204    let path: String = env::var("RUST_DEP_GRAPH").unwrap_or_else(|_| "dep_graph".to_string());
205
206    let nodes = match env::var("RUST_DEP_GRAPH_FILTER") {
207        Ok(string) => {
208            // Expect one of: "-> target", "source -> target", or "source ->".
209            let edge_filter =
210                EdgeFilter::new(&string).unwrap_or_else(|e| ::rustc_middle::util::bug::bug_fmt(format_args!("invalid filter: {0}", e))bug!("invalid filter: {}", e));
211            let sources = node_set(graph, &edge_filter.source);
212            let targets = node_set(graph, &edge_filter.target);
213            filter_nodes(graph, &sources, &targets)
214        }
215        Err(_) => graph.nodes().into_iter().map(|n| n.kind).collect(),
216    };
217    let edges = filter_edges(graph, &nodes);
218
219    {
220        // dump a .txt file with just the edges:
221        let txt_path = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.txt", path))
    })format!("{path}.txt");
222        let mut file = File::create_buffered(&txt_path).unwrap();
223        for (source, target) in &edges {
224            file.write_fmt(format_args!("{0:?} -> {1:?}\n", source, target))write!(file, "{source:?} -> {target:?}\n").unwrap();
225        }
226    }
227
228    {
229        // dump a .dot file in graphviz format:
230        let dot_path = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.dot", path))
    })format!("{path}.dot");
231        let mut v = Vec::new();
232        dot::render(&GraphvizDepGraph(nodes, edges), &mut v).unwrap();
233        fs::write(dot_path, v).unwrap();
234    }
235}
236
237#[allow(missing_docs)]
238struct GraphvizDepGraph(FxIndexSet<DepKind>, Vec<(DepKind, DepKind)>);
239
240impl<'a> dot::GraphWalk<'a> for GraphvizDepGraph {
241    type Node = DepKind;
242    type Edge = (DepKind, DepKind);
243    fn nodes(&self) -> dot::Nodes<'_, DepKind> {
244        let nodes: Vec<_> = self.0.iter().cloned().collect();
245        nodes.into()
246    }
247    fn edges(&self) -> dot::Edges<'_, (DepKind, DepKind)> {
248        self.1[..].into()
249    }
250    fn source(&self, edge: &(DepKind, DepKind)) -> DepKind {
251        edge.0
252    }
253    fn target(&self, edge: &(DepKind, DepKind)) -> DepKind {
254        edge.1
255    }
256}
257
258impl<'a> dot::Labeller<'a> for GraphvizDepGraph {
259    type Node = DepKind;
260    type Edge = (DepKind, DepKind);
261    fn graph_id(&self) -> dot::Id<'_> {
262        dot::Id::new("DependencyGraph").unwrap()
263    }
264    fn node_id(&self, n: &DepKind) -> dot::Id<'_> {
265        let s: String = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", n))
    })format!("{n:?}")
266            .chars()
267            .map(|c| if c == '_' || c.is_alphanumeric() { c } else { '_' })
268            .collect();
269        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_incremental/src/assert_dep_graph.rs:269",
                        "rustc_incremental::assert_dep_graph",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_incremental/src/assert_dep_graph.rs"),
                        ::tracing_core::__macro_support::Option::Some(269u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::assert_dep_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!("n={0:?} s={1:?}",
                                                    n, s) as &dyn Value))])
            });
    } else { ; }
};debug!("n={:?} s={:?}", n, s);
270        dot::Id::new(s).unwrap()
271    }
272    fn node_label(&self, n: &DepKind) -> dot::LabelText<'_> {
273        dot::LabelText::label(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", n))
    })format!("{n:?}"))
274    }
275}
276
277// Given an optional filter like `"x,y,z"`, returns either `None` (no
278// filter) or the set of nodes whose labels contain all of those
279// substrings.
280fn node_set<'g>(
281    graph: &'g RetainedDepGraph,
282    filter: &DepNodeFilter,
283) -> Option<FxIndexSet<&'g DepNode>> {
284    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_incremental/src/assert_dep_graph.rs:284",
                        "rustc_incremental::assert_dep_graph",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_incremental/src/assert_dep_graph.rs"),
                        ::tracing_core::__macro_support::Option::Some(284u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::assert_dep_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!("node_set(filter={0:?})",
                                                    filter) as &dyn Value))])
            });
    } else { ; }
};debug!("node_set(filter={:?})", filter);
285
286    if filter.accepts_all() {
287        return None;
288    }
289
290    Some(graph.nodes().into_iter().filter(|n| filter.test(n)).collect())
291}
292
293fn filter_nodes<'g>(
294    graph: &'g RetainedDepGraph,
295    sources: &Option<FxIndexSet<&'g DepNode>>,
296    targets: &Option<FxIndexSet<&'g DepNode>>,
297) -> FxIndexSet<DepKind> {
298    if let Some(sources) = sources {
299        if let Some(targets) = targets {
300            walk_between(graph, sources, targets)
301        } else {
302            walk_nodes(graph, sources, OUTGOING)
303        }
304    } else if let Some(targets) = targets {
305        walk_nodes(graph, targets, INCOMING)
306    } else {
307        graph.nodes().into_iter().map(|n| n.kind).collect()
308    }
309}
310
311fn walk_nodes<'g>(
312    graph: &'g RetainedDepGraph,
313    starts: &FxIndexSet<&'g DepNode>,
314    direction: Direction,
315) -> FxIndexSet<DepKind> {
316    let mut set = FxIndexSet::default();
317    for &start in starts {
318        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_incremental/src/assert_dep_graph.rs:318",
                        "rustc_incremental::assert_dep_graph",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_incremental/src/assert_dep_graph.rs"),
                        ::tracing_core::__macro_support::Option::Some(318u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::assert_dep_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!("walk_nodes: start={0:?} outgoing?={1:?}",
                                                    start, direction == OUTGOING) as &dyn Value))])
            });
    } else { ; }
};debug!("walk_nodes: start={:?} outgoing?={:?}", start, direction == OUTGOING);
319        if set.insert(start.kind) {
320            let mut stack = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [graph.indices[start]]))vec![graph.indices[start]];
321            while let Some(index) = stack.pop() {
322                for (_, edge) in graph.inner.adjacent_edges(index, direction) {
323                    let neighbor_index = edge.source_or_target(direction);
324                    let neighbor = graph.inner.node_data(neighbor_index);
325                    if set.insert(neighbor.kind) {
326                        stack.push(neighbor_index);
327                    }
328                }
329            }
330        }
331    }
332    set
333}
334
335fn walk_between<'g>(
336    graph: &'g RetainedDepGraph,
337    sources: &FxIndexSet<&'g DepNode>,
338    targets: &FxIndexSet<&'g DepNode>,
339) -> FxIndexSet<DepKind> {
340    // This is a bit tricky. We want to include a node only if it is:
341    // (a) reachable from a source and (b) will reach a target. And we
342    // have to be careful about cycles etc. Luckily efficiency is not
343    // a big concern!
344
345    #[derive(#[automatically_derived]
impl ::core::marker::Copy for State { }Copy, #[automatically_derived]
impl ::core::clone::Clone for State {
    #[inline]
    fn clone(&self) -> State { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for State {
    #[inline]
    fn eq(&self, other: &State) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
346    enum State {
347        Undecided,
348        Deciding,
349        Included,
350        Excluded,
351    }
352
353    let mut node_states = ::alloc::vec::from_elem(State::Undecided, graph.inner.len_nodes())vec![State::Undecided; graph.inner.len_nodes()];
354
355    for &target in targets {
356        node_states[graph.indices[target].0] = State::Included;
357    }
358
359    for source in sources.iter().map(|&n| graph.indices[n]) {
360        recurse(graph, &mut node_states, source);
361    }
362
363    return graph
364        .nodes()
365        .into_iter()
366        .filter(|&n| {
367            let index = graph.indices[n];
368            node_states[index.0] == State::Included
369        })
370        .map(|n| n.kind)
371        .collect();
372
373    fn recurse(graph: &RetainedDepGraph, node_states: &mut [State], node: NodeIndex) -> bool {
374        match node_states[node.0] {
375            // known to reach a target
376            State::Included => return true,
377
378            // known not to reach a target
379            State::Excluded => return false,
380
381            // backedge, not yet known, say false
382            State::Deciding => return false,
383
384            State::Undecided => {}
385        }
386
387        node_states[node.0] = State::Deciding;
388
389        for neighbor_index in graph.inner.successor_nodes(node) {
390            if recurse(graph, node_states, neighbor_index) {
391                node_states[node.0] = State::Included;
392            }
393        }
394
395        // if we didn't find a path to target, then set to excluded
396        if node_states[node.0] == State::Deciding {
397            node_states[node.0] = State::Excluded;
398            false
399        } else {
400            if !(node_states[node.0] == State::Included) {
    ::core::panicking::panic("assertion failed: node_states[node.0] == State::Included")
};assert!(node_states[node.0] == State::Included);
401            true
402        }
403    }
404}
405
406fn filter_edges(graph: &RetainedDepGraph, nodes: &FxIndexSet<DepKind>) -> Vec<(DepKind, DepKind)> {
407    let uniq: FxIndexSet<_> = graph
408        .edges()
409        .into_iter()
410        .map(|(s, t)| (s.kind, t.kind))
411        .filter(|(source, target)| nodes.contains(source) && nodes.contains(target))
412        .collect();
413    uniq.into_iter().collect()
414}