rustc_borrowck/type_check/liveness/
trace.rs1use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
2use rustc_index::bit_set::DenseBitSet;
3use rustc_index::interval::IntervalSet;
4use rustc_infer::infer::canonical::QueryRegionConstraints;
5use rustc_infer::infer::outlives::for_liveness;
6use rustc_middle::mir::{BasicBlock, Body, ConstraintCategory, Local, Location};
7use rustc_middle::traits::query::DropckOutlivesResult;
8use rustc_middle::ty::relate::Relate;
9use rustc_middle::ty::{Ty, TyCtxt, TypeVisitable, TypeVisitableExt};
10use rustc_mir_dataflow::ResultsCursor;
11use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
12use rustc_mir_dataflow::move_paths::{HasMoveData, MoveData, MovePathIndex};
13use rustc_mir_dataflow::points::{DenseLocationMap, PointIndex};
14use rustc_span::DUMMY_SP;
15use rustc_trait_selection::traits::query::type_op::{DropckOutlives, TypeOp, TypeOpOutput};
16use tracing::debug;
17
18use crate::polonius;
19use crate::region_infer::values;
20use crate::type_check::liveness::local_use_map::LocalUseMap;
21use crate::type_check::{NormalizeLocation, TypeChecker};
22
23pub(super) fn trace<'a, 'tcx>(
38 typeck: &mut TypeChecker<'_, 'tcx>,
39 body: &Body<'tcx>,
40 location_map: &DenseLocationMap,
41 flow_inits: ResultsCursor<'a, 'tcx, MaybeInitializedPlaces<'a, 'tcx>>,
42 move_data: &MoveData<'tcx>,
43 relevant_live_locals: Vec<Local>,
44 boring_locals: Vec<Local>,
45) {
46 let local_use_map = &LocalUseMap::build(&relevant_live_locals, location_map, body);
47 let cx = LivenessContext {
48 typeck,
49 body,
50 flow_inits,
51 location_map,
52 local_use_map,
53 move_data,
54 drop_data: FxIndexMap::default(),
55 };
56
57 let mut results = LivenessResults::new(cx);
58
59 results.add_extra_drop_facts(&relevant_live_locals);
60
61 results.compute_for_all_locals(relevant_live_locals);
62
63 results.dropck_boring_locals(boring_locals);
64}
65
66struct LivenessContext<'a, 'typeck, 'b, 'tcx> {
68 typeck: &'a mut TypeChecker<'typeck, 'tcx>,
70
71 location_map: &'a DenseLocationMap,
73
74 body: &'a Body<'tcx>,
76
77 move_data: &'a MoveData<'tcx>,
79
80 drop_data: FxIndexMap<Ty<'tcx>, DropData<'tcx>>,
82
83 flow_inits: ResultsCursor<'b, 'tcx, MaybeInitializedPlaces<'b, 'tcx>>,
86
87 local_use_map: &'a LocalUseMap,
90}
91
92struct DropData<'tcx> {
93 dropck_result: DropckOutlivesResult<'tcx>,
94 region_constraint_data: Option<&'tcx QueryRegionConstraints<'tcx>>,
95}
96
97struct LivenessResults<'a, 'typeck, 'b, 'tcx> {
98 cx: LivenessContext<'a, 'typeck, 'b, 'tcx>,
99
100 defs: DenseBitSet<PointIndex>,
102
103 use_live_at: IntervalSet<PointIndex>,
106
107 drop_live_at: IntervalSet<PointIndex>,
111
112 drop_locations: Vec<Location>,
114
115 stack: Vec<PointIndex>,
117}
118
119impl<'a, 'typeck, 'b, 'tcx> LivenessResults<'a, 'typeck, 'b, 'tcx> {
120 fn new(cx: LivenessContext<'a, 'typeck, 'b, 'tcx>) -> Self {
121 let num_points = cx.location_map.num_points();
122 LivenessResults {
123 cx,
124 defs: DenseBitSet::new_empty(num_points),
125 use_live_at: IntervalSet::new(num_points),
126 drop_live_at: IntervalSet::new(num_points),
127 drop_locations: vec![],
128 stack: vec![],
129 }
130 }
131
132 fn compute_for_all_locals(&mut self, relevant_live_locals: Vec<Local>) {
133 for local in relevant_live_locals {
134 self.reset_local_state();
135 self.add_defs_for(local);
136 self.compute_use_live_points_for(local);
137 self.compute_drop_live_points_for(local);
138
139 let local_ty = self.cx.body.local_decls[local].ty;
140
141 if !self.use_live_at.is_empty() {
142 self.cx.add_use_live_facts_for(local_ty, &self.use_live_at);
143 }
144
145 if !self.drop_live_at.is_empty() {
146 self.cx.add_drop_live_facts_for(
147 local,
148 local_ty,
149 &self.drop_locations,
150 &self.drop_live_at,
151 );
152 }
153 }
154 }
155
156 fn dropck_boring_locals(&mut self, boring_locals: Vec<Local>) {
163 for local in boring_locals {
164 let local_ty = self.cx.body.local_decls[local].ty;
165 let drop_data = self.cx.drop_data.entry(local_ty).or_insert_with({
166 let typeck = &self.cx.typeck;
167 move || LivenessContext::compute_drop_data(typeck, local_ty)
168 });
169
170 drop_data.dropck_result.report_overflows(
171 self.cx.typeck.infcx.tcx,
172 self.cx.body.local_decls[local].source_info.span,
173 local_ty,
174 );
175 }
176 }
177
178 fn add_extra_drop_facts(&mut self, relevant_live_locals: &[Local]) {
183 let Some(facts) = self.cx.typeck.polonius_facts.as_ref() else { return };
193 let facts_to_add: Vec<_> = {
194 let relevant_live_locals: FxIndexSet<_> =
195 relevant_live_locals.iter().copied().collect();
196
197 facts
198 .var_dropped_at
199 .iter()
200 .filter_map(|&(local, location_index)| {
201 let local_ty = self.cx.body.local_decls[local].ty;
202 if relevant_live_locals.contains(&local) || !local_ty.has_free_regions() {
203 return None;
204 }
205
206 let location = self.cx.typeck.location_table.to_location(location_index);
207 Some((local, local_ty, location))
208 })
209 .collect()
210 };
211
212 let live_at = IntervalSet::new(self.cx.location_map.num_points());
213 for (local, local_ty, location) in facts_to_add {
214 self.cx.add_drop_live_facts_for(local, local_ty, &[location], &live_at);
215 }
216 }
217
218 fn reset_local_state(&mut self) {
220 self.defs.clear();
221 self.use_live_at.clear();
222 self.drop_live_at.clear();
223 self.drop_locations.clear();
224 assert!(self.stack.is_empty());
225 }
226
227 fn add_defs_for(&mut self, local: Local) {
229 for def in self.cx.local_use_map.defs(local) {
230 debug!("- defined at {:?}", def);
231 self.defs.insert(def);
232 }
233 }
234
235 fn compute_use_live_points_for(&mut self, local: Local) {
242 debug!("compute_use_live_points_for(local={:?})", local);
243
244 self.stack.extend(self.cx.local_use_map.uses(local));
245 while let Some(p) = self.stack.pop() {
246 let block_start = self.cx.location_map.to_block_start(p);
252 let previous_defs = self.defs.last_set_in(block_start..=p);
253 let previous_live_at = self.use_live_at.last_set_in(block_start..=p);
254
255 let exclusive_start = match (previous_defs, previous_live_at) {
256 (Some(a), Some(b)) => Some(std::cmp::max(a, b)),
257 (Some(a), None) | (None, Some(a)) => Some(a),
258 (None, None) => None,
259 };
260
261 if let Some(exclusive) = exclusive_start {
262 self.use_live_at.insert_range(exclusive + 1..=p);
263
264 continue;
267 } else {
268 self.use_live_at.insert_range(block_start..=p);
270
271 let block = self.cx.location_map.to_location(block_start).block;
276 self.stack.extend(
277 self.cx.body.basic_blocks.predecessors()[block]
278 .iter()
279 .map(|&pred_bb| self.cx.body.terminator_loc(pred_bb))
280 .map(|pred_loc| self.cx.location_map.point_from_location(pred_loc)),
281 );
282 }
283 }
284 }
285
286 fn compute_drop_live_points_for(&mut self, local: Local) {
296 debug!("compute_drop_live_points_for(local={:?})", local);
297
298 let Some(mpi) = self.cx.move_data.rev_lookup.find_local(local) else { return };
299 debug!("compute_drop_live_points_for: mpi = {:?}", mpi);
300
301 for drop_point in self.cx.local_use_map.drops(local) {
303 let location = self.cx.location_map.to_location(drop_point);
304 debug_assert_eq!(self.cx.body.terminator_loc(location.block), location,);
305
306 if self.cx.initialized_at_terminator(location.block, mpi)
307 && self.drop_live_at.insert(drop_point)
308 {
309 self.drop_locations.push(location);
310 self.stack.push(drop_point);
311 }
312 }
313
314 debug!("compute_drop_live_points_for: drop_locations={:?}", self.drop_locations);
315
316 while let Some(term_point) = self.stack.pop() {
320 self.compute_drop_live_points_for_block(mpi, term_point);
321 }
322 }
323
324 fn compute_drop_live_points_for_block(&mut self, mpi: MovePathIndex, term_point: PointIndex) {
336 debug!(
337 "compute_drop_live_points_for_block(mpi={:?}, term_point={:?})",
338 self.cx.move_data.move_paths[mpi].place,
339 self.cx.location_map.to_location(term_point),
340 );
341
342 debug_assert!(self.drop_live_at.contains(term_point));
345
346 let term_location = self.cx.location_map.to_location(term_point);
350 debug_assert_eq!(self.cx.body.terminator_loc(term_location.block), term_location,);
351 let block = term_location.block;
352 let entry_point = self.cx.location_map.entry_point(term_location.block);
353 for p in (entry_point..term_point).rev() {
354 debug!(
355 "compute_drop_live_points_for_block: p = {:?}",
356 self.cx.location_map.to_location(p)
357 );
358
359 if self.defs.contains(p) {
360 debug!("compute_drop_live_points_for_block: def site");
361 return;
362 }
363
364 if self.use_live_at.contains(p) {
365 debug!("compute_drop_live_points_for_block: use-live at {:?}", p);
366 return;
367 }
368
369 if !self.drop_live_at.insert(p) {
370 debug!("compute_drop_live_points_for_block: already drop-live");
371 return;
372 }
373 }
374
375 let body = self.cx.body;
376 for &pred_block in body.basic_blocks.predecessors()[block].iter() {
377 debug!("compute_drop_live_points_for_block: pred_block = {:?}", pred_block,);
378
379 if !self.cx.initialized_at_exit(pred_block, mpi) {
398 debug!("compute_drop_live_points_for_block: not initialized");
399 continue;
400 }
401
402 let pred_term_loc = self.cx.body.terminator_loc(pred_block);
403 let pred_term_point = self.cx.location_map.point_from_location(pred_term_loc);
404
405 if self.defs.contains(pred_term_point) {
408 debug!("compute_drop_live_points_for_block: defined at {:?}", pred_term_loc);
409 continue;
410 }
411
412 if self.use_live_at.contains(pred_term_point) {
413 debug!("compute_drop_live_points_for_block: use-live at {:?}", pred_term_loc);
414 continue;
415 }
416
417 if self.drop_live_at.insert(pred_term_point) {
420 debug!("compute_drop_live_points_for_block: pushed to stack");
421 self.stack.push(pred_term_point);
422 }
423 }
424
425 }
459}
460
461impl<'tcx> LivenessContext<'_, '_, '_, 'tcx> {
462 fn initialized_at_curr_loc(&self, mpi: MovePathIndex) -> bool {
466 let state = self.flow_inits.get();
467 if state.contains(mpi) {
468 return true;
469 }
470
471 let move_paths = &self.flow_inits.analysis().move_data().move_paths;
472 move_paths[mpi].find_descendant(move_paths, |mpi| state.contains(mpi)).is_some()
473 }
474
475 fn initialized_at_terminator(&mut self, block: BasicBlock, mpi: MovePathIndex) -> bool {
480 self.flow_inits.seek_before_primary_effect(self.body.terminator_loc(block));
481 self.initialized_at_curr_loc(mpi)
482 }
483
484 fn initialized_at_exit(&mut self, block: BasicBlock, mpi: MovePathIndex) -> bool {
490 self.flow_inits.seek_after_primary_effect(self.body.terminator_loc(block));
491 self.initialized_at_curr_loc(mpi)
492 }
493
494 fn add_use_live_facts_for(&mut self, value: Ty<'tcx>, live_at: &IntervalSet<PointIndex>) {
497 debug!("add_use_live_facts_for(value={:?})", value);
498 Self::make_all_regions_live(self.location_map, self.typeck, value, live_at);
499 }
500
501 fn add_drop_live_facts_for(
507 &mut self,
508 dropped_local: Local,
509 dropped_ty: Ty<'tcx>,
510 drop_locations: &[Location],
511 live_at: &IntervalSet<PointIndex>,
512 ) {
513 debug!(
514 "add_drop_live_constraint(\
515 dropped_local={:?}, \
516 dropped_ty={:?}, \
517 drop_locations={:?}, \
518 live_at={:?})",
519 dropped_local,
520 dropped_ty,
521 drop_locations,
522 values::pretty_print_points(self.location_map, live_at.iter()),
523 );
524
525 let drop_data = self.drop_data.entry(dropped_ty).or_insert_with({
526 let typeck = &self.typeck;
527 move || Self::compute_drop_data(typeck, dropped_ty)
528 });
529
530 if let Some(data) = &drop_data.region_constraint_data {
531 for &drop_location in drop_locations {
532 self.typeck.push_region_constraints(
533 drop_location.to_locations(),
534 ConstraintCategory::Boring,
535 data,
536 );
537 }
538 }
539
540 drop_data.dropck_result.report_overflows(
541 self.typeck.infcx.tcx,
542 self.body.source_info(*drop_locations.first().unwrap()).span,
543 dropped_ty,
544 );
545
546 for &kind in &drop_data.dropck_result.kinds {
549 Self::make_all_regions_live(self.location_map, self.typeck, kind, live_at);
550 polonius::legacy::emit_drop_facts(
551 self.typeck.tcx(),
552 dropped_local,
553 &kind,
554 self.typeck.universal_regions,
555 self.typeck.polonius_facts,
556 );
557 }
558 }
559
560 fn make_all_regions_live(
561 location_map: &DenseLocationMap,
562 typeck: &mut TypeChecker<'_, 'tcx>,
563 value: impl TypeVisitable<TyCtxt<'tcx>> + Relate<TyCtxt<'tcx>>,
564 live_at: &IntervalSet<PointIndex>,
565 ) {
566 debug!("make_all_regions_live(value={:?})", value);
567 debug!(
568 "make_all_regions_live: live_at={}",
569 values::pretty_print_points(location_map, live_at.iter()),
570 );
571
572 value.visit_with(&mut for_liveness::FreeRegionsVisitor {
573 tcx: typeck.tcx(),
574 param_env: typeck.infcx.param_env,
575 op: |r| {
576 let live_region_vid = typeck.universal_regions.to_region_vid(r);
577
578 typeck.constraints.liveness_constraints.add_points(live_region_vid, live_at);
579 },
580 });
581
582 if let Some(polonius_liveness) = typeck.polonius_liveness.as_mut() {
584 polonius_liveness.record_live_region_variance(
585 typeck.infcx.tcx,
586 typeck.universal_regions,
587 value,
588 );
589 }
590 }
591
592 fn compute_drop_data(typeck: &TypeChecker<'_, 'tcx>, dropped_ty: Ty<'tcx>) -> DropData<'tcx> {
593 debug!("compute_drop_data(dropped_ty={:?})", dropped_ty,);
594
595 match typeck
596 .infcx
597 .param_env
598 .and(DropckOutlives { dropped_ty })
599 .fully_perform(typeck.infcx, DUMMY_SP)
600 {
601 Ok(TypeOpOutput { output, constraints, .. }) => {
602 DropData { dropck_result: output, region_constraint_data: constraints }
603 }
604 Err(_) => DropData { dropck_result: Default::default(), region_constraint_data: None },
605 }
606 }
607}