1use std::io::Write;
2use std::ops::ControlFlow;
3use std::sync::Arc;
4use std::{iter, mem};
56use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7use rustc_errors::{Diag, DiagCtxtHandle};
8use rustc_hir::def::DefKind;
9use rustc_middle::queries::TaggedQueryKey;
10use rustc_middle::query::{Cycle, QueryJob, QueryJobId, QueryLatch, QueryStackFrame, QueryWaiter};
11use rustc_middle::ty::TyCtxt;
12use rustc_span::{DUMMY_SP, Span};
1314use crate::{CollectActiveJobsKind, collect_active_query_jobs};
1516/// Map from query job IDs to job information collected by
17/// `collect_active_query_jobs`.
18#[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)]
19pub struct QueryJobMap<'tcx> {
20 map: FxHashMap<QueryJobId, QueryJobInfo<'tcx>>,
21}
2223impl<'tcx> QueryJobMap<'tcx> {
24/// Adds information about a job ID to the job map.
25 ///
26 /// Should only be called by `collect_active_query_jobs_inner`.
27pub(crate) fn insert(&mut self, id: QueryJobId, info: QueryJobInfo<'tcx>) {
28self.map.insert(id, info);
29 }
3031fn tagged_key_of(&self, id: QueryJobId) -> TaggedQueryKey<'tcx> {
32self.map[&id].tagged_key
33 }
3435fn span_of(&self, id: QueryJobId) -> Span {
36self.map[&id].job.span
37 }
3839fn parent_of(&self, id: QueryJobId) -> Option<QueryJobId> {
40self.map[&id].job.parent
41 }
4243fn latch_of(&self, id: QueryJobId) -> Option<&QueryLatch<'tcx>> {
44self.map[&id].job.latch.as_ref()
45 }
46}
4748#[derive(#[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",
"tagged_key", &self.tagged_key, "job", &&self.job)
}
}Debug)]
49pub(crate) struct QueryJobInfo<'tcx> {
50pub(crate) tagged_key: TaggedQueryKey<'tcx>,
51pub(crate) job: QueryJob<'tcx>,
52}
5354pub(crate) fn find_cycle_in_stack<'tcx>(
55 id: QueryJobId,
56 job_map: QueryJobMap<'tcx>,
57 current_job: &Option<QueryJobId>,
58 span: Span,
59) -> Cycle<'tcx> {
60// Find the waitee amongst `current_job` parents.
61let mut frames = Vec::new();
62let mut current_job = Option::clone(current_job);
6364while let Some(job) = current_job {
65let info = &job_map.map[&job];
66 frames.push(QueryStackFrame { span: info.job.span, tagged_key: info.tagged_key });
6768if job == id {
69 frames.reverse();
7071// This is the end of the cycle. The span entry we included was for
72 // the usage of the cycle itself, and not part of the cycle.
73 // Replace it with the span which caused the cycle to form.
74frames[0].span = span;
75// Find out why the cycle itself was used.
76let usage = try {
77let parent = info.job.parent?;
78 QueryStackFrame { span: info.job.span, tagged_key: job_map.tagged_key_of(parent) }
79 };
80return Cycle { usage, frames };
81 }
8283 current_job = info.job.parent;
84 }
8586{ ::core::panicking::panic_fmt(format_args!("did not find a cycle")); }panic!("did not find a cycle")87}
8889/// Finds the query job closest to the root that is for the same query method as `id`
90/// (but not necessarily the same query key), and returns information about it.
91#[cold]
92#[inline(never)]
93pub(crate) fn find_dep_kind_root<'tcx>(
94 tcx: TyCtxt<'tcx>,
95 id: QueryJobId,
96 job_map: QueryJobMap<'tcx>,
97) -> (Span, String, usize) {
98let mut depth = 1;
99let mut info = &job_map.map[&id];
100// Two query jobs are for the same query method if they have the same
101 // `TaggedQueryKey` discriminant.
102let expected_query = mem::discriminant::<TaggedQueryKey<'tcx>>(&info.tagged_key);
103let mut last_info = info;
104105while let Some(id) = info.job.parent {
106 info = &job_map.map[&id];
107if mem::discriminant(&info.tagged_key) == expected_query {
108 depth += 1;
109 last_info = info;
110 }
111 }
112 (last_info.job.span, last_info.tagged_key.description(tcx), depth)
113}
114115/// The locaton of a resumable waiter. The usize is the index into waiters in the query's latch.
116/// We'll use this to remove the waiter using `QueryLatch::extract_waiter` if we're waking it up.
117type ResumableWaiterLocation = (QueryJobId, usize);
118119/// This abstracts over non-resumable waiters which are found in `QueryJob`'s `parent` field
120/// and resumable waiters are in `latch` field.
121struct AbstractedWaiter {
122/// The span corresponding to the reason for why we're waiting on this query.
123span: Span,
124/// The query which we are waiting from, if none the waiter is from a compiler root.
125parent: Option<QueryJobId>,
126 resumable: Option<ResumableWaiterLocation>,
127}
128129/// Returns all the non-resumable and resumable waiters of a query.
130/// This is used so we can uniformly loop over both non-resumable and resumable waiters.
131fn abstracted_waiters_of(job_map: &QueryJobMap<'_>, query: QueryJobId) -> Vec<AbstractedWaiter> {
132let mut result = Vec::new();
133134// Add the parent which is a non-resumable waiter since it's on the same stack
135result.push(AbstractedWaiter {
136 span: job_map.span_of(query),
137 parent: job_map.parent_of(query),
138 resumable: None,
139 });
140141// Add the explicit waiters which use condvars and are resumable
142if let Some(latch) = job_map.latch_of(query) {
143for (i, waiter) in latch.waiters.lock().as_ref().unwrap().iter().enumerate() {
144 result.push(AbstractedWaiter {
145 span: waiter.span,
146 parent: waiter.parent,
147 resumable: Some((query, i)),
148 });
149 }
150 }
151152result153}
154155/// Looks for a query cycle by doing a depth first search starting at `query`.
156/// `span` is the reason for the `query` to execute. This is initially DUMMY_SP.
157/// If a cycle is detected, this initial value is replaced with the span causing
158/// the cycle. `stack` will contain just the cycle on return if detected.
159fn find_cycle<'tcx>(
160 job_map: &QueryJobMap<'tcx>,
161 query: QueryJobId,
162 span: Span,
163 stack: &mut Vec<(Span, QueryJobId)>,
164 visited: &mut FxHashSet<QueryJobId>,
165) -> ControlFlow<Option<ResumableWaiterLocation>> {
166if !visited.insert(query) {
167return if let Some(pos) = stack.iter().position(|q| q.1 == query) {
168// We detected a query cycle, fix up the initial span and return Some
169170 // Remove previous stack entries
171stack.drain(0..pos);
172// Replace the span for the first query with the cycle cause
173stack[0].0 = span;
174 ControlFlow::Break(None)
175 } else {
176 ControlFlow::Continue(())
177 };
178 }
179180// Query marked as visited is added it to the stack
181stack.push((span, query));
182183// Visit all the waiters
184for abstracted_waiter in abstracted_waiters_of(job_map, query) {
185let Some(parent) = abstracted_waiter.parent else {
186// Skip waiters which are not queries
187continue;
188 };
189if let ControlFlow::Break(maybe_resumable) =
190 find_cycle(job_map, parent, abstracted_waiter.span, stack, visited)
191 {
192// Return the resumable waiter in `waiter.resumable` if present
193return ControlFlow::Break(abstracted_waiter.resumable.or(maybe_resumable));
194 }
195 }
196197// Remove the entry in our stack since we didn't find a cycle
198stack.pop();
199200 ControlFlow::Continue(())
201}
202203/// Finds out if there's a path to the compiler root (aka. code which isn't in a query)
204/// from `query` without going through any of the queries in `visited`.
205/// This is achieved with a depth first search.
206fn connected_to_root<'tcx>(
207 job_map: &QueryJobMap<'tcx>,
208 query: QueryJobId,
209 visited: &mut FxHashSet<QueryJobId>,
210) -> bool {
211// We already visited this or we're deliberately ignoring it
212if !visited.insert(query) {
213return false;
214 }
215216// Visit all the waiters
217for abstracted_waiter in abstracted_waiters_of(job_map, query) {
218match abstracted_waiter.parent {
219// This query is connected to the root
220None => return true,
221Some(parent) => {
222if connected_to_root(job_map, parent, visited) {
223return true;
224 }
225 }
226 }
227 }
228229false
230}
231232/// Processes a found query cycle into a `Cycle`
233fn process_cycle<'tcx>(job_map: &QueryJobMap<'tcx>, stack: Vec<(Span, QueryJobId)>) -> Cycle<'tcx> {
234// The stack is a vector of pairs of spans and queries; reverse it so that
235 // the earlier entries require later entries
236let (mut spans, queries): (Vec<_>, Vec<_>) = stack.into_iter().rev().unzip();
237238// Shift the spans so that queries are matched with the span for their waitee
239spans.rotate_right(1);
240241// Zip them back together
242let mut stack: Vec<_> = iter::zip(spans, queries).collect();
243244struct EntryPoint {
245 query_in_cycle: QueryJobId,
246 query_waiting_on_cycle: Option<(Span, QueryJobId)>,
247 }
248249// Find the queries in the cycle which are
250 // connected to queries outside the cycle
251let entry_points = stack252 .iter()
253 .filter_map(|&(_, query_in_cycle)| {
254let mut entrypoint = false;
255let mut query_waiting_on_cycle = None;
256257// Find a direct waiter who leads to the root
258for abstracted_waiter in abstracted_waiters_of(job_map, query_in_cycle) {
259let Some(parent) = abstracted_waiter.parent else {
260// The query in the cycle is directly connected to root.
261entrypoint = true;
262continue;
263 };
264265// Mark all the other queries in the cycle as already visited,
266 // so paths to the root through the cycle itself won't count.
267let mut visited = FxHashSet::from_iter(stack.iter().map(|q| q.1));
268269if connected_to_root(job_map, parent, &mut visited) {
270 query_waiting_on_cycle = Some((abstracted_waiter.span, parent));
271 entrypoint = true;
272break;
273 }
274 }
275276entrypoint.then_some(EntryPoint { query_in_cycle, query_waiting_on_cycle })
277 })
278 .collect::<Vec<EntryPoint>>();
279280// Pick an entry point, preferring ones with waiters
281let entry_point = entry_points282 .iter()
283 .find(|entry_point| entry_point.query_waiting_on_cycle.is_some())
284 .unwrap_or(&entry_points[0]);
285286// Shift the stack so that our entry point is first
287let entry_point_pos = stack.iter().position(|(_, query)| *query == entry_point.query_in_cycle);
288if let Some(pos) = entry_point_pos {
289stack.rotate_left(pos);
290 }
291292let usage = entry_point293 .query_waiting_on_cycle
294 .map(|(span, job)| QueryStackFrame { span, tagged_key: job_map.tagged_key_of(job) });
295296// Create the cycle error
297Cycle {
298usage,
299 frames: stack300 .iter()
301 .map(|&(span, job)| QueryStackFrame { span, tagged_key: job_map.tagged_key_of(job) })
302 .collect(),
303 }
304}
305306/// Looks for a query cycle starting at `query`.
307/// Returns a waiter to resume if a cycle is found.
308fn find_and_process_cycle<'tcx>(
309 job_map: &QueryJobMap<'tcx>,
310 query: QueryJobId,
311) -> Option<Arc<QueryWaiter<'tcx>>> {
312let mut visited = FxHashSet::default();
313let mut stack = Vec::new();
314if let ControlFlow::Break(resumable) =
315find_cycle(job_map, query, DUMMY_SP, &mut stack, &mut visited)
316 {
317// Create the cycle error
318let error = process_cycle(job_map, stack);
319320// We unwrap `resumable` here since there must always be one
321 // edge which is resumable / waited using a query latch
322let (waitee_query, waiter_idx) = resumable.unwrap();
323324// Extract the waiter we want to resume
325let waiter = job_map.latch_of(waitee_query).unwrap().extract_waiter(waiter_idx);
326327// Set the cycle error so it will be picked up when resumed
328*waiter.cycle.lock() = Some(error);
329330// Put the waiter on the list of things to resume
331Some(waiter)
332 } else {
333None334 }
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///
341/// There may be multiple cycles involved in a deadlock, but this only breaks one at a time so
342/// there will be multiple rounds through the deadlock handler if multiple cycles are present.
343#[allow(rustc::potential_query_instability)]
344pub fn break_query_cycle<'tcx>(job_map: QueryJobMap<'tcx>, registry: &rustc_thread_pool::Registry) {
345// Look for a cycle starting at each query job
346let waiter = job_map347 .map
348 .keys()
349 .find_map(|query| find_and_process_cycle(&job_map, *query))
350 .expect("unable to find a query cycle");
351352// Mark the thread we're about to wake up as unblocked.
353rustc_thread_pool::mark_unblocked(registry);
354355if !waiter.condvar.notify_one() {
{
::core::panicking::panic_fmt(format_args!("unable to wake the waiter"));
}
};assert!(waiter.condvar.notify_one(), "unable to wake the waiter");
356}
357358pub fn print_query_stack<'tcx>(
359 tcx: TyCtxt<'tcx>,
360mut current_query: Option<QueryJobId>,
361 dcx: DiagCtxtHandle<'_>,
362 limit_frames: Option<usize>,
363mut file: Option<std::fs::File>,
364) -> usize {
365// Be careful relying on global state here: this code is called from
366 // a panic hook, which means that the global `DiagCtxt` may be in a weird
367 // state if it was responsible for triggering the panic.
368let mut count_printed = 0;
369let mut count_total = 0;
370371// Make use of a partial query job map if we fail to take locks collecting active queries.
372let job_map = collect_active_query_jobs(tcx, CollectActiveJobsKind::PartialAllowed);
373374if let Some(ref mut file) = file {
375let _ = file.write_fmt(format_args!("\n\nquery stack during panic:\n"))writeln!(file, "\n\nquery stack during panic:");
376 }
377while let Some(query) = current_query {
378let Some(query_info) = job_map.map.get(&query) else {
379break;
380 };
381let description = query_info.tagged_key.description(tcx);
382if Some(count_printed) < limit_frames || limit_frames.is_none() {
383// Only print to stderr as many stack frames as `num_frames` when present.
384 dcx.struct_failure_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#{1} [{0}] {2}",
query_info.tagged_key.query_name(), count_printed,
description))
})format!(
385"#{count_printed} [{query_name}] {description}",
386 query_name = query_info.tagged_key.query_name(),
387 ))
388 .with_span(query_info.job.span)
389 .emit();
390 count_printed += 1;
391 }
392393if let Some(ref mut file) = file {
394let _ = file.write_fmt(format_args!("#{1} [{0}] {2}\n",
query_info.tagged_key.query_name(), count_total, description))writeln!(
395 file,
396"#{count_total} [{query_name}] {description}",
397 query_name = query_info.tagged_key.query_name(),
398 );
399 }
400401 current_query = query_info.job.parent;
402 count_total += 1;
403 }
404405if let Some(ref mut file) = file {
406let _ = file.write_fmt(format_args!("end of query stack\n"))writeln!(file, "end of query stack");
407 }
408count_total409}
410411#[inline(never)]
412#[cold]
413pub(crate) fn create_cycle_error<'tcx>(
414 tcx: TyCtxt<'tcx>,
415Cycle { usage, frames }: &Cycle<'tcx>,
416) -> Diag<'tcx> {
417if !!frames.is_empty() {
::core::panicking::panic("assertion failed: !frames.is_empty()")
};assert!(!frames.is_empty());
418419let span = frames[0].tagged_key.default_span(tcx, frames[1 % frames.len()].span);
420421let mut cycle_stack = Vec::new();
422423use crate::error::StackCount;
424let stack_bottom = frames[0].tagged_key.description(tcx);
425let stack_count = if frames.len() == 1 {
426 StackCount::Single { stack_bottom: stack_bottom.clone() }
427 } else {
428 StackCount::Multiple { stack_bottom: stack_bottom.clone() }
429 };
430431for i in 1..frames.len() {
432let frame = &frames[i];
433let span = frame.tagged_key.default_span(tcx, frames[(i + 1) % frames.len()].span);
434 cycle_stack
435 .push(crate::error::CycleStack { span, desc: frame.tagged_key.description(tcx) });
436 }
437438let cycle_usage = usage.as_ref().map(|usage| crate::error::CycleUsage {
439 span: usage.tagged_key.default_span(tcx, usage.span),
440 usage: usage.tagged_key.description(tcx),
441 });
442443let is_all_def_kind = |def_kind| {
444// Trivial type alias and trait alias cycles consists of `type_of` and
445 // `explicit_implied_predicates_of` queries, so we just check just these here.
446frames.iter().all(|frame| match frame.tagged_key {
447 TaggedQueryKey::type_of(def_id)
448 | TaggedQueryKey::explicit_implied_predicates_of(def_id)
449if tcx.def_kind(def_id) == def_kind =>
450 {
451true
452}
453_ => false,
454 })
455 };
456457let alias = if is_all_def_kind(DefKind::TyAlias) {
458Some(crate::error::Alias::Ty)
459 } else if is_all_def_kind(DefKind::TraitAlias) {
460Some(crate::error::Alias::Trait)
461 } else {
462None463 };
464465let cycle_diag = crate::error::Cycle {
466span,
467cycle_stack,
468stack_bottom,
469alias,
470cycle_usage,
471stack_count,
472 note_span: (),
473 };
474475tcx.sess.dcx().create_err(cycle_diag)
476}