1 use crate::borrow_check::borrow_set::BorrowSet;
2 use crate::borrow_check::location::{LocationIndex, LocationTable};
3 use crate::borrow_check::nll::facts::AllFactsExt;
4 use crate::borrow_check::nll::type_check::{MirTypeckResults, MirTypeckRegionConstraints};
5 use crate::borrow_check::nll::region_infer::values::RegionValueElements;
6 use crate::dataflow::indexes::BorrowIndex;
7 use crate::dataflow::move_paths::{InitLocation, MoveData, MovePathIndex, InitKind};
8 use crate::dataflow::FlowAtLocation;
9 use crate::dataflow::MaybeInitializedPlaces;
10 use crate::transform::MirSource;
11 use crate::borrow_check::Upvar;
12 use rustc::hir::def_id::DefId;
13 use rustc::infer::InferCtxt;
14 use rustc::mir::{ClosureOutlivesSubject, ClosureRegionRequirements,
15 Local, Location, Body, BodyCache, LocalKind, BasicBlock,
16 Promoted, ReadOnlyBodyCache};
17 use rustc::ty::{self, RegionKind, RegionVid};
18 use rustc_index::vec::IndexVec;
19 use rustc_errors::Diagnostic;
20 use syntax_pos::symbol::Symbol;
24 use std::path::PathBuf;
26 use std::str::FromStr;
27 use syntax::symbol::sym;
29 use self::mir_util::PassWhere;
30 use polonius_engine::{Algorithm, Output};
31 use crate::util as mir_util;
32 use crate::util::pretty;
34 mod constraint_generation;
39 mod member_constraints;
41 crate mod constraints;
42 crate mod universal_regions;
44 crate mod region_infer;
46 use self::facts::AllFacts;
47 use self::region_infer::RegionInferenceContext;
48 use self::universal_regions::UniversalRegions;
50 /// Rewrites the regions in the MIR to use NLL variables, also
51 /// scraping out the set of universal regions (e.g., region parameters)
52 /// declared on the function. That set will need to be given to
53 /// `compute_regions`.
54 pub(in crate::borrow_check) fn replace_regions_in_mir<'cx, 'tcx>(
55 infcx: &InferCtxt<'cx, 'tcx>,
57 param_env: ty::ParamEnv<'tcx>,
58 body: &mut BodyCache<'tcx>,
59 promoted: &mut IndexVec<Promoted, BodyCache<'tcx>>,
60 ) -> UniversalRegions<'tcx> {
61 debug!("replace_regions_in_mir(def_id={:?})", def_id);
63 // Compute named region information. This also renumbers the inputs/outputs.
64 let universal_regions = UniversalRegions::new(infcx, def_id, param_env);
66 // Replace all remaining regions with fresh inference variables.
67 renumber::renumber_mir(infcx, body, promoted);
69 let source = MirSource::item(def_id);
70 mir_util::dump_mir(infcx.tcx, None, "renumber", &0, source, body, |_, _| Ok(()));
76 // This function populates an AllFacts instance with base facts related to
77 // MovePaths and needed for the move analysis.
78 fn populate_polonius_move_facts(
79 all_facts: &mut AllFacts,
80 move_data: &MoveData<'_>,
81 location_table: &LocationTable,
88 .iter_locals_enumerated()
89 .map(|(v, &m)| (m, v)));
91 for (child, move_path) in move_data.move_paths.iter_enumerated() {
96 .parents(&move_data.move_paths)
98 .map(|&parent| (child, parent)));
102 for init in move_data.inits.iter() {
104 match init.location {
105 InitLocation::Statement(location) => {
106 let block_data = &body[location.block];
107 let is_terminator = location.statement_index == block_data.statements.len();
109 if is_terminator && init.kind == InitKind::NonPanicPathOnly {
110 // We are at the terminator of an init that has a panic path,
111 // and where the init should not happen on panic
113 for &successor in block_data.terminator().successors() {
114 if body[successor].is_cleanup {
118 // The initialization happened in (or rather, when arriving at)
119 // the successors, but not in the unwind block.
120 let first_statement = Location { block: successor, statement_index: 0};
123 .push((init.path, location_table.start_index(first_statement)));
127 // In all other cases, the initialization just happens at the
128 // midpoint, like any other effect.
129 all_facts.initialized_at.push((init.path, location_table.mid_index(location)));
132 // Arguments are initialized on function entry
133 InitLocation::Argument(local) => {
134 assert!(body.local_kind(local) == LocalKind::Arg);
135 let fn_entry = Location {block: BasicBlock::from_u32(0u32), statement_index: 0 };
136 all_facts.initialized_at.push((init.path, location_table.start_index(fn_entry)));
144 // deinitialisation is assumed to always happen!
151 .map(|mo| (mo.path, location_table.mid_index(mo.source))));
154 /// Computes the (non-lexical) regions from the input MIR.
156 /// This may result in errors being reported.
157 pub(in crate::borrow_check) fn compute_regions<'cx, 'tcx>(
158 infcx: &InferCtxt<'cx, 'tcx>,
160 universal_regions: UniversalRegions<'tcx>,
161 body: ReadOnlyBodyCache<'_, 'tcx>,
162 promoted: &IndexVec<Promoted, ReadOnlyBodyCache<'_, 'tcx>>,
163 local_names: &IndexVec<Local, Option<Symbol>>,
165 location_table: &LocationTable,
166 param_env: ty::ParamEnv<'tcx>,
167 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'cx, 'tcx>>,
168 move_data: &MoveData<'tcx>,
169 borrow_set: &BorrowSet<'tcx>,
170 errors_buffer: &mut Vec<Diagnostic>,
172 RegionInferenceContext<'tcx>,
173 Option<Rc<Output<RegionVid, BorrowIndex, LocationIndex, Local, MovePathIndex>>>,
174 Option<ClosureRegionRequirements<'tcx>>,
176 let mut all_facts = AllFacts::enabled(infcx.tcx).then_some(AllFacts::default());
178 let universal_regions = Rc::new(universal_regions);
181 = &Rc::new(RegionValueElements::new(&body));
183 // Run the MIR type-checker.
184 let MirTypeckResults {
186 universal_region_relations,
187 } = type_check::type_check(
202 if let Some(all_facts) = &mut all_facts {
205 .extend(universal_regions.universal_regions());
206 populate_polonius_move_facts(all_facts, move_data, location_table, &body);
209 // Create the region inference context, taking ownership of the
210 // region inference data that was contained in `infcx`, and the
211 // base constraints generated by the type-check.
212 let var_origins = infcx.take_region_var_origins();
213 let MirTypeckRegionConstraints {
215 placeholder_index_to_region: _,
216 mut liveness_constraints,
217 outlives_constraints,
219 closure_bounds_mapping,
222 let placeholder_indices = Rc::new(placeholder_indices);
224 constraint_generation::generate_constraints(
227 &mut liveness_constraints,
234 let mut regioncx = RegionInferenceContext::new(
238 universal_region_relations,
239 outlives_constraints,
241 closure_bounds_mapping,
243 liveness_constraints,
247 // Generate various additional constraints.
248 invalidation::generate_invalidates(
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 {
267 let algorithm = env::var("POLONIUS_ALGORITHM")
268 .unwrap_or_else(|_| String::from("Hybrid"));
269 let algorithm = Algorithm::from_str(&algorithm).unwrap();
270 debug!("compute_regions: using polonius algorithm {:?}", algorithm);
271 Some(Rc::new(Output::compute(
281 // Solve the region constraints.
282 let closure_region_requirements =
283 regioncx.solve(infcx, &body, local_names, upvars, def_id, errors_buffer);
285 // Dump MIR results into a file, if that is enabled. This let us
286 // write unit-tests, as well as helping with debugging.
289 MirSource::item(def_id),
292 &closure_region_requirements,
295 // We also have a `#[rustc_nll]` annotation that causes us to dump
302 &closure_region_requirements,
305 (regioncx, polonius_output, closure_region_requirements)
308 fn dump_mir_results<'a, 'tcx>(
309 infcx: &InferCtxt<'a, 'tcx>,
310 source: MirSource<'tcx>,
312 regioncx: &RegionInferenceContext<'_>,
313 closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
315 if !mir_util::dump_enabled(infcx.tcx, "nll", source) {
328 // Before the CFG, dump out the values for each region variable.
329 PassWhere::BeforeCFG => {
330 regioncx.dump_mir(out)?;
333 if let Some(closure_region_requirements) = closure_region_requirements {
334 writeln!(out, "| Free Region Constraints")?;
335 for_each_region_constraint(closure_region_requirements, &mut |msg| {
336 writeln!(out, "| {}", msg)
342 PassWhere::BeforeLocation(_) => {
345 PassWhere::AfterTerminator(_) => {
348 PassWhere::BeforeBlock(_) | PassWhere::AfterLocation(_) | PassWhere::AfterCFG => {}
354 // Also dump the inference graph constraints as a graphviz file.
355 let _: io::Result<()> = try {
357 pretty::create_dump_file(infcx.tcx, "regioncx.all.dot", None, "nll", &0, source)?;
358 regioncx.dump_graphviz_raw_constraints(&mut file)?;
361 // Also dump the inference graph constraints as a graphviz file.
362 let _: io::Result<()> = try {
364 pretty::create_dump_file(infcx.tcx, "regioncx.scc.dot", None, "nll", &0, source)?;
365 regioncx.dump_graphviz_scc_constraints(&mut file)?;
369 fn dump_annotation<'a, 'tcx>(
370 infcx: &InferCtxt<'a, 'tcx>,
373 regioncx: &RegionInferenceContext<'tcx>,
374 closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
375 errors_buffer: &mut Vec<Diagnostic>,
378 let base_def_id = tcx.closure_base_def_id(mir_def_id);
379 if !tcx.has_attr(base_def_id, sym::rustc_regions) {
383 // When the enclosing function is tagged with `#[rustc_regions]`,
384 // we dump out various bits of state as warnings. This is useful
385 // for verifying that the compiler is behaving as expected. These
386 // warnings focus on the closure region requirements -- for
387 // viewing the intraprocedural state, the -Zdump-mir output is
390 if let Some(closure_region_requirements) = closure_region_requirements {
394 .span_note_diag(body.span, "External requirements");
396 regioncx.annotate(tcx, &mut err);
399 "number of external vids: {}",
400 closure_region_requirements.num_external_vids
403 // Dump the region constraints we are imposing *between* those
404 // newly created variables.
405 for_each_region_constraint(closure_region_requirements, &mut |msg| {
410 err.buffer(errors_buffer);
415 .span_note_diag(body.span, "No external requirements");
416 regioncx.annotate(tcx, &mut err);
418 err.buffer(errors_buffer);
422 fn for_each_region_constraint(
423 closure_region_requirements: &ClosureRegionRequirements<'_>,
424 with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
425 ) -> io::Result<()> {
426 for req in &closure_region_requirements.outlives_requirements {
427 let subject: &dyn Debug = match &req.subject {
428 ClosureOutlivesSubject::Region(subject) => subject,
429 ClosureOutlivesSubject::Ty(ty) => ty,
433 subject, req.outlived_free_region,
439 /// Right now, we piggy back on the `ReVar` to store our NLL inference
440 /// regions. These are indexed with `RegionVid`. This method will
441 /// assert that the region is a `ReVar` and extract its internal index.
442 /// This is reasonable because in our MIR we replace all universal regions
443 /// with inference variables.
444 pub trait ToRegionVid {
445 fn to_region_vid(self) -> RegionVid;
448 impl<'tcx> ToRegionVid for &'tcx RegionKind {
449 fn to_region_vid(self) -> RegionVid {
450 if let ty::ReVar(vid) = self {
453 bug!("region is not an ReVar: {:?}", self)
458 impl ToRegionVid for RegionVid {
459 fn to_region_vid(self) -> RegionVid {
464 crate trait ConstraintDescription {
465 fn description(&self) -> &'static str;