Skip to main content

rustc_query_impl/
job.rs

1use std::io::Write;
2use std::iter;
3use std::ops::ControlFlow;
4use std::sync::Arc;
5
6use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7use rustc_errors::{Diag, DiagCtxtHandle};
8use rustc_hir::def::DefKind;
9use rustc_middle::query::{
10    CycleError, QueryInfo, QueryJob, QueryJobId, QueryLatch, QueryStackDeferred, QueryStackFrame,
11    QueryWaiter,
12};
13use rustc_middle::ty::TyCtxt;
14use rustc_session::Session;
15use rustc_span::{DUMMY_SP, Span};
16
17use crate::plumbing::collect_active_jobs_from_all_queries;
18
19/// 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}
25
26impl<'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`.
30    pub(crate) fn insert(&mut self, id: QueryJobId, info: QueryJobInfo<'tcx>) {
31        self.map.insert(id, info);
32    }
33
34    fn frame_of(&self, id: QueryJobId) -> &QueryStackFrame<QueryStackDeferred<'tcx>> {
35        &self.map[&id].frame
36    }
37
38    fn span_of(&self, id: QueryJobId) -> Span {
39        self.map[&id].job.span
40    }
41
42    fn parent_of(&self, id: QueryJobId) -> Option<QueryJobId> {
43        self.map[&id].job.parent
44    }
45
46    fn latch_of(&self, id: QueryJobId) -> Option<&QueryLatch<'tcx>> {
47        self.map[&id].job.latch.as_ref()
48    }
49}
50
51#[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> {
53    pub(crate) frame: QueryStackFrame<QueryStackDeferred<'tcx>>,
54    pub(crate) job: QueryJob<'tcx>,
55}
56
57pub(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
64    let mut cycle = Vec::new();
65    let mut current_job = Option::clone(current_job);
66
67    while let Some(job) = current_job {
68        let info = &job_map.map[&job];
69        cycle.push(QueryInfo { span: info.job.span, frame: info.frame.clone() });
70
71        if job == id {
72            cycle.reverse();
73
74            // 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
78            cycle[0].span = span;
79            // Find out why the cycle itself was used
80            let usage = try {
81                let parent = info.job.parent?;
82                (info.job.span, job_map.frame_of(parent).clone())
83            };
84            return CycleError { usage, cycle };
85        }
86
87        current_job = info.job.parent;
88    }
89
90    { ::core::panicking::panic_fmt(format_args!("did not find a cycle")); }panic!("did not find a cycle")
91}
92
93#[cold]
94#[inline(never)]
95pub(crate) fn find_dep_kind_root<'tcx>(
96    id: QueryJobId,
97    job_map: QueryJobMap<'tcx>,
98) -> (QueryJobInfo<'tcx>, usize) {
99    let mut depth = 1;
100    let info = &job_map.map[&id];
101    let dep_kind = info.frame.dep_kind;
102    let mut current_id = info.job.parent;
103    let mut last_layout = (info.clone(), depth);
104
105    while let Some(id) = current_id {
106        let info = &job_map.map[&id];
107        if info.frame.dep_kind == dep_kind {
108            depth += 1;
109            last_layout = (info.clone(), depth);
110        }
111        current_id = info.job.parent;
112    }
113    last_layout
114}
115
116/// A resumable waiter of a query. The usize is the index into waiters in the query's latch
117type Waiter = (QueryJobId, usize);
118
119/// 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,
130    mut 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
133    if let Some(parent) = job_map.parent_of(query) {
134        visit(job_map.span_of(query), parent)?;
135    }
136
137    // Visit the explicit waiters which use condvars and are resumable
138    if let Some(latch) = job_map.latch_of(query) {
139        for (i, waiter) in latch.info.lock().waiters.iter().enumerate() {
140            if let Some(waiter_query) = waiter.query {
141                // Return a value which indicates that this waiter can be resumed
142                visit(waiter.span, waiter_query).map_break(|_| Some((query, i)))?;
143            }
144        }
145    }
146
147    ControlFlow::Continue(())
148}
149
150/// 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>> {
161    if !visited.insert(query) {
162        return 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
164
165            // Remove previous stack entries
166            stack.drain(0..p);
167            // Replace the span for the first query with the cycle cause
168            stack[0].0 = span;
169            ControlFlow::Break(None)
170        } else {
171            ControlFlow::Continue(())
172        };
173    }
174
175    // Query marked as visited is added it to the stack
176    stack.push((span, query));
177
178    // Visit all the waiters
179    let r = visit_waiters(job_map, query, |span, successor| {
180        cycle_check(job_map, successor, span, stack, visited)
181    });
182
183    // Remove the entry in our stack if we didn't find a cycle
184    if r.is_continue() {
185        stack.pop();
186    }
187
188    r
189}
190
191/// 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
200    if !visited.insert(query) {
201        return ControlFlow::Continue(());
202    }
203
204    // This query is connected to the root (it has no query parent), return true
205    if job_map.parent_of(query).is_none() {
206        return ControlFlow::Break(None);
207    }
208
209    visit_waiters(job_map, query, |_, successor| connected_to_root(job_map, successor, visited))
210}
211
212// 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
215    F: Fn(&T) -> (Span, QueryJobId),
216{
217    // Deterministically pick an entry point
218    // FIXME: Sort this instead
219    queries
220        .iter()
221        .min_by_key(|v| {
222            let (span, query) = f(v);
223            let 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
227            let span_cmp = if span == DUMMY_SP { 1 } else { 0 };
228            (span_cmp, hash)
229        })
230        .unwrap()
231}
232
233/// 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 {
243    let mut visited = FxHashSet::default();
244    let mut stack = Vec::new();
245    // Look for a cycle starting with the last query in `jobs`
246    if let ControlFlow::Break(waiter) =
247        cycle_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
251        let (mut spans, queries): (Vec<_>, Vec<_>) = stack.into_iter().rev().unzip();
252
253        // Shift the spans so that queries are matched with the span for their waitee
254        spans.rotate_right(1);
255
256        // Zip them back together
257        let mut stack: Vec<_> = iter::zip(spans, queries).collect();
258
259        // Remove the queries in our cycle from the list of jobs to look at
260        for r in &stack {
261            if let Some(pos) = jobs.iter().position(|j| j == &r.1) {
262                jobs.remove(pos);
263            }
264        }
265
266        // Find the queries in the cycle which are
267        // connected to queries outside the cycle
268        let entry_points = stack
269            .iter()
270            .filter_map(|&(span, query)| {
271                if job_map.parent_of(query).is_none() {
272                    // This query is connected to the root (it has no query parent)
273                    Some((span, query, None))
274                } else {
275                    let mut waiters = Vec::new();
276                    // Find all the direct waiters who lead to the root
277                    let _ = visit_waiters(job_map, query, |span, waiter| {
278                        // Mark all the other queries in the cycle as already visited
279                        let mut visited = FxHashSet::from_iter(stack.iter().map(|q| q.1));
280
281                        if connected_to_root(job_map, waiter, &mut visited).is_break() {
282                            waiters.push((span, waiter));
283                        }
284
285                        ControlFlow::Continue(())
286                    });
287                    if waiters.is_empty() {
288                        None
289                    } else {
290                        // Deterministically pick one of the waiters to show to the user
291                        let waiter = *pick_query(job_map, &waiters, |s| *s);
292                        Some((span, query, Some(waiter)))
293                    }
294                }
295            })
296            .collect::<Vec<(Span, QueryJobId, Option<(Span, QueryJobId)>)>>();
297
298        // Deterministically pick an entry point
299        let (_, entry_point, usage) = pick_query(job_map, &entry_points, |e| (e.0, e.1));
300
301        // Shift the stack so that our entry point is first
302        let entry_point_pos = stack.iter().position(|(_, query)| query == entry_point);
303        if let Some(pos) = entry_point_pos {
304            stack.rotate_left(pos);
305        }
306
307        let usage = usage.map(|(span, job)| (span, job_map.frame_of(job).clone()));
308
309        // Create the cycle error
310        let error = CycleError {
311            usage,
312            cycle: stack
313                .iter()
314                .map(|&(span, job)| QueryInfo { span, frame: job_map.frame_of(job).clone() })
315                .collect(),
316        };
317
318        // We unwrap `waiter` here since there must always be one
319        // edge which is resumable / waited using a query latch
320        let (waitee_query, waiter_idx) = waiter.unwrap();
321
322        // Extract the waiter we want to resume
323        let waiter = job_map.latch_of(waitee_query).unwrap().extract_waiter(waiter_idx);
324
325        // Set the cycle error so it will be picked up when resumed
326        *waiter.cycle.lock() = Some(error);
327
328        // Put the waiter on the list of things to resume
329        wakelist.push(waiter);
330
331        true
332    } else {
333        false
334    }
335}
336
337/// 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) {
346    let 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)]
351    let mut jobs: Vec<QueryJobId> = job_map.map.keys().copied().collect();
352
353    let mut found_cycle = false;
354
355    while jobs.len() > 0 {
356        if remove_cycle(&job_map, &mut jobs, &mut wakelist) {
357            found_cycle = true;
358        }
359    }
360
361    // 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.
368    if !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    }
374
375    // 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.
378    for _ in 0..wakelist.len() {
379        rustc_thread_pool::mark_unblocked(registry);
380    }
381
382    for waiter in wakelist.into_iter() {
383        waiter.condvar.notify_one();
384    }
385}
386
387pub fn print_query_stack<'tcx>(
388    tcx: TyCtxt<'tcx>,
389    mut current_query: Option<QueryJobId>,
390    dcx: DiagCtxtHandle<'_>,
391    limit_frames: Option<usize>,
392    mut 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.
397    let mut count_printed = 0;
398    let mut count_total = 0;
399
400    // Make use of a partial query job map if we fail to take locks collecting active queries.
401    let job_map: QueryJobMap<'_> = collect_active_jobs_from_all_queries(tcx, false)
402        .unwrap_or_else(|partial_job_map| partial_job_map);
403
404    if let Some(ref mut file) = file {
405        let _ = file.write_fmt(format_args!("\n\nquery stack during panic:\n"))writeln!(file, "\n\nquery stack during panic:");
406    }
407    while let Some(query) = current_query {
408        let Some(query_info) = job_map.map.get(&query) else {
409            break;
410        };
411        let query_extra = query_info.frame.info.extract();
412        if 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        }
422
423        if let Some(ref mut file) = file {
424            let _ = 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        }
430
431        current_query = query_info.job.parent;
432        count_total += 1;
433    }
434
435    if let Some(ref mut file) = file {
436        let _ = file.write_fmt(format_args!("end of query stack\n"))writeln!(file, "end of query stack");
437    }
438    count_total
439}
440
441#[inline(never)]
442#[cold]
443pub(crate) fn report_cycle<'a>(
444    sess: &'a Session,
445    CycleError { usage, cycle: stack }: &CycleError,
446) -> Diag<'a> {
447    if !!stack.is_empty() {
    ::core::panicking::panic("assertion failed: !stack.is_empty()")
};assert!(!stack.is_empty());
448
449    let span = stack[0].frame.info.default_span(stack[1 % stack.len()].span);
450
451    let mut cycle_stack = Vec::new();
452
453    use crate::error::StackCount;
454    let stack_count = if stack.len() == 1 { StackCount::Single } else { StackCount::Multiple };
455
456    for i in 1..stack.len() {
457        let frame = &stack[i].frame;
458        let 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    }
462
463    let mut cycle_usage = None;
464    if let Some((span, ref query)) = *usage {
465        cycle_usage = Some(crate::error::CycleUsage {
466            span: query.info.default_span(span),
467            usage: query.info.description.to_string(),
468        });
469    }
470
471    let alias =
472        if 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))) {
473            Some(crate::error::Alias::Ty)
474        } else if stack.iter().all(|entry| entry.frame.info.def_kind == Some(DefKind::TraitAlias)) {
475            Some(crate::error::Alias::Trait)
476        } else {
477            None
478        };
479
480    let cycle_diag = crate::error::Cycle {
481        span,
482        cycle_stack,
483        stack_bottom: stack[0].frame.info.description.to_owned(),
484        alias,
485        cycle_usage,
486        stack_count,
487        note_span: (),
488    };
489
490    sess.dcx().create_err(cycle_diag)
491}