1 //! The entry point of the NLL borrow checker.
3 use rustc::infer::InferCtxt;
5 BasicBlock, Body, BodyAndCache, ClosureOutlivesSubject, ClosureRegionRequirements, LocalKind,
6 Location, Promoted, ReadOnlyBodyAndCache,
8 use rustc::ty::{self, RegionKind, RegionVid};
9 use rustc_errors::Diagnostic;
10 use rustc_hir::def_id::DefId;
11 use rustc_index::vec::IndexVec;
12 use rustc_span::symbol::sym;
16 use std::path::PathBuf;
18 use std::str::FromStr;
20 use self::mir_util::PassWhere;
21 use polonius_engine::{Algorithm, Output};
23 use crate::dataflow::move_paths::{InitKind, InitLocation, MoveData};
24 use crate::dataflow::FlowAtLocation;
25 use crate::dataflow::MaybeInitializedPlaces;
26 use crate::transform::MirSource;
27 use crate::util as mir_util;
28 use crate::util::pretty;
30 use crate::borrow_check::{
31 borrow_set::BorrowSet,
32 constraint_generation,
33 diagnostics::RegionErrors,
34 facts::{AllFacts, AllFactsExt, RustcFacts},
36 location::LocationTable,
37 region_infer::{values::RegionValueElements, RegionInferenceContext},
39 type_check::{self, MirTypeckRegionConstraints, MirTypeckResults},
40 universal_regions::UniversalRegions,
43 crate type PoloniusOutput = Output<RustcFacts>;
45 /// The output of `nll::compute_regions`. This includes the computed `RegionInferenceContext`, any
46 /// closure requirements to propagate, and any generated errors.
47 crate struct NllOutput<'tcx> {
48 pub regioncx: RegionInferenceContext<'tcx>,
49 pub polonius_output: Option<Rc<PoloniusOutput>>,
50 pub opt_closure_req: Option<ClosureRegionRequirements<'tcx>>,
51 pub nll_errors: RegionErrors<'tcx>,
54 /// Rewrites the regions in the MIR to use NLL variables, also scraping out the set of universal
55 /// regions (e.g., region parameters) declared on the function. That set will need to be given to
56 /// `compute_regions`.
57 pub(in crate::borrow_check) fn replace_regions_in_mir<'cx, 'tcx>(
58 infcx: &InferCtxt<'cx, 'tcx>,
60 param_env: ty::ParamEnv<'tcx>,
61 body: &mut BodyAndCache<'tcx>,
62 promoted: &mut IndexVec<Promoted, BodyAndCache<'tcx>>,
63 ) -> UniversalRegions<'tcx> {
64 debug!("replace_regions_in_mir(def_id={:?})", def_id);
66 // Compute named region information. This also renumbers the inputs/outputs.
67 let universal_regions = UniversalRegions::new(infcx, def_id, param_env);
69 // Replace all remaining regions with fresh inference variables.
70 renumber::renumber_mir(infcx, body, promoted);
72 let source = MirSource::item(def_id);
73 mir_util::dump_mir(infcx.tcx, None, "renumber", &0, source, body, |_, _| Ok(()));
78 // This function populates an AllFacts instance with base facts related to
79 // MovePaths and needed for the move analysis.
80 fn populate_polonius_move_facts(
81 all_facts: &mut AllFacts,
82 move_data: &MoveData<'_>,
83 location_table: &LocationTable,
88 .extend(move_data.rev_lookup.iter_locals_enumerated().map(|(v, &m)| (m, v)));
90 for (child, move_path) in move_data.move_paths.iter_enumerated() {
93 .extend(move_path.parents(&move_data.move_paths).iter().map(|&parent| (child, parent)));
97 for init in move_data.inits.iter() {
99 InitLocation::Statement(location) => {
100 let block_data = &body[location.block];
101 let is_terminator = location.statement_index == block_data.statements.len();
103 if is_terminator && init.kind == InitKind::NonPanicPathOnly {
104 // We are at the terminator of an init that has a panic path,
105 // and where the init should not happen on panic
107 for &successor in block_data.terminator().successors() {
108 if body[successor].is_cleanup {
112 // The initialization happened in (or rather, when arriving at)
113 // the successors, but not in the unwind block.
114 let first_statement = Location { block: successor, statement_index: 0 };
117 .push((init.path, location_table.start_index(first_statement)));
120 // In all other cases, the initialization just happens at the
121 // midpoint, like any other effect.
122 all_facts.initialized_at.push((init.path, location_table.mid_index(location)));
125 // Arguments are initialized on function entry
126 InitLocation::Argument(local) => {
127 assert!(body.local_kind(local) == LocalKind::Arg);
128 let fn_entry = Location { block: BasicBlock::from_u32(0u32), statement_index: 0 };
129 all_facts.initialized_at.push((init.path, location_table.start_index(fn_entry)));
135 // deinitialisation is assumed to always happen!
138 .extend(move_data.moves.iter().map(|mo| (mo.path, location_table.mid_index(mo.source))));
141 /// Computes the (non-lexical) regions from the input MIR.
143 /// This may result in errors being reported.
144 pub(in crate::borrow_check) fn compute_regions<'cx, 'tcx>(
145 infcx: &InferCtxt<'cx, 'tcx>,
147 universal_regions: UniversalRegions<'tcx>,
148 body: ReadOnlyBodyAndCache<'_, 'tcx>,
149 promoted: &IndexVec<Promoted, ReadOnlyBodyAndCache<'_, 'tcx>>,
150 location_table: &LocationTable,
151 param_env: ty::ParamEnv<'tcx>,
152 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'cx, 'tcx>>,
153 move_data: &MoveData<'tcx>,
154 borrow_set: &BorrowSet<'tcx>,
155 ) -> NllOutput<'tcx> {
156 let mut all_facts = AllFacts::enabled(infcx.tcx).then_some(AllFacts::default());
158 let universal_regions = Rc::new(universal_regions);
160 let elements = &Rc::new(RegionValueElements::new(&body));
162 // Run the MIR type-checker.
163 let MirTypeckResults { constraints, universal_region_relations } = type_check::type_check(
178 if let Some(all_facts) = &mut all_facts {
179 let _prof_timer = infcx.tcx.prof.generic_activity("polonius_fact_generation");
180 all_facts.universal_region.extend(universal_regions.universal_regions());
181 populate_polonius_move_facts(all_facts, move_data, location_table, &body);
183 // Emit universal regions facts, and their relations, for Polonius.
185 // 1: universal regions are modeled in Polonius as a pair:
186 // - the universal region vid itself.
187 // - a "placeholder loan" associated to this universal region. Since they don't exist in
188 // the `borrow_set`, their `BorrowIndex` are synthesized as the universal region index
189 // added to the existing number of loans, as if they succeeded them in the set.
191 let borrow_count = borrow_set.borrows.len();
193 "compute_regions: polonius placeholders, num_universals={}, borrow_count={}",
194 universal_regions.len(),
198 for universal_region in universal_regions.universal_regions() {
199 let universal_region_idx = universal_region.index();
200 let placeholder_loan_idx = borrow_count + universal_region_idx;
201 all_facts.placeholder.push((universal_region, placeholder_loan_idx.into()));
204 // 2: the universal region relations `outlives` constraints are emitted as
205 // `known_subset` facts.
206 for (fr1, fr2) in universal_region_relations.known_outlives() {
209 "compute_regions: emitting polonius `known_subset` fr1={:?}, fr2={:?}",
212 all_facts.known_subset.push((*fr1, *fr2));
217 // Create the region inference context, taking ownership of the
218 // region inference data that was contained in `infcx`, and the
219 // base constraints generated by the type-check.
220 let var_origins = infcx.take_region_var_origins();
221 let MirTypeckRegionConstraints {
223 placeholder_index_to_region: _,
224 mut liveness_constraints,
225 outlives_constraints,
227 closure_bounds_mapping,
230 let placeholder_indices = Rc::new(placeholder_indices);
232 constraint_generation::generate_constraints(
234 &mut liveness_constraints,
241 let mut regioncx = RegionInferenceContext::new(
245 universal_region_relations,
246 outlives_constraints,
248 closure_bounds_mapping,
250 liveness_constraints,
254 // Generate various additional constraints.
255 invalidation::generate_invalidates(infcx.tcx, &mut all_facts, location_table, body, borrow_set);
257 // Dump facts if requested.
258 let polonius_output = all_facts.and_then(|all_facts| {
259 if infcx.tcx.sess.opts.debugging_opts.nll_facts {
260 let def_path = infcx.tcx.hir().def_path(def_id);
262 PathBuf::from("nll-facts").join(def_path.to_filename_friendly_no_crate());
263 all_facts.write_to_dir(dir_path, location_table).unwrap();
266 if infcx.tcx.sess.opts.debugging_opts.polonius {
268 env::var("POLONIUS_ALGORITHM").unwrap_or_else(|_| String::from("Naive"));
269 let algorithm = Algorithm::from_str(&algorithm).unwrap();
270 debug!("compute_regions: using polonius algorithm {:?}", algorithm);
271 let _prof_timer = infcx.tcx.prof.generic_activity("polonius_analysis");
272 Some(Rc::new(Output::compute(&all_facts, algorithm, false)))
278 // Solve the region constraints.
279 let (closure_region_requirements, nll_errors) =
280 regioncx.solve(infcx, &body, def_id, polonius_output.clone());
285 opt_closure_req: closure_region_requirements,
290 pub(super) fn dump_mir_results<'a, 'tcx>(
291 infcx: &InferCtxt<'a, 'tcx>,
292 source: MirSource<'tcx>,
294 regioncx: &RegionInferenceContext<'_>,
295 closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
297 if !mir_util::dump_enabled(infcx.tcx, "nll", source) {
301 mir_util::dump_mir(infcx.tcx, None, "nll", &0, source, body, |pass_where, out| {
303 // Before the CFG, dump out the values for each region variable.
304 PassWhere::BeforeCFG => {
305 regioncx.dump_mir(out)?;
308 if let Some(closure_region_requirements) = closure_region_requirements {
309 writeln!(out, "| Free Region Constraints")?;
310 for_each_region_constraint(closure_region_requirements, &mut |msg| {
311 writeln!(out, "| {}", msg)
317 PassWhere::BeforeLocation(_) => {}
319 PassWhere::AfterTerminator(_) => {}
321 PassWhere::BeforeBlock(_) | PassWhere::AfterLocation(_) | PassWhere::AfterCFG => {}
326 // Also dump the inference graph constraints as a graphviz file.
327 let _: io::Result<()> = try {
329 pretty::create_dump_file(infcx.tcx, "regioncx.all.dot", None, "nll", &0, source)?;
330 regioncx.dump_graphviz_raw_constraints(&mut file)?;
333 // Also dump the inference graph constraints as a graphviz file.
334 let _: io::Result<()> = try {
336 pretty::create_dump_file(infcx.tcx, "regioncx.scc.dot", None, "nll", &0, source)?;
337 regioncx.dump_graphviz_scc_constraints(&mut file)?;
341 pub(super) fn dump_annotation<'a, 'tcx>(
342 infcx: &InferCtxt<'a, 'tcx>,
345 regioncx: &RegionInferenceContext<'tcx>,
346 closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
347 errors_buffer: &mut Vec<Diagnostic>,
350 let base_def_id = tcx.closure_base_def_id(mir_def_id);
351 if !tcx.has_attr(base_def_id, sym::rustc_regions) {
355 // When the enclosing function is tagged with `#[rustc_regions]`,
356 // we dump out various bits of state as warnings. This is useful
357 // for verifying that the compiler is behaving as expected. These
358 // warnings focus on the closure region requirements -- for
359 // viewing the intraprocedural state, the -Zdump-mir output is
362 if let Some(closure_region_requirements) = closure_region_requirements {
363 let mut err = tcx.sess.diagnostic().span_note_diag(body.span, "external requirements");
365 regioncx.annotate(tcx, &mut err);
368 "number of external vids: {}",
369 closure_region_requirements.num_external_vids
372 // Dump the region constraints we are imposing *between* those
373 // newly created variables.
374 for_each_region_constraint(closure_region_requirements, &mut |msg| {
380 err.buffer(errors_buffer);
382 let mut err = tcx.sess.diagnostic().span_note_diag(body.span, "no external requirements");
383 regioncx.annotate(tcx, &mut err);
385 err.buffer(errors_buffer);
389 fn for_each_region_constraint(
390 closure_region_requirements: &ClosureRegionRequirements<'_>,
391 with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
392 ) -> io::Result<()> {
393 for req in &closure_region_requirements.outlives_requirements {
394 let subject: &dyn Debug = match &req.subject {
395 ClosureOutlivesSubject::Region(subject) => subject,
396 ClosureOutlivesSubject::Ty(ty) => ty,
398 with_msg(&format!("where {:?}: {:?}", subject, req.outlived_free_region,))?;
403 /// Right now, we piggy back on the `ReVar` to store our NLL inference
404 /// regions. These are indexed with `RegionVid`. This method will
405 /// assert that the region is a `ReVar` and extract its internal index.
406 /// This is reasonable because in our MIR we replace all universal regions
407 /// with inference variables.
408 pub trait ToRegionVid {
409 fn to_region_vid(self) -> RegionVid;
412 impl<'tcx> ToRegionVid for &'tcx RegionKind {
413 fn to_region_vid(self) -> RegionVid {
414 if let ty::ReVar(vid) = self { *vid } else { bug!("region is not an ReVar: {:?}", self) }
418 impl ToRegionVid for RegionVid {
419 fn to_region_vid(self) -> RegionVid {
424 crate trait ConstraintDescription {
425 fn description(&self) -> &'static str;