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