1use std::env;
37use std::fs::{self, File};
38use std::io::Write;
39
40use rustc_attr_ir::{Attribute, AttributeKind};
41use rustc_data_structures::fx::FxIndexSet;
42use rustc_data_structures::graph::linked_graph::{Direction, INCOMING, NodeIndex, OUTGOING};
43use rustc_graphviz::{self as dot, FillColor, Style};
44use rustc_hir as hir;
45use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
46use rustc_hir::intravisit::{self, Visitor};
47use rustc_middle::dep_graph::{
48 DepGraph, DepKind, DepNode, DepNodeColor, DepNodeFilter, EdgeFilter, RetainedDepGraph,
49};
50use rustc_middle::hir::nested_filter;
51use rustc_middle::ty::{TyCtxt, tls};
52use rustc_span::{Span, Symbol, bug, sym};
53use tracing::debug;
54
55use crate::diagnostics;
56
57#[allow(missing_docs)]
58pub(crate) fn assert_dep_graph(tcx: TyCtxt<'_>) {
59 tcx.dep_graph.with_ignore(|| {
60 let retained_dep_graph = tcx.dep_graph.retained_dep_graph();
63
64 if tcx.sess.opts.unstable_opts.dump_dep_graph {
65 dump_graph(&tcx.dep_graph);
66 }
67
68 if !tcx.sess.opts.unstable_opts.query_dep_graph {
69 return;
70 }
71
72 if !tcx.features().rustc_attrs() {
76 return;
77 }
78
79 let (if_this_changed, then_this_would_need) = {
81 let mut visitor =
82 IfThisChanged { tcx, if_this_changed: ::alloc::vec::Vec::new()vec![], then_this_would_need: ::alloc::vec::Vec::new()vec![] };
83 visitor.process_attrs(CRATE_DEF_ID);
84 tcx.hir_visit_all_item_likes_in_crate(&mut visitor);
85 (visitor.if_this_changed, visitor.then_this_would_need)
86 };
87
88 if !if_this_changed.is_empty() || !then_this_would_need.is_empty() {
89 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!(
90 tcx.sess.opts.unstable_opts.query_dep_graph,
91 "cannot use the `#[{}]` or `#[{}]` annotations \
92 without supplying `-Z query-dep-graph`",
93 sym::rustc_if_this_changed,
94 sym::rustc_then_this_would_need
95 );
96 }
97
98 check_paths(tcx, retained_dep_graph.as_ref(), &if_this_changed, &then_this_would_need);
100 })
101}
102
103type Sources = Vec<(Span, DefId, DepNode)>;
104type Targets = Vec<(Span, Symbol, hir::HirId, DepNode)>;
105
106struct IfThisChanged<'tcx> {
107 tcx: TyCtxt<'tcx>,
108 if_this_changed: Sources,
109 then_this_would_need: Targets,
110}
111
112impl<'tcx> IfThisChanged<'tcx> {
113 fn process_attrs(&mut self, def_id: LocalDefId) {
114 let def_path_hash = self.tcx.def_path_hash(def_id.to_def_id());
115 let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
116 let attrs = self.tcx.hir_attrs(hir_id);
117 for attr in attrs {
118 if let Attribute::Parsed(AttributeKind::RustcIfThisChanged(span, dep_node)) = *attr {
119 let dep_node = match dep_node {
120 None => {
121 DepNode::from_def_path_hash(self.tcx, def_path_hash, DepKind::hir_owner)
122 }
123 Some(n) => {
124 match DepNode::from_label_string(self.tcx, n.as_str(), def_path_hash) {
125 Ok(n) => n,
126 Err(()) => self
127 .tcx
128 .dcx()
129 .emit_fatal(diagnostics::UnrecognizedDepNode { span, name: n }),
130 }
131 }
132 };
133 self.if_this_changed.push((span, def_id.to_def_id(), dep_node));
134 } else if let Attribute::Parsed(AttributeKind::RustcThenThisWouldNeed(dep_nodes)) = 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.dcx().emit_fatal(diagnostics::UnrecognizedDepNode {
141 span: n.span,
142 name: n.name,
143 });
144 };
145 self.then_this_would_need.push((n.span, n.name, hir_id, dep_node));
146 }
147 }
148 }
149 }
150}
151
152impl<'tcx> Visitor<'tcx> for IfThisChanged<'tcx> {
153 type NestedFilter = nested_filter::OnlyBodies;
154
155 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
156 self.tcx
157 }
158
159 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
160 self.process_attrs(item.owner_id.def_id);
161 intravisit::walk_item(self, item);
162 }
163
164 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
165 self.process_attrs(trait_item.owner_id.def_id);
166 intravisit::walk_trait_item(self, trait_item);
167 }
168
169 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
170 self.process_attrs(impl_item.owner_id.def_id);
171 intravisit::walk_impl_item(self, impl_item);
172 }
173
174 fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
175 self.process_attrs(s.def_id);
176 intravisit::walk_field_def(self, s);
177 }
178}
179
180fn check_paths<'tcx>(
181 tcx: TyCtxt<'tcx>,
182 retained_dep_graph: Option<&RetainedDepGraph>,
183 if_this_changed: &Sources,
184 then_this_would_need: &Targets,
185) {
186 if if_this_changed.is_empty() {
187 for &(target_span, _, _, _) in then_this_would_need {
188 tcx.dcx().emit_err(diagnostics::MissingIfThisChanged { span: target_span });
189 }
190 return;
191 }
192 let Some(query) = retained_dep_graph else { return };
193 for &(_, source_def_id, ref source_dep_node) in if_this_changed {
194 let dependents = query.transitive_predecessors(source_dep_node);
195 for &(target_span, ref target_pass, _, ref target_dep_node) in then_this_would_need {
196 if !dependents.contains(&target_dep_node) {
197 tcx.dcx().emit_err(diagnostics::NoPath {
198 span: target_span,
199 source: tcx.def_path_str(source_def_id),
200 target: *target_pass,
201 });
202 } else {
203 tcx.dcx().emit_err(diagnostics::Ok { span: target_span });
204 }
205 }
206 }
207}
208
209fn dump_graph(graph: &DepGraph) {
210 let Some(retained) = &graph.retained_dep_graph() else {
211 return;
212 };
213
214 let path: String = env::var("RUST_DEP_GRAPH").unwrap_or_else(|_| "dep_graph".to_string());
215
216 let nodes = match env::var("RUST_DEP_GRAPH_FILTER") {
217 Ok(string) => {
218 let edge_filter =
220 EdgeFilter::new(&string).unwrap_or_else(|e| ::rustc_span::macros::bug_impl(None, format_args!("invalid filter: {0}", e),
Location::caller())bug!("invalid filter: {}", e));
221 let sources = node_set(retained, &edge_filter.source);
222 let targets = node_set(retained, &edge_filter.target);
223 filter_nodes(retained, &sources, &targets)
224 }
225 Err(_) => retained.nodes().into_iter().collect(),
226 };
227 let edges = filter_edges(retained, &nodes);
228
229 {
230 let txt_path = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.txt", path))
})format!("{path}.txt");
232 let mut file = File::create_buffered(&txt_path).unwrap();
233 for (source, target) in &edges {
234 file.write_fmt(format_args!("{0:?} -> {1:?}\n", source, target))write!(file, "{source:?} -> {target:?}\n").unwrap();
235 }
236 }
237
238 {
239 let dot_path = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.dot", path))
})format!("{path}.dot");
241 let mut v = Vec::new();
242 dot::render(
243 &GraphvizDepGraph {
244 dep_graph: graph.clone(),
245 nodes: nodes.clone(),
246 edges: edges.into_iter().map(|(&a, &b)| (a, b)).clone().collect(),
247 },
248 &mut v,
249 )
250 .unwrap();
251 fs::write(dot_path, v).unwrap();
252 }
253}
254
255#[allow(missing_docs)]
256struct GraphvizDepGraph<'g> {
257 dep_graph: DepGraph,
258 nodes: FxIndexSet<&'g DepNode>,
259 edges: Vec<(DepNode, DepNode)>,
260}
261
262impl<'a> dot::GraphWalk<'a> for GraphvizDepGraph<'a> {
263 type Node = DepNode;
264 type Edge = (DepNode, DepNode);
265 fn nodes(&self) -> dot::Nodes<'_, DepNode> {
266 let nodes: Vec<_> = self.nodes.iter().cloned().map(|&a| a).collect();
267 nodes.into()
268 }
269 fn edges(&self) -> dot::Edges<'_, (DepNode, DepNode)> {
270 self.edges[..].into()
271 }
272 fn source(&self, edge: &(DepNode, DepNode)) -> DepNode {
273 edge.0
274 }
275 fn target(&self, edge: &(DepNode, DepNode)) -> DepNode {
276 edge.1
277 }
278}
279
280impl<'a> dot::Labeller<'a> for GraphvizDepGraph<'a> {
281 type Node = DepNode;
282 type Edge = (DepNode, DepNode);
283 fn graph_id(&self) -> dot::Id<'_> {
284 dot::Id::new("DependencyGraph").unwrap()
285 }
286 fn node_id(&self, n: &DepNode) -> dot::Id<'_> {
287 let s: String = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", n))
})format!("{n:?}")
288 .chars()
289 .map(|c| if c == '_' || c.is_alphanumeric() { c } else { '_' })
290 .collect();
291 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/assert_dep_graph.rs:291",
"rustc_incremental::assert_dep_graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/assert_dep_graph.rs"),
::tracing_core::__macro_support::Option::Some(291u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("n={0:?} s={1:?}",
n, s) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("n={:?} s={:?}", n, s);
292 dot::Id::new(s).unwrap()
293 }
294 fn node_label(&self, n: &DepNode) -> dot::LabelText<'_> {
295 tls::with_opt(|opt_tcx| {
296 if let Some(tcx) = opt_tcx
297 && let Some(def_id) = n.extract_def_id(tcx)
298 {
299 dot::LabelText::label(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?} ({1})", n.kind,
tcx.def_path_debug_str(def_id)))
})format!("{:?} ({})", n.kind, tcx.def_path_debug_str(def_id)))
300 } else {
301 dot::LabelText::label(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", n.kind))
})format!("{:?}", n.kind))
302 }
303 })
304 }
305
306 fn node_style(&'a self, n: &DepNode) -> Style {
308 Style::Filled(match self.dep_graph.node_color(n) {
309 DepNodeColor::Green(_) => FillColor::Green,
310 DepNodeColor::Red => FillColor::Red,
311 DepNodeColor::Unknown => FillColor::Unspecified,
312 })
313 }
314}
315
316fn node_set<'g>(
320 graph: &'g RetainedDepGraph,
321 filter: &DepNodeFilter,
322) -> Option<FxIndexSet<&'g DepNode>> {
323 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/assert_dep_graph.rs:323",
"rustc_incremental::assert_dep_graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/assert_dep_graph.rs"),
::tracing_core::__macro_support::Option::Some(323u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("node_set(filter={0:?})",
filter) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("node_set(filter={:?})", filter);
324
325 if filter.accepts_all() {
326 return None;
327 }
328
329 Some(graph.nodes().into_iter().filter(|n| filter.test(n)).collect())
330}
331
332fn filter_nodes<'g>(
333 graph: &'g RetainedDepGraph,
334 sources: &Option<FxIndexSet<&'g DepNode>>,
335 targets: &Option<FxIndexSet<&'g DepNode>>,
336) -> FxIndexSet<&'g DepNode> {
337 if let Some(sources) = sources {
338 if let Some(targets) = targets {
339 walk_between(graph, sources, targets)
340 } else {
341 walk_nodes(graph, sources, OUTGOING)
342 }
343 } else if let Some(targets) = targets {
344 walk_nodes(graph, targets, INCOMING)
345 } else {
346 graph.nodes().into_iter().collect()
347 }
348}
349
350fn walk_nodes<'g>(
351 graph: &'g RetainedDepGraph,
352 starts: &FxIndexSet<&'g DepNode>,
353 direction: Direction,
354) -> FxIndexSet<&'g DepNode> {
355 let mut set = FxIndexSet::default();
356 for &start in starts {
357 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/assert_dep_graph.rs:357",
"rustc_incremental::assert_dep_graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/assert_dep_graph.rs"),
::tracing_core::__macro_support::Option::Some(357u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("walk_nodes: start={0:?} outgoing?={1:?}",
start, direction == OUTGOING) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("walk_nodes: start={:?} outgoing?={:?}", start, direction == OUTGOING);
358 if set.insert(start) {
359 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]];
360 while let Some(index) = stack.pop() {
361 for (_, edge) in graph.inner.adjacent_edges(index, direction) {
362 let neighbor_index = edge.source_or_target(direction);
363 let neighbor = graph.inner.node_data(neighbor_index);
364 if set.insert(neighbor) {
365 stack.push(neighbor_index);
366 }
367 }
368 }
369 }
370 }
371 set
372}
373
374fn walk_between<'g>(
375 graph: &'g RetainedDepGraph,
376 sources: &FxIndexSet<&'g DepNode>,
377 targets: &FxIndexSet<&'g DepNode>,
378) -> FxIndexSet<&'g DepNode> {
379 #[derive(#[automatically_derived]impl ::core::marker::Copy for State { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for State {
}
#[automatically_derived]impl ::core::clone::Clone for State {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for State { }
#[automatically_derived]impl ::core::cmp::PartialEq for State {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
385 enum State {
386 Undecided,
387 Deciding,
388 Included,
389 Excluded,
390 }
391
392 let mut node_states = ::alloc::vec::from_elem_global(State::Undecided, graph.inner.len_nodes())vec![State::Undecided; graph.inner.len_nodes()];
393
394 for &target in targets {
395 node_states[graph.indices[target].0] = State::Included;
396 }
397
398 for source in sources.iter().map(|&n| graph.indices[n]) {
399 recurse(graph, &mut node_states, source);
400 }
401
402 return graph
403 .nodes()
404 .into_iter()
405 .filter(|&n| {
406 let index = graph.indices[n];
407 node_states[index.0] == State::Included
408 })
409 .collect();
410
411 fn recurse(graph: &RetainedDepGraph, node_states: &mut [State], node: NodeIndex) -> bool {
412 match node_states[node.0] {
413 State::Included => return true,
415
416 State::Excluded => return false,
418
419 State::Deciding => return false,
421
422 State::Undecided => {}
423 }
424
425 node_states[node.0] = State::Deciding;
426
427 for neighbor_index in graph.inner.successor_nodes(node) {
428 if recurse(graph, node_states, neighbor_index) {
429 node_states[node.0] = State::Included;
430 }
431 }
432
433 if node_states[node.0] == State::Deciding {
435 node_states[node.0] = State::Excluded;
436 false
437 } else {
438 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);
439 true
440 }
441 }
442}
443
444fn filter_edges<'g>(
445 graph: &'g RetainedDepGraph,
446 nodes: &'g FxIndexSet<&'g DepNode>,
447) -> Vec<(&'g DepNode, &'g DepNode)> {
448 let uniq: FxIndexSet<_> = graph
449 .edges()
450 .into_iter()
451 .filter(|&(&source, &target)| nodes.contains(&source) && nodes.contains(&target))
452 .collect();
453 uniq.into_iter().collect()
454}