rustc_query_system/query/
job.rs

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