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