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