Skip to main content

rustc_query_impl/
job.rs

1use std::io::Write;
2use std::ops::ControlFlow;
3use std::sync::Arc;
4use std::{iter, mem};
5
6use 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};
13
14use crate::{CollectActiveJobsKind, collect_active_query_jobs};
15
16/// 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}
22
23impl<'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`.
27    pub(crate) fn insert(&mut self, id: QueryJobId, info: QueryJobInfo<'tcx>) {
28        self.map.insert(id, info);
29    }
30
31    fn tagged_key_of(&self, id: QueryJobId) -> TaggedQueryKey<'tcx> {
32        self.map[&id].tagged_key
33    }
34
35    fn span_of(&self, id: QueryJobId) -> Span {
36        self.map[&id].job.span
37    }
38
39    fn parent_of(&self, id: QueryJobId) -> Option<QueryJobId> {
40        self.map[&id].job.parent
41    }
42
43    fn latch_of(&self, id: QueryJobId) -> Option<&QueryLatch<'tcx>> {
44        self.map[&id].job.latch.as_ref()
45    }
46}
47
48#[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> {
50    pub(crate) tagged_key: TaggedQueryKey<'tcx>,
51    pub(crate) job: QueryJob<'tcx>,
52}
53
54pub(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.
61    let mut frames = Vec::new();
62    let mut current_job = Option::clone(current_job);
63
64    while let Some(job) = current_job {
65        let info = &job_map.map[&job];
66        frames.push(QueryStackFrame { span: info.job.span, tagged_key: info.tagged_key });
67
68        if job == id {
69            frames.reverse();
70
71            // 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.
74            frames[0].span = span;
75            // Find out why the cycle itself was used.
76            let usage = try {
77                let parent = info.job.parent?;
78                QueryStackFrame { span: info.job.span, tagged_key: job_map.tagged_key_of(parent) }
79            };
80            return Cycle { usage, frames };
81        }
82
83        current_job = info.job.parent;
84    }
85
86    { ::core::panicking::panic_fmt(format_args!("did not find a cycle")); }panic!("did not find a cycle")
87}
88
89/// 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) {
98    let mut depth = 1;
99    let mut info = &job_map.map[&id];
100    // Two query jobs are for the same query method if they have the same
101    // `TaggedQueryKey` discriminant.
102    let expected_query = mem::discriminant::<TaggedQueryKey<'tcx>>(&info.tagged_key);
103    let mut last_info = info;
104
105    while let Some(id) = info.job.parent {
106        info = &job_map.map[&id];
107        if 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}
114
115/// 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);
118
119/// 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.
123    span: Span,
124    /// The query which we are waiting from, if none the waiter is from a compiler root.
125    parent: Option<QueryJobId>,
126    resumable: Option<ResumableWaiterLocation>,
127}
128
129/// 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> {
132    let mut result = Vec::new();
133
134    // Add the parent which is a non-resumable waiter since it's on the same stack
135    result.push(AbstractedWaiter {
136        span: job_map.span_of(query),
137        parent: job_map.parent_of(query),
138        resumable: None,
139    });
140
141    // Add the explicit waiters which use condvars and are resumable
142    if let Some(latch) = job_map.latch_of(query) {
143        for (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    }
151
152    result
153}
154
155/// 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>> {
166    if !visited.insert(query) {
167        return 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
169
170            // Remove previous stack entries
171            stack.drain(0..pos);
172            // Replace the span for the first query with the cycle cause
173            stack[0].0 = span;
174            ControlFlow::Break(None)
175        } else {
176            ControlFlow::Continue(())
177        };
178    }
179
180    // Query marked as visited is added it to the stack
181    stack.push((span, query));
182
183    // Visit all the waiters
184    for abstracted_waiter in abstracted_waiters_of(job_map, query) {
185        let Some(parent) = abstracted_waiter.parent else {
186            // Skip waiters which are not queries
187            continue;
188        };
189        if 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
193            return ControlFlow::Break(abstracted_waiter.resumable.or(maybe_resumable));
194        }
195    }
196
197    // Remove the entry in our stack since we didn't find a cycle
198    stack.pop();
199
200    ControlFlow::Continue(())
201}
202
203/// 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
212    if !visited.insert(query) {
213        return false;
214    }
215
216    // Visit all the waiters
217    for abstracted_waiter in abstracted_waiters_of(job_map, query) {
218        match abstracted_waiter.parent {
219            // This query is connected to the root
220            None => return true,
221            Some(parent) => {
222                if connected_to_root(job_map, parent, visited) {
223                    return true;
224                }
225            }
226        }
227    }
228
229    false
230}
231
232/// Looks for a query cycle using the last query in `jobs`.
233/// If a cycle is found, all queries in the cycle is removed from `jobs` and
234/// the function return true.
235/// If a cycle was not found, the starting query is removed from `jobs` and
236/// the function returns false.
237fn remove_cycle<'tcx>(
238    job_map: &QueryJobMap<'tcx>,
239    jobs: &mut Vec<QueryJobId>,
240    wakelist: &mut Vec<Arc<QueryWaiter<'tcx>>>,
241) -> bool {
242    let mut visited = FxHashSet::default();
243    let mut stack = Vec::new();
244    // Look for a cycle starting with the last query in `jobs`
245    if let ControlFlow::Break(resumable) =
246        find_cycle(job_map, jobs.pop().unwrap(), DUMMY_SP, &mut stack, &mut visited)
247    {
248        // The stack is a vector of pairs of spans and queries; reverse it so that
249        // the earlier entries require later entries
250        let (mut spans, queries): (Vec<_>, Vec<_>) = stack.into_iter().rev().unzip();
251
252        // Shift the spans so that queries are matched with the span for their waitee
253        spans.rotate_right(1);
254
255        // Zip them back together
256        let mut stack: Vec<_> = iter::zip(spans, queries).collect();
257
258        // Remove the queries in our cycle from the list of jobs to look at
259        for r in &stack {
260            if let Some(pos) = jobs.iter().position(|j| j == &r.1) {
261                jobs.remove(pos);
262            }
263        }
264
265        struct EntryPoint {
266            query_in_cycle: QueryJobId,
267            query_waiting_on_cycle: Option<(Span, QueryJobId)>,
268        }
269
270        // Find the queries in the cycle which are
271        // connected to queries outside the cycle
272        let entry_points = stack
273            .iter()
274            .filter_map(|&(_, query_in_cycle)| {
275                let mut entrypoint = false;
276                let mut query_waiting_on_cycle = None;
277
278                // Find a direct waiter who leads to the root
279                for abstracted_waiter in abstracted_waiters_of(job_map, query_in_cycle) {
280                    let Some(parent) = abstracted_waiter.parent else {
281                        // The query in the cycle is directly connected to root.
282                        entrypoint = true;
283                        continue;
284                    };
285
286                    // Mark all the other queries in the cycle as already visited,
287                    // so paths to the root through the cycle itself won't count.
288                    let mut visited = FxHashSet::from_iter(stack.iter().map(|q| q.1));
289
290                    if connected_to_root(job_map, parent, &mut visited) {
291                        query_waiting_on_cycle = Some((abstracted_waiter.span, parent));
292                        entrypoint = true;
293                        break;
294                    }
295                }
296
297                entrypoint.then_some(EntryPoint { query_in_cycle, query_waiting_on_cycle })
298            })
299            .collect::<Vec<EntryPoint>>();
300
301        // Pick an entry point, preferring ones with waiters
302        let entry_point = entry_points
303            .iter()
304            .find(|entry_point| entry_point.query_waiting_on_cycle.is_some())
305            .unwrap_or(&entry_points[0]);
306
307        // Shift the stack so that our entry point is first
308        let entry_point_pos =
309            stack.iter().position(|(_, query)| *query == entry_point.query_in_cycle);
310        if let Some(pos) = entry_point_pos {
311            stack.rotate_left(pos);
312        }
313
314        let usage = entry_point
315            .query_waiting_on_cycle
316            .map(|(span, job)| QueryStackFrame { span, tagged_key: job_map.tagged_key_of(job) });
317
318        // Create the cycle error
319        let error = Cycle {
320            usage,
321            frames: stack
322                .iter()
323                .map(|&(span, job)| QueryStackFrame {
324                    span,
325                    tagged_key: job_map.tagged_key_of(job),
326                })
327                .collect(),
328        };
329
330        // We unwrap `resumable` here since there must always be one
331        // edge which is resumable / waited using a query latch
332        let (waitee_query, waiter_idx) = resumable.unwrap();
333
334        // Extract the waiter we want to resume
335        let waiter = job_map.latch_of(waitee_query).unwrap().extract_waiter(waiter_idx);
336
337        // Set the cycle error so it will be picked up when resumed
338        *waiter.cycle.lock() = Some(error);
339
340        // Put the waiter on the list of things to resume
341        wakelist.push(waiter);
342
343        true
344    } else {
345        false
346    }
347}
348
349/// Detects query cycles by using depth first search over all active query jobs.
350/// If a query cycle is found it will break the cycle by finding an edge which
351/// uses a query latch and then resuming that waiter.
352/// There may be multiple cycles involved in a deadlock, so this searches
353/// all active queries for cycles before finally resuming all the waiters at once.
354pub fn break_query_cycles<'tcx>(
355    job_map: QueryJobMap<'tcx>,
356    registry: &rustc_thread_pool::Registry,
357) {
358    let mut wakelist = Vec::new();
359    // It is OK per the comments:
360    // - https://github.com/rust-lang/rust/pull/131200#issuecomment-2798854932
361    // - https://github.com/rust-lang/rust/pull/131200#issuecomment-2798866392
362    #[allow(rustc::potential_query_instability)]
363    let mut jobs: Vec<QueryJobId> = job_map.map.keys().copied().collect();
364
365    let mut found_cycle = false;
366
367    while jobs.len() > 0 {
368        if remove_cycle(&job_map, &mut jobs, &mut wakelist) {
369            found_cycle = true;
370        }
371    }
372
373    // Check that a cycle was found. It is possible for a deadlock to occur without
374    // a query cycle if a query which can be waited on uses Rayon to do multithreading
375    // internally. Such a query (X) may be executing on 2 threads (A and B) and A may
376    // wait using Rayon on B. Rayon may then switch to executing another query (Y)
377    // which in turn will wait on X causing a deadlock. We have a false dependency from
378    // X to Y due to Rayon waiting and a true dependency from Y to X. The algorithm here
379    // only considers the true dependency and won't detect a cycle.
380    if !found_cycle {
381        {
    ::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!(
382            "deadlock detected as we're unable to find a query cycle to break\n\
383            current query map:\n{job_map:#?}",
384        );
385    }
386
387    // Mark all the thread we're about to wake up as unblocked. This needs to be done before
388    // we wake the threads up as otherwise Rayon could detect a deadlock if a thread we
389    // resumed fell asleep and this thread had yet to mark the remaining threads as unblocked.
390    for _ in 0..wakelist.len() {
391        rustc_thread_pool::mark_unblocked(registry);
392    }
393
394    for waiter in wakelist.into_iter() {
395        waiter.condvar.notify_one();
396    }
397}
398
399pub fn print_query_stack<'tcx>(
400    tcx: TyCtxt<'tcx>,
401    mut current_query: Option<QueryJobId>,
402    dcx: DiagCtxtHandle<'_>,
403    limit_frames: Option<usize>,
404    mut file: Option<std::fs::File>,
405) -> usize {
406    // Be careful relying on global state here: this code is called from
407    // a panic hook, which means that the global `DiagCtxt` may be in a weird
408    // state if it was responsible for triggering the panic.
409    let mut count_printed = 0;
410    let mut count_total = 0;
411
412    // Make use of a partial query job map if we fail to take locks collecting active queries.
413    let job_map = collect_active_query_jobs(tcx, CollectActiveJobsKind::PartialAllowed);
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 description = query_info.tagged_key.description(tcx);
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!("#{1} [{0}] {2}",
                query_info.tagged_key.query_name(), count_printed,
                description))
    })format!(
426                "#{count_printed} [{query_name}] {description}",
427                query_name = query_info.tagged_key.query_name(),
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!("#{1} [{0}] {2}\n",
        query_info.tagged_key.query_name(), count_total, description))writeln!(
436                file,
437                "#{count_total} [{query_name}] {description}",
438                query_name = query_info.tagged_key.query_name(),
439            );
440        }
441
442        current_query = query_info.job.parent;
443        count_total += 1;
444    }
445
446    if let Some(ref mut file) = file {
447        let _ = file.write_fmt(format_args!("end of query stack\n"))writeln!(file, "end of query stack");
448    }
449    count_total
450}
451
452#[inline(never)]
453#[cold]
454pub(crate) fn create_cycle_error<'tcx>(
455    tcx: TyCtxt<'tcx>,
456    Cycle { usage, frames }: &Cycle<'tcx>,
457) -> Diag<'tcx> {
458    if !!frames.is_empty() {
    ::core::panicking::panic("assertion failed: !frames.is_empty()")
};assert!(!frames.is_empty());
459
460    let span = frames[0].tagged_key.default_span(tcx, frames[1 % frames.len()].span);
461
462    let mut cycle_stack = Vec::new();
463
464    use crate::error::StackCount;
465    let stack_bottom = frames[0].tagged_key.description(tcx);
466    let stack_count = if frames.len() == 1 {
467        StackCount::Single { stack_bottom: stack_bottom.clone() }
468    } else {
469        StackCount::Multiple { stack_bottom: stack_bottom.clone() }
470    };
471
472    for i in 1..frames.len() {
473        let frame = &frames[i];
474        let span = frame.tagged_key.default_span(tcx, frames[(i + 1) % frames.len()].span);
475        cycle_stack
476            .push(crate::error::CycleStack { span, desc: frame.tagged_key.description(tcx) });
477    }
478
479    let cycle_usage = usage.as_ref().map(|usage| crate::error::CycleUsage {
480        span: usage.tagged_key.default_span(tcx, usage.span),
481        usage: usage.tagged_key.description(tcx),
482    });
483
484    let alias = if frames
485        .iter()
486        .all(|frame| frame.tagged_key.def_kind(tcx) == Some(DefKind::TyAlias))
487    {
488        Some(crate::error::Alias::Ty)
489    } else if frames.iter().all(|frame| frame.tagged_key.def_kind(tcx) == Some(DefKind::TraitAlias))
490    {
491        Some(crate::error::Alias::Trait)
492    } else {
493        None
494    };
495
496    let cycle_diag = crate::error::Cycle {
497        span,
498        cycle_stack,
499        stack_bottom,
500        alias,
501        cycle_usage,
502        stack_count,
503        note_span: (),
504    };
505
506    tcx.sess.dcx().create_err(cycle_diag)
507}