1use std::io::Write;
2use std::iter;
3use std::sync::Arc;
45use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6use rustc_errors::{Diag, DiagCtxtHandle};
7use rustc_hir::def::DefKind;
8use rustc_query_system::query::{
9CycleError, QueryInfo, QueryJob, QueryJobId, QueryLatch, QueryStackDeferred, QueryStackFrame,
10QueryWaiter,
11};
12use rustc_session::Session;
13use rustc_span::{DUMMY_SP, Span};
1415use crate::QueryCtxt;
16use crate::dep_graph::DepContext;
1718/// Map from query job IDs to job information collected by
19/// `collect_active_jobs_from_all_queries`.
20#[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)]
21pub struct QueryJobMap<'tcx> {
22 map: FxHashMap<QueryJobId, QueryJobInfo<'tcx>>,
23}
2425impl<'tcx> QueryJobMap<'tcx> {
26/// Adds information about a job ID to the job map.
27 ///
28 /// Should only be called by `gather_active_jobs_inner`.
29pub(crate) fn insert(&mut self, id: QueryJobId, info: QueryJobInfo<'tcx>) {
30self.map.insert(id, info);
31 }
3233fn frame_of(&self, id: QueryJobId) -> &QueryStackFrame<QueryStackDeferred<'tcx>> {
34&self.map[&id].frame
35 }
3637fn span_of(&self, id: QueryJobId) -> Span {
38self.map[&id].job.span
39 }
4041fn parent_of(&self, id: QueryJobId) -> Option<QueryJobId> {
42self.map[&id].job.parent
43 }
4445fn latch_of(&self, id: QueryJobId) -> Option<&QueryLatch<'tcx>> {
46self.map[&id].job.latch.as_ref()
47 }
48}
4950#[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)]
51pub(crate) struct QueryJobInfo<'tcx> {
52pub(crate) frame: QueryStackFrame<QueryStackDeferred<'tcx>>,
53pub(crate) job: QueryJob<'tcx>,
54}
5556pub(crate) fn find_cycle_in_stack<'tcx>(
57 id: QueryJobId,
58 job_map: QueryJobMap<'tcx>,
59 current_job: &Option<QueryJobId>,
60 span: Span,
61) -> CycleError<QueryStackDeferred<'tcx>> {
62// Find the waitee amongst `current_job` parents
63let mut cycle = Vec::new();
64let mut current_job = Option::clone(current_job);
6566while let Some(job) = current_job {
67let info = &job_map.map[&job];
68 cycle.push(QueryInfo { span: info.job.span, frame: info.frame.clone() });
6970if job == id {
71 cycle.reverse();
7273// This is the end of the cycle
74 // The span entry we included was for the usage
75 // of the cycle itself, and not part of the cycle
76 // Replace it with the span which caused the cycle to form
77cycle[0].span = span;
78// Find out why the cycle itself was used
79let usage = try {
80let parent = info.job.parent?;
81 (info.job.span, job_map.frame_of(parent).clone())
82 };
83return CycleError { usage, cycle };
84 }
8586 current_job = info.job.parent;
87 }
8889{ ::core::panicking::panic_fmt(format_args!("did not find a cycle")); }panic!("did not find a cycle")90}
9192#[cold]
93#[inline(never)]
94pub(crate) fn find_dep_kind_root<'tcx>(
95 id: QueryJobId,
96 job_map: QueryJobMap<'tcx>,
97) -> (QueryJobInfo<'tcx>, usize) {
98let mut depth = 1;
99let info = &job_map.map[&id];
100let dep_kind = info.frame.dep_kind;
101let mut current_id = info.job.parent;
102let mut last_layout = (info.clone(), depth);
103104while let Some(id) = current_id {
105let info = &job_map.map[&id];
106if info.frame.dep_kind == dep_kind {
107 depth += 1;
108 last_layout = (info.clone(), depth);
109 }
110 current_id = info.job.parent;
111 }
112last_layout113}
114115/// A resumable waiter of a query. The usize is the index into waiters in the query's latch
116type Waiter = (QueryJobId, usize);
117118/// Visits all the non-resumable and resumable waiters of a query.
119/// Only waiters in a query are visited.
120/// `visit` is called for every waiter and is passed a query waiting on `query_ref`
121/// and a span indicating the reason the query waited on `query_ref`.
122/// If `visit` returns Some, this function returns.
123/// For visits of non-resumable waiters it returns the return value of `visit`.
124/// For visits of resumable waiters it returns Some(Some(Waiter)) which has the
125/// required information to resume the waiter.
126/// If all `visit` calls returns None, this function also returns None.
127fn visit_waiters<'tcx, F>(
128 job_map: &QueryJobMap<'tcx>,
129 query: QueryJobId,
130mut visit: F,
131) -> Option<Option<Waiter>>
132where
133F: FnMut(Span, QueryJobId) -> Option<Option<Waiter>>,
134{
135// Visit the parent query which is a non-resumable waiter since it's on the same stack
136if let Some(parent) = job_map.parent_of(query)
137 && let Some(cycle) = visit(job_map.span_of(query), parent)
138 {
139return Some(cycle);
140 }
141142// Visit the explicit waiters which use condvars and are resumable
143if let Some(latch) = job_map.latch_of(query) {
144for (i, waiter) in latch.info.lock().waiters.iter().enumerate() {
145if let Some(waiter_query) = waiter.query {
146if visit(waiter.span, waiter_query).is_some() {
147// Return a value which indicates that this waiter can be resumed
148return Some(Some((query, i)));
149 }
150 }
151 }
152 }
153154None155}
156157/// Look for query cycles by doing a depth first search starting at `query`.
158/// `span` is the reason for the `query` to execute. This is initially DUMMY_SP.
159/// If a cycle is detected, this initial value is replaced with the span causing
160/// the cycle.
161fn cycle_check<'tcx>(
162 job_map: &QueryJobMap<'tcx>,
163 query: QueryJobId,
164 span: Span,
165 stack: &mut Vec<(Span, QueryJobId)>,
166 visited: &mut FxHashSet<QueryJobId>,
167) -> Option<Option<Waiter>> {
168if !visited.insert(query) {
169return if let Some(p) = stack.iter().position(|q| q.1 == query) {
170// We detected a query cycle, fix up the initial span and return Some
171172 // Remove previous stack entries
173stack.drain(0..p);
174// Replace the span for the first query with the cycle cause
175stack[0].0 = span;
176Some(None)
177 } else {
178None179 };
180 }
181182// Query marked as visited is added it to the stack
183stack.push((span, query));
184185// Visit all the waiters
186let r = visit_waiters(job_map, query, |span, successor| {
187cycle_check(job_map, successor, span, stack, visited)
188 });
189190// Remove the entry in our stack if we didn't find a cycle
191if r.is_none() {
192stack.pop();
193 }
194195r196}
197198/// Finds out if there's a path to the compiler root (aka. code which isn't in a query)
199/// from `query` without going through any of the queries in `visited`.
200/// This is achieved with a depth first search.
201fn connected_to_root<'tcx>(
202 job_map: &QueryJobMap<'tcx>,
203 query: QueryJobId,
204 visited: &mut FxHashSet<QueryJobId>,
205) -> bool {
206// We already visited this or we're deliberately ignoring it
207if !visited.insert(query) {
208return false;
209 }
210211// This query is connected to the root (it has no query parent), return true
212if job_map.parent_of(query).is_none() {
213return true;
214 }
215216visit_waiters(job_map, query, |_, successor| {
217connected_to_root(job_map, successor, visited).then_some(None)
218 })
219 .is_some()
220}
221222// Deterministically pick an query from a list
223fn pick_query<'a, 'tcx, T, F>(job_map: &QueryJobMap<'tcx>, queries: &'a [T], f: F) -> &'a T
224where
225F: Fn(&T) -> (Span, QueryJobId),
226{
227// Deterministically pick an entry point
228 // FIXME: Sort this instead
229queries230 .iter()
231 .min_by_key(|v| {
232let (span, query) = f(v);
233let hash = job_map.frame_of(query).hash;
234// Prefer entry points which have valid spans for nicer error messages
235 // We add an integer to the tuple ensuring that entry points
236 // with valid spans are picked first
237let span_cmp = if span == DUMMY_SP { 1 } else { 0 };
238 (span_cmp, hash)
239 })
240 .unwrap()
241}
242243/// Looks for query cycles starting from the last query in `jobs`.
244/// If a cycle is found, all queries in the cycle is removed from `jobs` and
245/// the function return true.
246/// If a cycle was not found, the starting query is removed from `jobs` and
247/// the function returns false.
248fn remove_cycle<'tcx>(
249 job_map: &QueryJobMap<'tcx>,
250 jobs: &mut Vec<QueryJobId>,
251 wakelist: &mut Vec<Arc<QueryWaiter<'tcx>>>,
252) -> bool {
253let mut visited = FxHashSet::default();
254let mut stack = Vec::new();
255// Look for a cycle starting with the last query in `jobs`
256if let Some(waiter) =
257cycle_check(job_map, jobs.pop().unwrap(), DUMMY_SP, &mut stack, &mut visited)
258 {
259// The stack is a vector of pairs of spans and queries; reverse it so that
260 // the earlier entries require later entries
261let (mut spans, queries): (Vec<_>, Vec<_>) = stack.into_iter().rev().unzip();
262263// Shift the spans so that queries are matched with the span for their waitee
264spans.rotate_right(1);
265266// Zip them back together
267let mut stack: Vec<_> = iter::zip(spans, queries).collect();
268269// Remove the queries in our cycle from the list of jobs to look at
270for r in &stack {
271if let Some(pos) = jobs.iter().position(|j| j == &r.1) {
272 jobs.remove(pos);
273 }
274 }
275276// Find the queries in the cycle which are
277 // connected to queries outside the cycle
278let entry_points = stack279 .iter()
280 .filter_map(|&(span, query)| {
281if job_map.parent_of(query).is_none() {
282// This query is connected to the root (it has no query parent)
283Some((span, query, None))
284 } else {
285let mut waiters = Vec::new();
286// Find all the direct waiters who lead to the root
287visit_waiters(job_map, query, |span, waiter| {
288// Mark all the other queries in the cycle as already visited
289let mut visited = FxHashSet::from_iter(stack.iter().map(|q| q.1));
290291if connected_to_root(job_map, waiter, &mut visited) {
292waiters.push((span, waiter));
293 }
294295None296 });
297if waiters.is_empty() {
298None299 } else {
300// Deterministically pick one of the waiters to show to the user
301let waiter = *pick_query(job_map, &waiters, |s| *s);
302Some((span, query, Some(waiter)))
303 }
304 }
305 })
306 .collect::<Vec<(Span, QueryJobId, Option<(Span, QueryJobId)>)>>();
307308// Deterministically pick an entry point
309let (_, entry_point, usage) = pick_query(job_map, &entry_points, |e| (e.0, e.1));
310311// Shift the stack so that our entry point is first
312let entry_point_pos = stack.iter().position(|(_, query)| query == entry_point);
313if let Some(pos) = entry_point_pos {
314stack.rotate_left(pos);
315 }
316317let usage = usage.map(|(span, job)| (span, job_map.frame_of(job).clone()));
318319// Create the cycle error
320let error = CycleError {
321usage,
322 cycle: stack323 .iter()
324 .map(|&(span, job)| QueryInfo { span, frame: job_map.frame_of(job).clone() })
325 .collect(),
326 };
327328// We unwrap `waiter` here since there must always be one
329 // edge which is resumable / waited using a query latch
330let (waitee_query, waiter_idx) = waiter.unwrap();
331332// Extract the waiter we want to resume
333let waiter = job_map.latch_of(waitee_query).unwrap().extract_waiter(waiter_idx);
334335// Set the cycle error so it will be picked up when resumed
336*waiter.cycle.lock() = Some(error);
337338// Put the waiter on the list of things to resume
339wakelist.push(waiter);
340341true
342} else {
343false
344}
345}
346347/// Detects query cycles by using depth first search over all active query jobs.
348/// If a query cycle is found it will break the cycle by finding an edge which
349/// uses a query latch and then resuming that waiter.
350/// There may be multiple cycles involved in a deadlock, so this searches
351/// all active queries for cycles before finally resuming all the waiters at once.
352pub fn break_query_cycles<'tcx>(
353 job_map: QueryJobMap<'tcx>,
354 registry: &rustc_thread_pool::Registry,
355) {
356let mut wakelist = Vec::new();
357// It is OK per the comments:
358 // - https://github.com/rust-lang/rust/pull/131200#issuecomment-2798854932
359 // - https://github.com/rust-lang/rust/pull/131200#issuecomment-2798866392
360#[allow(rustc::potential_query_instability)]
361let mut jobs: Vec<QueryJobId> = job_map.map.keys().copied().collect();
362363let mut found_cycle = false;
364365while jobs.len() > 0 {
366if remove_cycle(&job_map, &mut jobs, &mut wakelist) {
367 found_cycle = true;
368 }
369 }
370371// Check that a cycle was found. It is possible for a deadlock to occur without
372 // a query cycle if a query which can be waited on uses Rayon to do multithreading
373 // internally. Such a query (X) may be executing on 2 threads (A and B) and A may
374 // wait using Rayon on B. Rayon may then switch to executing another query (Y)
375 // which in turn will wait on X causing a deadlock. We have a false dependency from
376 // X to Y due to Rayon waiting and a true dependency from Y to X. The algorithm here
377 // only considers the true dependency and won't detect a cycle.
378if !found_cycle {
379{
::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!(
380"deadlock detected as we're unable to find a query cycle to break\n\
381 current query map:\n{job_map:#?}",
382 );
383 }
384385// Mark all the thread we're about to wake up as unblocked. This needs to be done before
386 // we wake the threads up as otherwise Rayon could detect a deadlock if a thread we
387 // resumed fell asleep and this thread had yet to mark the remaining threads as unblocked.
388for _ in 0..wakelist.len() {
389 rustc_thread_pool::mark_unblocked(registry);
390 }
391392for waiter in wakelist.into_iter() {
393 waiter.condvar.notify_one();
394 }
395}
396397pub fn print_query_stack<'tcx>(
398 qcx: QueryCtxt<'tcx>,
399mut current_query: Option<QueryJobId>,
400 dcx: DiagCtxtHandle<'_>,
401 limit_frames: Option<usize>,
402mut file: Option<std::fs::File>,
403) -> usize {
404// Be careful relying on global state here: this code is called from
405 // a panic hook, which means that the global `DiagCtxt` may be in a weird
406 // state if it was responsible for triggering the panic.
407let mut count_printed = 0;
408let mut count_total = 0;
409410// Make use of a partial query job map if we fail to take locks collecting active queries.
411let job_map: QueryJobMap<'_> = qcx412 .collect_active_jobs_from_all_queries(false)
413 .unwrap_or_else(|partial_job_map| partial_job_map);
414415if let Some(ref mut file) = file {
416let _ = file.write_fmt(format_args!("\n\nquery stack during panic:\n"))writeln!(file, "\n\nquery stack during panic:");
417 }
418while let Some(query) = current_query {
419let Some(query_info) = job_map.map.get(&query) else {
420break;
421 };
422let query_extra = query_info.frame.info.extract();
423if Some(count_printed) < limit_frames || limit_frames.is_none() {
424// Only print to stderr as many stack frames as `num_frames` when present.
425 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!(
426"#{} [{:?}] {}",
427 count_printed, query_info.frame.dep_kind, query_extra.description
428 ))
429 .with_span(query_info.job.span)
430 .emit();
431 count_printed += 1;
432 }
433434if let Some(ref mut file) = file {
435let _ = file.write_fmt(format_args!("#{0} [{1}] {2}\n", count_total,
qcx.tcx.dep_kind_vtable(query_info.frame.dep_kind).name,
query_extra.description))writeln!(
436 file,
437"#{} [{}] {}",
438 count_total,
439 qcx.tcx.dep_kind_vtable(query_info.frame.dep_kind).name,
440 query_extra.description
441 );
442 }
443444 current_query = query_info.job.parent;
445 count_total += 1;
446 }
447448if let Some(ref mut file) = file {
449let _ = file.write_fmt(format_args!("end of query stack\n"))writeln!(file, "end of query stack");
450 }
451count_total452}
453454#[inline(never)]
455#[cold]
456pub(crate) fn report_cycle<'a>(
457 sess: &'a Session,
458CycleError { usage, cycle: stack }: &CycleError,
459) -> Diag<'a> {
460if !!stack.is_empty() {
::core::panicking::panic("assertion failed: !stack.is_empty()")
};assert!(!stack.is_empty());
461462let span = stack[0].frame.info.default_span(stack[1 % stack.len()].span);
463464let mut cycle_stack = Vec::new();
465466use crate::error::StackCount;
467let stack_count = if stack.len() == 1 { StackCount::Single } else { StackCount::Multiple };
468469for i in 1..stack.len() {
470let frame = &stack[i].frame;
471let span = frame.info.default_span(stack[(i + 1) % stack.len()].span);
472 cycle_stack
473 .push(crate::error::CycleStack { span, desc: frame.info.description.to_owned() });
474 }
475476let mut cycle_usage = None;
477if let Some((span, ref query)) = *usage {
478cycle_usage = Some(crate::error::CycleUsage {
479 span: query.info.default_span(span),
480 usage: query.info.description.to_string(),
481 });
482 }
483484let alias =
485if 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))) {
486Some(crate::error::Alias::Ty)
487 } else if stack.iter().all(|entry| entry.frame.info.def_kind == Some(DefKind::TraitAlias)) {
488Some(crate::error::Alias::Trait)
489 } else {
490None491 };
492493let cycle_diag = crate::error::Cycle {
494span,
495cycle_stack,
496 stack_bottom: stack[0].frame.info.description.to_owned(),
497alias,
498cycle_usage,
499stack_count,
500 note_span: (),
501 };
502503sess.dcx().create_err(cycle_diag)
504}