1use std::io::Write;
2use std::iter;
3use std::ops::ControlFlow;
4use std::sync::Arc;
56use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7use rustc_errors::{Diag, DiagCtxtHandle};
8use rustc_hir::def::DefKind;
9use rustc_middle::query::{
10CycleError, QueryInfo, QueryJob, QueryJobId, QueryLatch, QueryStackDeferred, QueryStackFrame,
11QueryWaiter,
12};
13use rustc_middle::ty::TyCtxt;
14use rustc_session::Session;
15use rustc_span::{DUMMY_SP, Span};
1617use crate::plumbing::collect_active_jobs_from_all_queries;
1819/// Map from query job IDs to job information collected by
20/// `collect_active_jobs_from_all_queries`.
21#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryJobMap<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "QueryJobMap",
"map", &&self.map)
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::default::Default for QueryJobMap<'tcx> {
#[inline]
fn default() -> QueryJobMap<'tcx> {
QueryJobMap { map: ::core::default::Default::default() }
}
}Default)]
22pub struct QueryJobMap<'tcx> {
23 map: FxHashMap<QueryJobId, QueryJobInfo<'tcx>>,
24}
2526impl<'tcx> QueryJobMap<'tcx> {
27/// Adds information about a job ID to the job map.
28 ///
29 /// Should only be called by `gather_active_jobs_inner`.
30pub(crate) fn insert(&mut self, id: QueryJobId, info: QueryJobInfo<'tcx>) {
31self.map.insert(id, info);
32 }
3334fn frame_of(&self, id: QueryJobId) -> &QueryStackFrame<QueryStackDeferred<'tcx>> {
35&self.map[&id].frame
36 }
3738fn span_of(&self, id: QueryJobId) -> Span {
39self.map[&id].job.span
40 }
4142fn parent_of(&self, id: QueryJobId) -> Option<QueryJobId> {
43self.map[&id].job.parent
44 }
4546fn latch_of(&self, id: QueryJobId) -> Option<&QueryLatch<'tcx>> {
47self.map[&id].job.latch.as_ref()
48 }
49}
5051#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for QueryJobInfo<'tcx> {
#[inline]
fn clone(&self) -> QueryJobInfo<'tcx> {
QueryJobInfo {
frame: ::core::clone::Clone::clone(&self.frame),
job: ::core::clone::Clone::clone(&self.job),
}
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryJobInfo<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "QueryJobInfo",
"frame", &self.frame, "job", &&self.job)
}
}Debug)]
52pub(crate) struct QueryJobInfo<'tcx> {
53pub(crate) frame: QueryStackFrame<QueryStackDeferred<'tcx>>,
54pub(crate) job: QueryJob<'tcx>,
55}
5657pub(crate) fn find_cycle_in_stack<'tcx>(
58 id: QueryJobId,
59 job_map: QueryJobMap<'tcx>,
60 current_job: &Option<QueryJobId>,
61 span: Span,
62) -> CycleError<QueryStackDeferred<'tcx>> {
63// Find the waitee amongst `current_job` parents
64let mut cycle = Vec::new();
65let mut current_job = Option::clone(current_job);
6667while let Some(job) = current_job {
68let info = &job_map.map[&job];
69 cycle.push(QueryInfo { span: info.job.span, frame: info.frame.clone() });
7071if job == id {
72 cycle.reverse();
7374// This is the end of the cycle
75 // The span entry we included was for the usage
76 // of the cycle itself, and not part of the cycle
77 // Replace it with the span which caused the cycle to form
78cycle[0].span = span;
79// Find out why the cycle itself was used
80let usage = try {
81let parent = info.job.parent?;
82 (info.job.span, job_map.frame_of(parent).clone())
83 };
84return CycleError { usage, cycle };
85 }
8687 current_job = info.job.parent;
88 }
8990{ ::core::panicking::panic_fmt(format_args!("did not find a cycle")); }panic!("did not find a cycle")91}
9293#[cold]
94#[inline(never)]
95pub(crate) fn find_dep_kind_root<'tcx>(
96 id: QueryJobId,
97 job_map: QueryJobMap<'tcx>,
98) -> (QueryJobInfo<'tcx>, usize) {
99let mut depth = 1;
100let info = &job_map.map[&id];
101let dep_kind = info.frame.dep_kind;
102let mut current_id = info.job.parent;
103let mut last_layout = (info.clone(), depth);
104105while let Some(id) = current_id {
106let info = &job_map.map[&id];
107if info.frame.dep_kind == dep_kind {
108 depth += 1;
109 last_layout = (info.clone(), depth);
110 }
111 current_id = info.job.parent;
112 }
113last_layout114}
115116/// A resumable waiter of a query. The usize is the index into waiters in the query's latch
117type Waiter = (QueryJobId, usize);
118119/// Visits all the non-resumable and resumable waiters of a query.
120/// Only waiters in a query are visited.
121/// `visit` is called for every waiter and is passed a query waiting on `query`
122/// and a span indicating the reason the query waited on `query`.
123/// If `visit` returns `Break`, this function also returns `Break`,
124/// and if all `visit` calls returns `Continue` it also returns `Continue`.
125/// For visits of non-resumable waiters it returns the return value of `visit`.
126/// For visits of resumable waiters it returns information required to resume that waiter.
127fn visit_waiters<'tcx>(
128 job_map: &QueryJobMap<'tcx>,
129 query: QueryJobId,
130mut visit: impl FnMut(Span, QueryJobId) -> ControlFlow<Option<Waiter>>,
131) -> ControlFlow<Option<Waiter>> {
132// Visit the parent query which is a non-resumable waiter since it's on the same stack
133if let Some(parent) = job_map.parent_of(query) {
134visit(job_map.span_of(query), parent)?;
135 }
136137// Visit the explicit waiters which use condvars and are resumable
138if let Some(latch) = job_map.latch_of(query) {
139for (i, waiter) in latch.info.lock().waiters.iter().enumerate() {
140if let Some(waiter_query) = waiter.query {
141// Return a value which indicates that this waiter can be resumed
142visit(waiter.span, waiter_query).map_break(|_| Some((query, i)))?;
143 }
144 }
145 }
146147 ControlFlow::Continue(())
148}
149150/// Look for query cycles by doing a depth first search starting at `query`.
151/// `span` is the reason for the `query` to execute. This is initially DUMMY_SP.
152/// If a cycle is detected, this initial value is replaced with the span causing
153/// the cycle.
154fn cycle_check<'tcx>(
155 job_map: &QueryJobMap<'tcx>,
156 query: QueryJobId,
157 span: Span,
158 stack: &mut Vec<(Span, QueryJobId)>,
159 visited: &mut FxHashSet<QueryJobId>,
160) -> ControlFlow<Option<Waiter>> {
161if !visited.insert(query) {
162return if let Some(p) = stack.iter().position(|q| q.1 == query) {
163// We detected a query cycle, fix up the initial span and return Some
164165 // Remove previous stack entries
166stack.drain(0..p);
167// Replace the span for the first query with the cycle cause
168stack[0].0 = span;
169 ControlFlow::Break(None)
170 } else {
171 ControlFlow::Continue(())
172 };
173 }
174175// Query marked as visited is added it to the stack
176stack.push((span, query));
177178// Visit all the waiters
179let r = visit_waiters(job_map, query, |span, successor| {
180cycle_check(job_map, successor, span, stack, visited)
181 });
182183// Remove the entry in our stack if we didn't find a cycle
184if r.is_continue() {
185stack.pop();
186 }
187188r189}
190191/// Finds out if there's a path to the compiler root (aka. code which isn't in a query)
192/// from `query` without going through any of the queries in `visited`.
193/// This is achieved with a depth first search.
194fn connected_to_root<'tcx>(
195 job_map: &QueryJobMap<'tcx>,
196 query: QueryJobId,
197 visited: &mut FxHashSet<QueryJobId>,
198) -> ControlFlow<Option<Waiter>> {
199// We already visited this or we're deliberately ignoring it
200if !visited.insert(query) {
201return ControlFlow::Continue(());
202 }
203204// This query is connected to the root (it has no query parent), return true
205if job_map.parent_of(query).is_none() {
206return ControlFlow::Break(None);
207 }
208209visit_waiters(job_map, query, |_, successor| connected_to_root(job_map, successor, visited))
210}
211212// Deterministically pick an query from a list
213fn pick_query<'a, 'tcx, T, F>(job_map: &QueryJobMap<'tcx>, queries: &'a [T], f: F) -> &'a T
214where
215F: Fn(&T) -> (Span, QueryJobId),
216{
217// Deterministically pick an entry point
218 // FIXME: Sort this instead
219queries220 .iter()
221 .min_by_key(|v| {
222let (span, query) = f(v);
223let hash = job_map.frame_of(query).hash;
224// Prefer entry points which have valid spans for nicer error messages
225 // We add an integer to the tuple ensuring that entry points
226 // with valid spans are picked first
227let span_cmp = if span == DUMMY_SP { 1 } else { 0 };
228 (span_cmp, hash)
229 })
230 .unwrap()
231}
232233/// Looks for query cycles starting from the last query in `jobs`.
234/// If a cycle is found, all queries in the cycle is removed from `jobs` and
235/// the function return true.
236/// If a cycle was not found, the starting query is removed from `jobs` and
237/// the function returns false.
238fn remove_cycle<'tcx>(
239 job_map: &QueryJobMap<'tcx>,
240 jobs: &mut Vec<QueryJobId>,
241 wakelist: &mut Vec<Arc<QueryWaiter<'tcx>>>,
242) -> bool {
243let mut visited = FxHashSet::default();
244let mut stack = Vec::new();
245// Look for a cycle starting with the last query in `jobs`
246if let ControlFlow::Break(waiter) =
247cycle_check(job_map, jobs.pop().unwrap(), DUMMY_SP, &mut stack, &mut visited)
248 {
249// The stack is a vector of pairs of spans and queries; reverse it so that
250 // the earlier entries require later entries
251let (mut spans, queries): (Vec<_>, Vec<_>) = stack.into_iter().rev().unzip();
252253// Shift the spans so that queries are matched with the span for their waitee
254spans.rotate_right(1);
255256// Zip them back together
257let mut stack: Vec<_> = iter::zip(spans, queries).collect();
258259// Remove the queries in our cycle from the list of jobs to look at
260for r in &stack {
261if let Some(pos) = jobs.iter().position(|j| j == &r.1) {
262 jobs.remove(pos);
263 }
264 }
265266// Find the queries in the cycle which are
267 // connected to queries outside the cycle
268let entry_points = stack269 .iter()
270 .filter_map(|&(span, query)| {
271if job_map.parent_of(query).is_none() {
272// This query is connected to the root (it has no query parent)
273Some((span, query, None))
274 } else {
275let mut waiters = Vec::new();
276// Find all the direct waiters who lead to the root
277let _ = visit_waiters(job_map, query, |span, waiter| {
278// Mark all the other queries in the cycle as already visited
279let mut visited = FxHashSet::from_iter(stack.iter().map(|q| q.1));
280281if connected_to_root(job_map, waiter, &mut visited).is_break() {
282waiters.push((span, waiter));
283 }
284285 ControlFlow::Continue(())
286 });
287if waiters.is_empty() {
288None289 } else {
290// Deterministically pick one of the waiters to show to the user
291let waiter = *pick_query(job_map, &waiters, |s| *s);
292Some((span, query, Some(waiter)))
293 }
294 }
295 })
296 .collect::<Vec<(Span, QueryJobId, Option<(Span, QueryJobId)>)>>();
297298// Deterministically pick an entry point
299let (_, entry_point, usage) = pick_query(job_map, &entry_points, |e| (e.0, e.1));
300301// Shift the stack so that our entry point is first
302let entry_point_pos = stack.iter().position(|(_, query)| query == entry_point);
303if let Some(pos) = entry_point_pos {
304stack.rotate_left(pos);
305 }
306307let usage = usage.map(|(span, job)| (span, job_map.frame_of(job).clone()));
308309// Create the cycle error
310let error = CycleError {
311usage,
312 cycle: stack313 .iter()
314 .map(|&(span, job)| QueryInfo { span, frame: job_map.frame_of(job).clone() })
315 .collect(),
316 };
317318// We unwrap `waiter` here since there must always be one
319 // edge which is resumable / waited using a query latch
320let (waitee_query, waiter_idx) = waiter.unwrap();
321322// Extract the waiter we want to resume
323let waiter = job_map.latch_of(waitee_query).unwrap().extract_waiter(waiter_idx);
324325// Set the cycle error so it will be picked up when resumed
326*waiter.cycle.lock() = Some(error);
327328// Put the waiter on the list of things to resume
329wakelist.push(waiter);
330331true
332} else {
333false
334}
335}
336337/// Detects query cycles by using depth first search over all active query jobs.
338/// If a query cycle is found it will break the cycle by finding an edge which
339/// uses a query latch and then resuming that waiter.
340/// There may be multiple cycles involved in a deadlock, so this searches
341/// all active queries for cycles before finally resuming all the waiters at once.
342pub fn break_query_cycles<'tcx>(
343 job_map: QueryJobMap<'tcx>,
344 registry: &rustc_thread_pool::Registry,
345) {
346let mut wakelist = Vec::new();
347// It is OK per the comments:
348 // - https://github.com/rust-lang/rust/pull/131200#issuecomment-2798854932
349 // - https://github.com/rust-lang/rust/pull/131200#issuecomment-2798866392
350#[allow(rustc::potential_query_instability)]
351let mut jobs: Vec<QueryJobId> = job_map.map.keys().copied().collect();
352353let mut found_cycle = false;
354355while jobs.len() > 0 {
356if remove_cycle(&job_map, &mut jobs, &mut wakelist) {
357 found_cycle = true;
358 }
359 }
360361// Check that a cycle was found. It is possible for a deadlock to occur without
362 // a query cycle if a query which can be waited on uses Rayon to do multithreading
363 // internally. Such a query (X) may be executing on 2 threads (A and B) and A may
364 // wait using Rayon on B. Rayon may then switch to executing another query (Y)
365 // which in turn will wait on X causing a deadlock. We have a false dependency from
366 // X to Y due to Rayon waiting and a true dependency from Y to X. The algorithm here
367 // only considers the true dependency and won't detect a cycle.
368if !found_cycle {
369{
::core::panicking::panic_fmt(format_args!("deadlock detected as we\'re unable to find a query cycle to break\ncurrent query map:\n{0:#?}",
job_map));
};panic!(
370"deadlock detected as we're unable to find a query cycle to break\n\
371 current query map:\n{job_map:#?}",
372 );
373 }
374375// Mark all the thread we're about to wake up as unblocked. This needs to be done before
376 // we wake the threads up as otherwise Rayon could detect a deadlock if a thread we
377 // resumed fell asleep and this thread had yet to mark the remaining threads as unblocked.
378for _ in 0..wakelist.len() {
379 rustc_thread_pool::mark_unblocked(registry);
380 }
381382for waiter in wakelist.into_iter() {
383 waiter.condvar.notify_one();
384 }
385}
386387pub fn print_query_stack<'tcx>(
388 tcx: TyCtxt<'tcx>,
389mut current_query: Option<QueryJobId>,
390 dcx: DiagCtxtHandle<'_>,
391 limit_frames: Option<usize>,
392mut file: Option<std::fs::File>,
393) -> usize {
394// Be careful relying on global state here: this code is called from
395 // a panic hook, which means that the global `DiagCtxt` may be in a weird
396 // state if it was responsible for triggering the panic.
397let mut count_printed = 0;
398let mut count_total = 0;
399400// Make use of a partial query job map if we fail to take locks collecting active queries.
401let job_map: QueryJobMap<'_> = collect_active_jobs_from_all_queries(tcx, false)
402 .unwrap_or_else(|partial_job_map| partial_job_map);
403404if let Some(ref mut file) = file {
405let _ = file.write_fmt(format_args!("\n\nquery stack during panic:\n"))writeln!(file, "\n\nquery stack during panic:");
406 }
407while let Some(query) = current_query {
408let Some(query_info) = job_map.map.get(&query) else {
409break;
410 };
411let query_extra = query_info.frame.info.extract();
412if Some(count_printed) < limit_frames || limit_frames.is_none() {
413// Only print to stderr as many stack frames as `num_frames` when present.
414 dcx.struct_failure_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#{0} [{1:?}] {2}", count_printed,
query_info.frame.dep_kind, query_extra.description))
})format!(
415"#{} [{:?}] {}",
416 count_printed, query_info.frame.dep_kind, query_extra.description
417 ))
418 .with_span(query_info.job.span)
419 .emit();
420 count_printed += 1;
421 }
422423if let Some(ref mut file) = file {
424let _ = file.write_fmt(format_args!("#{0} [{1:?}] {2}\n", count_total,
query_info.frame.dep_kind, query_extra.description))writeln!(
425 file,
426"#{} [{:?}] {}",
427 count_total, query_info.frame.dep_kind, query_extra.description
428 );
429 }
430431 current_query = query_info.job.parent;
432 count_total += 1;
433 }
434435if let Some(ref mut file) = file {
436let _ = file.write_fmt(format_args!("end of query stack\n"))writeln!(file, "end of query stack");
437 }
438count_total439}
440441#[inline(never)]
442#[cold]
443pub(crate) fn report_cycle<'a>(
444 sess: &'a Session,
445CycleError { usage, cycle: stack }: &CycleError,
446) -> Diag<'a> {
447if !!stack.is_empty() {
::core::panicking::panic("assertion failed: !stack.is_empty()")
};assert!(!stack.is_empty());
448449let span = stack[0].frame.info.default_span(stack[1 % stack.len()].span);
450451let mut cycle_stack = Vec::new();
452453use crate::error::StackCount;
454let stack_count = if stack.len() == 1 { StackCount::Single } else { StackCount::Multiple };
455456for i in 1..stack.len() {
457let frame = &stack[i].frame;
458let span = frame.info.default_span(stack[(i + 1) % stack.len()].span);
459 cycle_stack
460 .push(crate::error::CycleStack { span, desc: frame.info.description.to_owned() });
461 }
462463let mut cycle_usage = None;
464if let Some((span, ref query)) = *usage {
465cycle_usage = Some(crate::error::CycleUsage {
466 span: query.info.default_span(span),
467 usage: query.info.description.to_string(),
468 });
469 }
470471let alias =
472if stack.iter().all(|entry| #[allow(non_exhaustive_omitted_patterns)] match entry.frame.info.def_kind {
Some(DefKind::TyAlias) => true,
_ => false,
}matches!(entry.frame.info.def_kind, Some(DefKind::TyAlias))) {
473Some(crate::error::Alias::Ty)
474 } else if stack.iter().all(|entry| entry.frame.info.def_kind == Some(DefKind::TraitAlias)) {
475Some(crate::error::Alias::Trait)
476 } else {
477None478 };
479480let cycle_diag = crate::error::Cycle {
481span,
482cycle_stack,
483 stack_bottom: stack[0].frame.info.description.to_owned(),
484alias,
485cycle_usage,
486stack_count,
487 note_span: (),
488 };
489490sess.dcx().create_err(cycle_diag)
491}