rustc_borrowck/
nll.rs

1//! The entry point of the NLL borrow checker.
2
3use std::io;
4use std::path::PathBuf;
5use std::rc::Rc;
6use std::str::FromStr;
7
8use polonius_engine::{Algorithm, Output};
9use rustc_index::IndexSlice;
10use rustc_middle::mir::pretty::{PrettyPrintMirOptions, dump_mir_with_options};
11use rustc_middle::mir::{Body, PassWhere, Promoted, create_dump_file, dump_enabled, dump_mir};
12use rustc_middle::ty::print::with_no_trimmed_paths;
13use rustc_middle::ty::{self, TyCtxt};
14use rustc_mir_dataflow::move_paths::MoveData;
15use rustc_mir_dataflow::points::DenseLocationMap;
16use rustc_session::config::MirIncludeSpans;
17use rustc_span::sym;
18use tracing::{debug, instrument};
19
20use crate::borrow_set::BorrowSet;
21use crate::consumers::ConsumerOptions;
22use crate::diagnostics::RegionErrors;
23use crate::handle_placeholders::compute_sccs_applying_placeholder_outlives_constraints;
24use crate::polonius::PoloniusDiagnosticsContext;
25use crate::polonius::legacy::{
26    PoloniusFacts, PoloniusFactsExt, PoloniusLocationTable, PoloniusOutput,
27};
28use crate::region_infer::RegionInferenceContext;
29use crate::type_check::{self, MirTypeckResults};
30use crate::universal_regions::UniversalRegions;
31use crate::{
32    BorrowCheckRootCtxt, BorrowckInferCtxt, ClosureOutlivesSubject, ClosureRegionRequirements,
33    polonius, renumber,
34};
35
36/// The output of `nll::compute_regions`. This includes the computed `RegionInferenceContext`, any
37/// closure requirements to propagate, and any generated errors.
38pub(crate) struct NllOutput<'tcx> {
39    pub regioncx: RegionInferenceContext<'tcx>,
40    pub polonius_input: Option<Box<PoloniusFacts>>,
41    pub polonius_output: Option<Box<PoloniusOutput>>,
42    pub opt_closure_req: Option<ClosureRegionRequirements<'tcx>>,
43    pub nll_errors: RegionErrors<'tcx>,
44
45    /// When using `-Zpolonius=next`: the data used to compute errors and diagnostics, e.g.
46    /// localized typeck and liveness constraints.
47    pub polonius_diagnostics: Option<PoloniusDiagnosticsContext>,
48}
49
50/// Rewrites the regions in the MIR to use NLL variables, also scraping out the set of universal
51/// regions (e.g., region parameters) declared on the function. That set will need to be given to
52/// `compute_regions`.
53#[instrument(skip(infcx, body, promoted), level = "debug")]
54pub(crate) fn replace_regions_in_mir<'tcx>(
55    infcx: &BorrowckInferCtxt<'tcx>,
56    body: &mut Body<'tcx>,
57    promoted: &mut IndexSlice<Promoted, Body<'tcx>>,
58) -> UniversalRegions<'tcx> {
59    let def = body.source.def_id().expect_local();
60
61    debug!(?def);
62
63    // Compute named region information. This also renumbers the inputs/outputs.
64    let universal_regions = UniversalRegions::new(infcx, def);
65
66    // Replace all remaining regions with fresh inference variables.
67    renumber::renumber_mir(infcx, body, promoted);
68
69    dump_mir(infcx.tcx, false, "renumber", &0, body, |_, _| Ok(()));
70
71    universal_regions
72}
73
74/// Computes the (non-lexical) regions from the input MIR.
75///
76/// This may result in errors being reported.
77pub(crate) fn compute_regions<'tcx>(
78    root_cx: &mut BorrowCheckRootCtxt<'tcx>,
79    infcx: &BorrowckInferCtxt<'tcx>,
80    universal_regions: UniversalRegions<'tcx>,
81    body: &Body<'tcx>,
82    promoted: &IndexSlice<Promoted, Body<'tcx>>,
83    location_table: &PoloniusLocationTable,
84    move_data: &MoveData<'tcx>,
85    borrow_set: &BorrowSet<'tcx>,
86    consumer_options: Option<ConsumerOptions>,
87) -> NllOutput<'tcx> {
88    let is_polonius_legacy_enabled = infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled();
89    let polonius_input = consumer_options.map(|c| c.polonius_input()).unwrap_or_default()
90        || is_polonius_legacy_enabled;
91    let polonius_output = consumer_options.map(|c| c.polonius_output()).unwrap_or_default()
92        || is_polonius_legacy_enabled;
93    let mut polonius_facts =
94        (polonius_input || PoloniusFacts::enabled(infcx.tcx)).then_some(PoloniusFacts::default());
95
96    let location_map = Rc::new(DenseLocationMap::new(body));
97
98    // Run the MIR type-checker.
99    let MirTypeckResults {
100        constraints,
101        universal_region_relations,
102        opaque_type_values,
103        polonius_context,
104    } = type_check::type_check(
105        root_cx,
106        infcx,
107        body,
108        promoted,
109        universal_regions,
110        location_table,
111        borrow_set,
112        &mut polonius_facts,
113        move_data,
114        Rc::clone(&location_map),
115    );
116
117    let lowered_constraints = compute_sccs_applying_placeholder_outlives_constraints(
118        constraints,
119        &universal_region_relations,
120        infcx,
121    );
122
123    // If requested, emit legacy polonius facts.
124    polonius::legacy::emit_facts(
125        &mut polonius_facts,
126        infcx.tcx,
127        location_table,
128        body,
129        borrow_set,
130        move_data,
131        &universal_region_relations,
132        &lowered_constraints,
133    );
134
135    let mut regioncx = RegionInferenceContext::new(
136        infcx,
137        lowered_constraints,
138        universal_region_relations,
139        location_map,
140    );
141
142    // If requested for `-Zpolonius=next`, convert NLL constraints to localized outlives constraints
143    // and use them to compute loan liveness.
144    let polonius_diagnostics = polonius_context.map(|polonius_context| {
145        polonius_context.compute_loan_liveness(infcx.tcx, &mut regioncx, body, borrow_set)
146    });
147
148    // If requested: dump NLL facts, and run legacy polonius analysis.
149    let polonius_output = polonius_facts.as_ref().and_then(|polonius_facts| {
150        if infcx.tcx.sess.opts.unstable_opts.nll_facts {
151            let def_id = body.source.def_id();
152            let def_path = infcx.tcx.def_path(def_id);
153            let dir_path = PathBuf::from(&infcx.tcx.sess.opts.unstable_opts.nll_facts_dir)
154                .join(def_path.to_filename_friendly_no_crate());
155            polonius_facts.write_to_dir(dir_path, location_table).unwrap();
156        }
157
158        if polonius_output {
159            let algorithm = infcx.tcx.env_var("POLONIUS_ALGORITHM").unwrap_or("Hybrid");
160            let algorithm = Algorithm::from_str(algorithm).unwrap();
161            debug!("compute_regions: using polonius algorithm {:?}", algorithm);
162            let _prof_timer = infcx.tcx.prof.generic_activity("polonius_analysis");
163            Some(Box::new(Output::compute(polonius_facts, algorithm, false)))
164        } else {
165            None
166        }
167    });
168
169    // Solve the region constraints.
170    let (closure_region_requirements, nll_errors) =
171        regioncx.solve(infcx, body, polonius_output.clone());
172
173    if let Some(guar) = nll_errors.has_errors() {
174        // Suppress unhelpful extra errors in `infer_opaque_types`.
175        infcx.set_tainted_by_errors(guar);
176    }
177
178    regioncx.infer_opaque_types(root_cx, infcx, opaque_type_values);
179
180    NllOutput {
181        regioncx,
182        polonius_input: polonius_facts.map(Box::new),
183        polonius_output,
184        opt_closure_req: closure_region_requirements,
185        nll_errors,
186        polonius_diagnostics,
187    }
188}
189
190/// `-Zdump-mir=nll` dumps MIR annotated with NLL specific information:
191/// - free regions
192/// - inferred region values
193/// - region liveness
194/// - inference constraints and their causes
195///
196/// As well as graphviz `.dot` visualizations of:
197/// - the region constraints graph
198/// - the region SCC graph
199pub(super) fn dump_nll_mir<'tcx>(
200    infcx: &BorrowckInferCtxt<'tcx>,
201    body: &Body<'tcx>,
202    regioncx: &RegionInferenceContext<'tcx>,
203    closure_region_requirements: &Option<ClosureRegionRequirements<'tcx>>,
204    borrow_set: &BorrowSet<'tcx>,
205) {
206    let tcx = infcx.tcx;
207    if !dump_enabled(tcx, "nll", body.source.def_id()) {
208        return;
209    }
210
211    // We want the NLL extra comments printed by default in NLL MIR dumps (they were removed in
212    // #112346). Specifying `-Z mir-include-spans` on the CLI still has priority: for example,
213    // they're always disabled in mir-opt tests to make working with blessed dumps easier.
214    let options = PrettyPrintMirOptions {
215        include_extra_comments: matches!(
216            infcx.tcx.sess.opts.unstable_opts.mir_include_spans,
217            MirIncludeSpans::On | MirIncludeSpans::Nll
218        ),
219    };
220    dump_mir_with_options(
221        tcx,
222        false,
223        "nll",
224        &0,
225        body,
226        |pass_where, out| {
227            emit_nll_mir(tcx, regioncx, closure_region_requirements, borrow_set, pass_where, out)
228        },
229        options,
230    );
231
232    // Also dump the region constraint graph as a graphviz file.
233    let _: io::Result<()> = try {
234        let mut file = create_dump_file(tcx, "regioncx.all.dot", false, "nll", &0, body)?;
235        regioncx.dump_graphviz_raw_constraints(&mut file)?;
236    };
237
238    // Also dump the region constraint SCC graph as a graphviz file.
239    let _: io::Result<()> = try {
240        let mut file = create_dump_file(tcx, "regioncx.scc.dot", false, "nll", &0, body)?;
241        regioncx.dump_graphviz_scc_constraints(&mut file)?;
242    };
243}
244
245/// Produces the actual NLL MIR sections to emit during the dumping process.
246pub(crate) fn emit_nll_mir<'tcx>(
247    tcx: TyCtxt<'tcx>,
248    regioncx: &RegionInferenceContext<'tcx>,
249    closure_region_requirements: &Option<ClosureRegionRequirements<'tcx>>,
250    borrow_set: &BorrowSet<'tcx>,
251    pass_where: PassWhere,
252    out: &mut dyn io::Write,
253) -> io::Result<()> {
254    match pass_where {
255        // Before the CFG, dump out the values for each region variable.
256        PassWhere::BeforeCFG => {
257            regioncx.dump_mir(tcx, out)?;
258            writeln!(out, "|")?;
259
260            if let Some(closure_region_requirements) = closure_region_requirements {
261                writeln!(out, "| Free Region Constraints")?;
262                for_each_region_constraint(tcx, closure_region_requirements, &mut |msg| {
263                    writeln!(out, "| {msg}")
264                })?;
265                writeln!(out, "|")?;
266            }
267
268            if borrow_set.len() > 0 {
269                writeln!(out, "| Borrows")?;
270                for (borrow_idx, borrow_data) in borrow_set.iter_enumerated() {
271                    writeln!(
272                        out,
273                        "| {:?}: issued at {:?} in {:?}",
274                        borrow_idx, borrow_data.reserve_location, borrow_data.region
275                    )?;
276                }
277                writeln!(out, "|")?;
278            }
279        }
280
281        PassWhere::BeforeLocation(_) => {}
282
283        PassWhere::AfterTerminator(_) => {}
284
285        PassWhere::BeforeBlock(_) | PassWhere::AfterLocation(_) | PassWhere::AfterCFG => {}
286    }
287    Ok(())
288}
289
290#[allow(rustc::diagnostic_outside_of_impl)]
291#[allow(rustc::untranslatable_diagnostic)]
292pub(super) fn dump_annotation<'tcx, 'infcx>(
293    infcx: &'infcx BorrowckInferCtxt<'tcx>,
294    body: &Body<'tcx>,
295    regioncx: &RegionInferenceContext<'tcx>,
296    closure_region_requirements: &Option<ClosureRegionRequirements<'tcx>>,
297) {
298    let tcx = infcx.tcx;
299    let base_def_id = tcx.typeck_root_def_id(body.source.def_id());
300    if !tcx.has_attr(base_def_id, sym::rustc_regions) {
301        return;
302    }
303
304    // When the enclosing function is tagged with `#[rustc_regions]`,
305    // we dump out various bits of state as warnings. This is useful
306    // for verifying that the compiler is behaving as expected. These
307    // warnings focus on the closure region requirements -- for
308    // viewing the intraprocedural state, the -Zdump-mir output is
309    // better.
310
311    let def_span = tcx.def_span(body.source.def_id());
312    let err = if let Some(closure_region_requirements) = closure_region_requirements {
313        let mut err = infcx.dcx().struct_span_note(def_span, "external requirements");
314
315        regioncx.annotate(tcx, &mut err);
316
317        err.note(format!(
318            "number of external vids: {}",
319            closure_region_requirements.num_external_vids
320        ));
321
322        // Dump the region constraints we are imposing *between* those
323        // newly created variables.
324        for_each_region_constraint(tcx, closure_region_requirements, &mut |msg| {
325            err.note(msg);
326            Ok(())
327        })
328        .unwrap();
329
330        err
331    } else {
332        let mut err = infcx.dcx().struct_span_note(def_span, "no external requirements");
333        regioncx.annotate(tcx, &mut err);
334        err
335    };
336
337    // FIXME(@lcnr): We currently don't dump the inferred hidden types here.
338    err.emit();
339}
340
341fn for_each_region_constraint<'tcx>(
342    tcx: TyCtxt<'tcx>,
343    closure_region_requirements: &ClosureRegionRequirements<'tcx>,
344    with_msg: &mut dyn FnMut(String) -> io::Result<()>,
345) -> io::Result<()> {
346    for req in &closure_region_requirements.outlives_requirements {
347        let subject = match req.subject {
348            ClosureOutlivesSubject::Region(subject) => format!("{subject:?}"),
349            ClosureOutlivesSubject::Ty(ty) => {
350                with_no_trimmed_paths!(format!(
351                    "{}",
352                    ty.instantiate(tcx, |vid| ty::Region::new_var(tcx, vid))
353                ))
354            }
355        };
356        with_msg(format!("where {}: {:?}", subject, req.outlived_free_region,))?;
357    }
358    Ok(())
359}
360
361pub(crate) trait ConstraintDescription {
362    fn description(&self) -> &'static str;
363}