Skip to main content

rustc_query_system/query/
job.rs

1use std::fmt::Debug;
2use std::hash::Hash;
3use std::io::Write;
4use std::iter;
5use std::num::NonZero;
6use std::sync::Arc;
7
8use parking_lot::{Condvar, Mutex};
9use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10use rustc_errors::{Diag, DiagCtxtHandle};
11use rustc_hir::def::DefKind;
12use rustc_session::Session;
13use rustc_span::{DUMMY_SP, Span};
14
15use super::{QueryStackDeferred, QueryStackFrameExtra};
16use crate::dep_graph::DepContext;
17use crate::error::CycleStack;
18use crate::query::plumbing::CycleError;
19use crate::query::{QueryContext, QueryStackFrame};
20
21/// Represents a span and a query key.
22#[derive(#[automatically_derived]
impl<I: ::core::clone::Clone> ::core::clone::Clone for QueryInfo<I> {
    #[inline]
    fn clone(&self) -> QueryInfo<I> {
        QueryInfo {
            span: ::core::clone::Clone::clone(&self.span),
            frame: ::core::clone::Clone::clone(&self.frame),
        }
    }
}Clone, #[automatically_derived]
impl<I: ::core::fmt::Debug> ::core::fmt::Debug for QueryInfo<I> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "QueryInfo",
            "span", &self.span, "frame", &&self.frame)
    }
}Debug)]
23pub struct QueryInfo<I> {
24    /// The span corresponding to the reason for which this query was required.
25    pub span: Span,
26    pub frame: QueryStackFrame<I>,
27}
28
29impl<'tcx> QueryInfo<QueryStackDeferred<'tcx>> {
30    pub(crate) fn lift(&self) -> QueryInfo<QueryStackFrameExtra> {
31        QueryInfo { span: self.span, frame: self.frame.lift() }
32    }
33}
34
35/// Map from query job IDs to job information collected by
36/// [`QueryContext::collect_active_jobs_from_all_queries`].
37pub type QueryMap<'tcx> = FxHashMap<QueryJobId, QueryJobInfo<'tcx>>;
38
39/// A value uniquely identifying an active query job.
40#[derive(#[automatically_derived]
impl ::core::marker::Copy for QueryJobId { }Copy, #[automatically_derived]
impl ::core::clone::Clone for QueryJobId {
    #[inline]
    fn clone(&self) -> QueryJobId {
        let _: ::core::clone::AssertParamIsClone<NonZero<u64>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for QueryJobId {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NonZero<u64>>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for QueryJobId {
    #[inline]
    fn eq(&self, other: &QueryJobId) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for QueryJobId {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for QueryJobId {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "QueryJobId",
            &&self.0)
    }
}Debug)]
41pub struct QueryJobId(pub NonZero<u64>);
42
43impl QueryJobId {
44    fn frame<'a, 'tcx>(self, map: &'a QueryMap<'tcx>) -> QueryStackFrame<QueryStackDeferred<'tcx>> {
45        map.get(&self).unwrap().frame.clone()
46    }
47
48    fn span<'a, 'tcx>(self, map: &'a QueryMap<'tcx>) -> Span {
49        map.get(&self).unwrap().job.span
50    }
51
52    fn parent<'a, 'tcx>(self, map: &'a QueryMap<'tcx>) -> Option<QueryJobId> {
53        map.get(&self).unwrap().job.parent
54    }
55
56    fn latch<'a, 'tcx>(self, map: &'a QueryMap<'tcx>) -> Option<&'a QueryLatch<'tcx>> {
57        map.get(&self).unwrap().job.latch.as_ref()
58    }
59}
60
61#[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)]
62pub struct QueryJobInfo<'tcx> {
63    pub frame: QueryStackFrame<QueryStackDeferred<'tcx>>,
64    pub job: QueryJob<'tcx>,
65}
66
67/// Represents an active query job.
68#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryJob<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "QueryJob",
            "id", &self.id, "span", &self.span, "parent", &self.parent,
            "latch", &&self.latch)
    }
}Debug)]
69pub struct QueryJob<'tcx> {
70    pub id: QueryJobId,
71
72    /// The span corresponding to the reason for which this query was required.
73    pub span: Span,
74
75    /// The parent query job which created this job and is implicitly waiting on it.
76    pub parent: Option<QueryJobId>,
77
78    /// The latch that is used to wait on this job.
79    latch: Option<QueryLatch<'tcx>>,
80}
81
82impl<'tcx> Clone for QueryJob<'tcx> {
83    fn clone(&self) -> Self {
84        Self { id: self.id, span: self.span, parent: self.parent, latch: self.latch.clone() }
85    }
86}
87
88impl<'tcx> QueryJob<'tcx> {
89    /// Creates a new query job.
90    #[inline]
91    pub fn new(id: QueryJobId, span: Span, parent: Option<QueryJobId>) -> Self {
92        QueryJob { id, span, parent, latch: None }
93    }
94
95    pub(super) fn latch(&mut self) -> QueryLatch<'tcx> {
96        if self.latch.is_none() {
97            self.latch = Some(QueryLatch::new());
98        }
99        self.latch.as_ref().unwrap().clone()
100    }
101
102    /// Signals to waiters that the query is complete.
103    ///
104    /// This does nothing for single threaded rustc,
105    /// as there are no concurrent jobs which could be waiting on us
106    #[inline]
107    pub fn signal_complete(self) {
108        if let Some(latch) = self.latch {
109            latch.set();
110        }
111    }
112}
113
114impl QueryJobId {
115    pub(super) fn find_cycle_in_stack<'tcx>(
116        &self,
117        query_map: QueryMap<'tcx>,
118        current_job: &Option<QueryJobId>,
119        span: Span,
120    ) -> CycleError<QueryStackDeferred<'tcx>> {
121        // Find the waitee amongst `current_job` parents
122        let mut cycle = Vec::new();
123        let mut current_job = Option::clone(current_job);
124
125        while let Some(job) = current_job {
126            let info = query_map.get(&job).unwrap();
127            cycle.push(QueryInfo { span: info.job.span, frame: info.frame.clone() });
128
129            if job == *self {
130                cycle.reverse();
131
132                // This is the end of the cycle
133                // The span entry we included was for the usage
134                // of the cycle itself, and not part of the cycle
135                // Replace it with the span which caused the cycle to form
136                cycle[0].span = span;
137                // Find out why the cycle itself was used
138                let usage = info
139                    .job
140                    .parent
141                    .as_ref()
142                    .map(|parent| (info.job.span, parent.frame(&query_map)));
143                return CycleError { usage, cycle };
144            }
145
146            current_job = info.job.parent;
147        }
148
149        { ::core::panicking::panic_fmt(format_args!("did not find a cycle")); }panic!("did not find a cycle")
150    }
151
152    #[cold]
153    #[inline(never)]
154    pub fn find_dep_kind_root<'tcx>(
155        &self,
156        query_map: QueryMap<'tcx>,
157    ) -> (QueryJobInfo<'tcx>, usize) {
158        let mut depth = 1;
159        let info = query_map.get(&self).unwrap();
160        let dep_kind = info.frame.dep_kind;
161        let mut current_id = info.job.parent;
162        let mut last_layout = (info.clone(), depth);
163
164        while let Some(id) = current_id {
165            let info = query_map.get(&id).unwrap();
166            if info.frame.dep_kind == dep_kind {
167                depth += 1;
168                last_layout = (info.clone(), depth);
169            }
170            current_id = info.job.parent;
171        }
172        last_layout
173    }
174}
175
176#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryWaiter<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "QueryWaiter",
            "query", &self.query, "condvar", &self.condvar, "span",
            &self.span, "cycle", &&self.cycle)
    }
}Debug)]
177struct QueryWaiter<'tcx> {
178    query: Option<QueryJobId>,
179    condvar: Condvar,
180    span: Span,
181    cycle: Mutex<Option<CycleError<QueryStackDeferred<'tcx>>>>,
182}
183
184#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryLatchInfo<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "QueryLatchInfo", "complete", &self.complete, "waiters",
            &&self.waiters)
    }
}Debug)]
185struct QueryLatchInfo<'tcx> {
186    complete: bool,
187    waiters: Vec<Arc<QueryWaiter<'tcx>>>,
188}
189
190#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryLatch<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "QueryLatch",
            "info", &&self.info)
    }
}Debug)]
191pub(super) struct QueryLatch<'tcx> {
192    info: Arc<Mutex<QueryLatchInfo<'tcx>>>,
193}
194
195impl<'tcx> Clone for QueryLatch<'tcx> {
196    fn clone(&self) -> Self {
197        Self { info: Arc::clone(&self.info) }
198    }
199}
200
201impl<'tcx> QueryLatch<'tcx> {
202    fn new() -> Self {
203        QueryLatch {
204            info: Arc::new(Mutex::new(QueryLatchInfo { complete: false, waiters: Vec::new() })),
205        }
206    }
207
208    /// Awaits for the query job to complete.
209    pub(super) fn wait_on(
210        &self,
211        qcx: impl QueryContext<'tcx>,
212        query: Option<QueryJobId>,
213        span: Span,
214    ) -> Result<(), CycleError<QueryStackDeferred<'tcx>>> {
215        let waiter =
216            Arc::new(QueryWaiter { query, span, cycle: Mutex::new(None), condvar: Condvar::new() });
217        self.wait_on_inner(qcx, &waiter);
218        // FIXME: Get rid of this lock. We have ownership of the QueryWaiter
219        // although another thread may still have a Arc reference so we cannot
220        // use Arc::get_mut
221        let mut cycle = waiter.cycle.lock();
222        match cycle.take() {
223            None => Ok(()),
224            Some(cycle) => Err(cycle),
225        }
226    }
227
228    /// Awaits the caller on this latch by blocking the current thread.
229    fn wait_on_inner(&self, qcx: impl QueryContext<'tcx>, waiter: &Arc<QueryWaiter<'tcx>>) {
230        let mut info = self.info.lock();
231        if !info.complete {
232            // We push the waiter on to the `waiters` list. It can be accessed inside
233            // the `wait` call below, by 1) the `set` method or 2) by deadlock detection.
234            // Both of these will remove it from the `waiters` list before resuming
235            // this thread.
236            info.waiters.push(Arc::clone(waiter));
237
238            // If this detects a deadlock and the deadlock handler wants to resume this thread
239            // we have to be in the `wait` call. This is ensured by the deadlock handler
240            // getting the self.info lock.
241            rustc_thread_pool::mark_blocked();
242            let proxy = qcx.jobserver_proxy();
243            proxy.release_thread();
244            waiter.condvar.wait(&mut info);
245            // Release the lock before we potentially block in `acquire_thread`
246            drop(info);
247            proxy.acquire_thread();
248        }
249    }
250
251    /// Sets the latch and resumes all waiters on it
252    fn set(&self) {
253        let mut info = self.info.lock();
254        if true {
    if !!info.complete {
        ::core::panicking::panic("assertion failed: !info.complete")
    };
};debug_assert!(!info.complete);
255        info.complete = true;
256        let registry = rustc_thread_pool::Registry::current();
257        for waiter in info.waiters.drain(..) {
258            rustc_thread_pool::mark_unblocked(&registry);
259            waiter.condvar.notify_one();
260        }
261    }
262
263    /// Removes a single waiter from the list of waiters.
264    /// This is used to break query cycles.
265    fn extract_waiter(&self, waiter: usize) -> Arc<QueryWaiter<'tcx>> {
266        let mut info = self.info.lock();
267        if true {
    if !!info.complete {
        ::core::panicking::panic("assertion failed: !info.complete")
    };
};debug_assert!(!info.complete);
268        // Remove the waiter from the list of waiters
269        info.waiters.remove(waiter)
270    }
271}
272
273/// A resumable waiter of a query. The usize is the index into waiters in the query's latch
274type Waiter = (QueryJobId, usize);
275
276/// Visits all the non-resumable and resumable waiters of a query.
277/// Only waiters in a query are visited.
278/// `visit` is called for every waiter and is passed a query waiting on `query_ref`
279/// and a span indicating the reason the query waited on `query_ref`.
280/// If `visit` returns Some, this function returns.
281/// For visits of non-resumable waiters it returns the return value of `visit`.
282/// For visits of resumable waiters it returns Some(Some(Waiter)) which has the
283/// required information to resume the waiter.
284/// If all `visit` calls returns None, this function also returns None.
285fn visit_waiters<'tcx, F>(
286    query_map: &QueryMap<'tcx>,
287    query: QueryJobId,
288    mut visit: F,
289) -> Option<Option<Waiter>>
290where
291    F: FnMut(Span, QueryJobId) -> Option<Option<Waiter>>,
292{
293    // Visit the parent query which is a non-resumable waiter since it's on the same stack
294    if let Some(parent) = query.parent(query_map)
295        && let Some(cycle) = visit(query.span(query_map), parent)
296    {
297        return Some(cycle);
298    }
299
300    // Visit the explicit waiters which use condvars and are resumable
301    if let Some(latch) = query.latch(query_map) {
302        for (i, waiter) in latch.info.lock().waiters.iter().enumerate() {
303            if let Some(waiter_query) = waiter.query {
304                if visit(waiter.span, waiter_query).is_some() {
305                    // Return a value which indicates that this waiter can be resumed
306                    return Some(Some((query, i)));
307                }
308            }
309        }
310    }
311
312    None
313}
314
315/// Look for query cycles by doing a depth first search starting at `query`.
316/// `span` is the reason for the `query` to execute. This is initially DUMMY_SP.
317/// If a cycle is detected, this initial value is replaced with the span causing
318/// the cycle.
319fn cycle_check<'tcx>(
320    query_map: &QueryMap<'tcx>,
321    query: QueryJobId,
322    span: Span,
323    stack: &mut Vec<(Span, QueryJobId)>,
324    visited: &mut FxHashSet<QueryJobId>,
325) -> Option<Option<Waiter>> {
326    if !visited.insert(query) {
327        return if let Some(p) = stack.iter().position(|q| q.1 == query) {
328            // We detected a query cycle, fix up the initial span and return Some
329
330            // Remove previous stack entries
331            stack.drain(0..p);
332            // Replace the span for the first query with the cycle cause
333            stack[0].0 = span;
334            Some(None)
335        } else {
336            None
337        };
338    }
339
340    // Query marked as visited is added it to the stack
341    stack.push((span, query));
342
343    // Visit all the waiters
344    let r = visit_waiters(query_map, query, |span, successor| {
345        cycle_check(query_map, successor, span, stack, visited)
346    });
347
348    // Remove the entry in our stack if we didn't find a cycle
349    if r.is_none() {
350        stack.pop();
351    }
352
353    r
354}
355
356/// Finds out if there's a path to the compiler root (aka. code which isn't in a query)
357/// from `query` without going through any of the queries in `visited`.
358/// This is achieved with a depth first search.
359fn connected_to_root<'tcx>(
360    query_map: &QueryMap<'tcx>,
361    query: QueryJobId,
362    visited: &mut FxHashSet<QueryJobId>,
363) -> bool {
364    // We already visited this or we're deliberately ignoring it
365    if !visited.insert(query) {
366        return false;
367    }
368
369    // This query is connected to the root (it has no query parent), return true
370    if query.parent(query_map).is_none() {
371        return true;
372    }
373
374    visit_waiters(query_map, query, |_, successor| {
375        connected_to_root(query_map, successor, visited).then_some(None)
376    })
377    .is_some()
378}
379
380// Deterministically pick an query from a list
381fn pick_query<'a, 'tcx, T, F>(query_map: &QueryMap<'tcx>, queries: &'a [T], f: F) -> &'a T
382where
383    F: Fn(&T) -> (Span, QueryJobId),
384{
385    // Deterministically pick an entry point
386    // FIXME: Sort this instead
387    queries
388        .iter()
389        .min_by_key(|v| {
390            let (span, query) = f(v);
391            let hash = query.frame(query_map).hash;
392            // Prefer entry points which have valid spans for nicer error messages
393            // We add an integer to the tuple ensuring that entry points
394            // with valid spans are picked first
395            let span_cmp = if span == DUMMY_SP { 1 } else { 0 };
396            (span_cmp, hash)
397        })
398        .unwrap()
399}
400
401/// Looks for query cycles starting from the last query in `jobs`.
402/// If a cycle is found, all queries in the cycle is removed from `jobs` and
403/// the function return true.
404/// If a cycle was not found, the starting query is removed from `jobs` and
405/// the function returns false.
406fn remove_cycle<'tcx>(
407    query_map: &QueryMap<'tcx>,
408    jobs: &mut Vec<QueryJobId>,
409    wakelist: &mut Vec<Arc<QueryWaiter<'tcx>>>,
410) -> bool {
411    let mut visited = FxHashSet::default();
412    let mut stack = Vec::new();
413    // Look for a cycle starting with the last query in `jobs`
414    if let Some(waiter) =
415        cycle_check(query_map, jobs.pop().unwrap(), DUMMY_SP, &mut stack, &mut visited)
416    {
417        // The stack is a vector of pairs of spans and queries; reverse it so that
418        // the earlier entries require later entries
419        let (mut spans, queries): (Vec<_>, Vec<_>) = stack.into_iter().rev().unzip();
420
421        // Shift the spans so that queries are matched with the span for their waitee
422        spans.rotate_right(1);
423
424        // Zip them back together
425        let mut stack: Vec<_> = iter::zip(spans, queries).collect();
426
427        // Remove the queries in our cycle from the list of jobs to look at
428        for r in &stack {
429            if let Some(pos) = jobs.iter().position(|j| j == &r.1) {
430                jobs.remove(pos);
431            }
432        }
433
434        // Find the queries in the cycle which are
435        // connected to queries outside the cycle
436        let entry_points = stack
437            .iter()
438            .filter_map(|&(span, query)| {
439                if query.parent(query_map).is_none() {
440                    // This query is connected to the root (it has no query parent)
441                    Some((span, query, None))
442                } else {
443                    let mut waiters = Vec::new();
444                    // Find all the direct waiters who lead to the root
445                    visit_waiters(query_map, query, |span, waiter| {
446                        // Mark all the other queries in the cycle as already visited
447                        let mut visited = FxHashSet::from_iter(stack.iter().map(|q| q.1));
448
449                        if connected_to_root(query_map, waiter, &mut visited) {
450                            waiters.push((span, waiter));
451                        }
452
453                        None
454                    });
455                    if waiters.is_empty() {
456                        None
457                    } else {
458                        // Deterministically pick one of the waiters to show to the user
459                        let waiter = *pick_query(query_map, &waiters, |s| *s);
460                        Some((span, query, Some(waiter)))
461                    }
462                }
463            })
464            .collect::<Vec<(Span, QueryJobId, Option<(Span, QueryJobId)>)>>();
465
466        // Deterministically pick an entry point
467        let (_, entry_point, usage) = pick_query(query_map, &entry_points, |e| (e.0, e.1));
468
469        // Shift the stack so that our entry point is first
470        let entry_point_pos = stack.iter().position(|(_, query)| query == entry_point);
471        if let Some(pos) = entry_point_pos {
472            stack.rotate_left(pos);
473        }
474
475        let usage = usage.as_ref().map(|(span, query)| (*span, query.frame(query_map)));
476
477        // Create the cycle error
478        let error = CycleError {
479            usage,
480            cycle: stack
481                .iter()
482                .map(|&(s, ref q)| QueryInfo { span: s, frame: q.frame(query_map) })
483                .collect(),
484        };
485
486        // We unwrap `waiter` here since there must always be one
487        // edge which is resumable / waited using a query latch
488        let (waitee_query, waiter_idx) = waiter.unwrap();
489
490        // Extract the waiter we want to resume
491        let waiter = waitee_query.latch(query_map).unwrap().extract_waiter(waiter_idx);
492
493        // Set the cycle error so it will be picked up when resumed
494        *waiter.cycle.lock() = Some(error);
495
496        // Put the waiter on the list of things to resume
497        wakelist.push(waiter);
498
499        true
500    } else {
501        false
502    }
503}
504
505/// Detects query cycles by using depth first search over all active query jobs.
506/// If a query cycle is found it will break the cycle by finding an edge which
507/// uses a query latch and then resuming that waiter.
508/// There may be multiple cycles involved in a deadlock, so this searches
509/// all active queries for cycles before finally resuming all the waiters at once.
510pub fn break_query_cycles<'tcx>(query_map: QueryMap<'tcx>, registry: &rustc_thread_pool::Registry) {
511    let mut wakelist = Vec::new();
512    // It is OK per the comments:
513    // - https://github.com/rust-lang/rust/pull/131200#issuecomment-2798854932
514    // - https://github.com/rust-lang/rust/pull/131200#issuecomment-2798866392
515    #[allow(rustc::potential_query_instability)]
516    let mut jobs: Vec<QueryJobId> = query_map.keys().cloned().collect();
517
518    let mut found_cycle = false;
519
520    while jobs.len() > 0 {
521        if remove_cycle(&query_map, &mut jobs, &mut wakelist) {
522            found_cycle = true;
523        }
524    }
525
526    // Check that a cycle was found. It is possible for a deadlock to occur without
527    // a query cycle if a query which can be waited on uses Rayon to do multithreading
528    // internally. Such a query (X) may be executing on 2 threads (A and B) and A may
529    // wait using Rayon on B. Rayon may then switch to executing another query (Y)
530    // which in turn will wait on X causing a deadlock. We have a false dependency from
531    // X to Y due to Rayon waiting and a true dependency from Y to X. The algorithm here
532    // only considers the true dependency and won't detect a cycle.
533    if !found_cycle {
534        {
    ::core::panicking::panic_fmt(format_args!("deadlock detected as we\'re unable to find a query cycle to break\ncurrent query map:\n{0:#?}",
            query_map));
};panic!(
535            "deadlock detected as we're unable to find a query cycle to break\n\
536            current query map:\n{:#?}",
537            query_map
538        );
539    }
540
541    // Mark all the thread we're about to wake up as unblocked. This needs to be done before
542    // we wake the threads up as otherwise Rayon could detect a deadlock if a thread we
543    // resumed fell asleep and this thread had yet to mark the remaining threads as unblocked.
544    for _ in 0..wakelist.len() {
545        rustc_thread_pool::mark_unblocked(registry);
546    }
547
548    for waiter in wakelist.into_iter() {
549        waiter.condvar.notify_one();
550    }
551}
552
553#[inline(never)]
554#[cold]
555pub fn report_cycle<'a>(
556    sess: &'a Session,
557    CycleError { usage, cycle: stack }: &CycleError,
558) -> Diag<'a> {
559    if !!stack.is_empty() {
    ::core::panicking::panic("assertion failed: !stack.is_empty()")
};assert!(!stack.is_empty());
560
561    let span = stack[0].frame.info.default_span(stack[1 % stack.len()].span);
562
563    let mut cycle_stack = Vec::new();
564
565    use crate::error::StackCount;
566    let stack_count = if stack.len() == 1 { StackCount::Single } else { StackCount::Multiple };
567
568    for i in 1..stack.len() {
569        let frame = &stack[i].frame;
570        let span = frame.info.default_span(stack[(i + 1) % stack.len()].span);
571        cycle_stack.push(CycleStack { span, desc: frame.info.description.to_owned() });
572    }
573
574    let mut cycle_usage = None;
575    if let Some((span, ref query)) = *usage {
576        cycle_usage = Some(crate::error::CycleUsage {
577            span: query.info.default_span(span),
578            usage: query.info.description.to_string(),
579        });
580    }
581
582    let alias =
583        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))) {
584            Some(crate::error::Alias::Ty)
585        } else if stack.iter().all(|entry| entry.frame.info.def_kind == Some(DefKind::TraitAlias)) {
586            Some(crate::error::Alias::Trait)
587        } else {
588            None
589        };
590
591    let cycle_diag = crate::error::Cycle {
592        span,
593        cycle_stack,
594        stack_bottom: stack[0].frame.info.description.to_owned(),
595        alias,
596        cycle_usage,
597        stack_count,
598        note_span: (),
599    };
600
601    sess.dcx().create_err(cycle_diag)
602}
603
604pub fn print_query_stack<'tcx, Qcx: QueryContext<'tcx>>(
605    qcx: Qcx,
606    mut current_query: Option<QueryJobId>,
607    dcx: DiagCtxtHandle<'_>,
608    limit_frames: Option<usize>,
609    mut file: Option<std::fs::File>,
610) -> usize {
611    // Be careful relying on global state here: this code is called from
612    // a panic hook, which means that the global `DiagCtxt` may be in a weird
613    // state if it was responsible for triggering the panic.
614    let mut count_printed = 0;
615    let mut count_total = 0;
616
617    // Make use of a partial query map if we fail to take locks collecting active queries.
618    let query_map = match qcx.collect_active_jobs_from_all_queries(false) {
619        Ok(query_map) => query_map,
620        Err(query_map) => query_map,
621    };
622
623    if let Some(ref mut file) = file {
624        let _ = file.write_fmt(format_args!("\n\nquery stack during panic:\n"))writeln!(file, "\n\nquery stack during panic:");
625    }
626    while let Some(query) = current_query {
627        let Some(query_info) = query_map.get(&query) else {
628            break;
629        };
630        let query_extra = query_info.frame.info.extract();
631        if Some(count_printed) < limit_frames || limit_frames.is_none() {
632            // Only print to stderr as many stack frames as `num_frames` when present.
633            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!(
634                "#{} [{:?}] {}",
635                count_printed, query_info.frame.dep_kind, query_extra.description
636            ))
637            .with_span(query_info.job.span)
638            .emit();
639            count_printed += 1;
640        }
641
642        if let Some(ref mut file) = file {
643            let _ = file.write_fmt(format_args!("#{0} [{1}] {2}\n", count_total,
        qcx.dep_context().dep_kind_vtable(query_info.frame.dep_kind).name,
        query_extra.description))writeln!(
644                file,
645                "#{} [{}] {}",
646                count_total,
647                qcx.dep_context().dep_kind_vtable(query_info.frame.dep_kind).name,
648                query_extra.description
649            );
650        }
651
652        current_query = query_info.job.parent;
653        count_total += 1;
654    }
655
656    if let Some(ref mut file) = file {
657        let _ = file.write_fmt(format_args!("end of query stack\n"))writeln!(file, "end of query stack");
658    }
659    count_total
660}