Skip to main content

rustc_query_impl/
job.rs

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