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::MoveData;
8 use crate::dataflow::FlowAtLocation;
9 use crate::dataflow::MaybeInitializedPlaces;
10 use crate::transform::MirSource;
11 use rustc::hir::def_id::DefId;
12 use rustc::infer::InferCtxt;
13 use rustc::mir::{ClosureOutlivesSubject, ClosureRegionRequirements, Mir};
14 use rustc::ty::{self, RegionKind, RegionVid};
15 use rustc_errors::Diagnostic;
19 use std::path::PathBuf;
21 use std::str::FromStr;
23 use self::mir_util::PassWhere;
24 use polonius_engine::{Algorithm, Output};
25 use crate::util as mir_util;
26 use crate::util::pretty;
28 mod constraint_generation;
29 pub mod explain_borrow;
32 crate mod region_infer;
35 mod universal_regions;
39 use self::facts::AllFacts;
40 use self::region_infer::RegionInferenceContext;
41 use self::universal_regions::UniversalRegions;
43 /// Rewrites the regions in the MIR to use NLL variables, also
44 /// scraping out the set of universal regions (e.g., region parameters)
45 /// declared on the function. That set will need to be given to
46 /// `compute_regions`.
47 pub(in crate::borrow_check) fn replace_regions_in_mir<'cx, 'gcx, 'tcx>(
48 infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
50 param_env: ty::ParamEnv<'tcx>,
52 ) -> UniversalRegions<'tcx> {
53 debug!("replace_regions_in_mir(def_id={:?})", def_id);
55 // Compute named region information. This also renumbers the inputs/outputs.
56 let universal_regions = UniversalRegions::new(infcx, def_id, param_env);
58 // Replace all remaining regions with fresh inference variables.
59 renumber::renumber_mir(infcx, mir);
61 let source = MirSource::item(def_id);
62 mir_util::dump_mir(infcx.tcx, None, "renumber", &0, source, mir, |_, _| Ok(()));
67 /// Computes the (non-lexical) regions from the input MIR.
69 /// This may result in errors being reported.
70 pub(in crate::borrow_check) fn compute_regions<'cx, 'gcx, 'tcx>(
71 infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
73 universal_regions: UniversalRegions<'tcx>,
75 location_table: &LocationTable,
76 param_env: ty::ParamEnv<'gcx>,
77 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'cx, 'gcx, 'tcx>>,
78 move_data: &MoveData<'tcx>,
79 borrow_set: &BorrowSet<'tcx>,
80 errors_buffer: &mut Vec<Diagnostic>,
82 RegionInferenceContext<'tcx>,
83 Option<Rc<Output<RegionVid, BorrowIndex, LocationIndex>>>,
84 Option<ClosureRegionRequirements<'gcx>>,
86 let mut all_facts = if AllFacts::enabled(infcx.tcx) {
87 Some(AllFacts::default())
92 let universal_regions = Rc::new(universal_regions);
94 let elements = &Rc::new(RegionValueElements::new(mir));
96 // Run the MIR type-checker.
97 let MirTypeckResults {
99 universal_region_relations,
100 } = type_check::type_check(
114 if let Some(all_facts) = &mut all_facts {
117 .extend(universal_regions.universal_regions());
120 // Create the region inference context, taking ownership of the
121 // region inference data that was contained in `infcx`, and the
122 // base constraints generated by the type-check.
123 let var_origins = infcx.take_region_var_origins();
124 let MirTypeckRegionConstraints {
126 placeholder_index_to_region: _,
127 mut liveness_constraints,
128 outlives_constraints,
129 closure_bounds_mapping,
132 let placeholder_indices = Rc::new(placeholder_indices);
134 constraint_generation::generate_constraints(
136 &mut liveness_constraints,
143 let mut regioncx = RegionInferenceContext::new(
147 universal_region_relations,
149 outlives_constraints,
150 closure_bounds_mapping,
152 liveness_constraints,
156 // Generate various additional constraints.
157 invalidation::generate_invalidates(
165 // Dump facts if requested.
166 let polonius_output = all_facts.and_then(|all_facts| {
167 if infcx.tcx.sess.opts.debugging_opts.nll_facts {
168 let def_path = infcx.tcx.hir().def_path(def_id);
170 PathBuf::from("nll-facts").join(def_path.to_filename_friendly_no_crate());
171 all_facts.write_to_dir(dir_path, location_table).unwrap();
174 if infcx.tcx.sess.opts.debugging_opts.polonius {
175 let algorithm = env::var("POLONIUS_ALGORITHM")
176 .unwrap_or_else(|_| String::from("Hybrid"));
177 let algorithm = Algorithm::from_str(&algorithm).unwrap();
178 debug!("compute_regions: using polonius algorithm {:?}", algorithm);
179 Some(Rc::new(Output::compute(
189 // Solve the region constraints.
190 let closure_region_requirements = regioncx.solve(infcx, &mir, def_id, errors_buffer);
192 // Dump MIR results into a file, if that is enabled. This let us
193 // write unit-tests, as well as helping with debugging.
196 MirSource::item(def_id),
199 &closure_region_requirements,
202 // We also have a `#[rustc_nll]` annotation that causes us to dump
204 dump_annotation(infcx, &mir, def_id, ®ioncx, &closure_region_requirements, errors_buffer);
206 (regioncx, polonius_output, closure_region_requirements)
209 fn dump_mir_results<'a, 'gcx, 'tcx>(
210 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
211 source: MirSource<'tcx>,
213 regioncx: &RegionInferenceContext<'_>,
214 closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
216 if !mir_util::dump_enabled(infcx.tcx, "nll", source) {
229 // Before the CFG, dump out the values for each region variable.
230 PassWhere::BeforeCFG => {
231 regioncx.dump_mir(out)?;
234 if let Some(closure_region_requirements) = closure_region_requirements {
235 writeln!(out, "| Free Region Constraints")?;
236 for_each_region_constraint(closure_region_requirements, &mut |msg| {
237 writeln!(out, "| {}", msg)
243 PassWhere::BeforeLocation(_) => {
246 PassWhere::AfterTerminator(_) => {
249 PassWhere::BeforeBlock(_) | PassWhere::AfterLocation(_) | PassWhere::AfterCFG => {}
255 // Also dump the inference graph constraints as a graphviz file.
256 let _: io::Result<()> = try {
258 pretty::create_dump_file(infcx.tcx, "regioncx.all.dot", None, "nll", &0, source)?;
259 regioncx.dump_graphviz_raw_constraints(&mut file)?;
262 // Also dump the inference graph constraints as a graphviz file.
263 let _: io::Result<()> = try {
265 pretty::create_dump_file(infcx.tcx, "regioncx.scc.dot", None, "nll", &0, source)?;
266 regioncx.dump_graphviz_scc_constraints(&mut file)?;
270 fn dump_annotation<'a, 'gcx, 'tcx>(
271 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
274 regioncx: &RegionInferenceContext<'tcx>,
275 closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
276 errors_buffer: &mut Vec<Diagnostic>,
279 let base_def_id = tcx.closure_base_def_id(mir_def_id);
280 if !tcx.has_attr(base_def_id, "rustc_regions") {
284 // When the enclosing function is tagged with `#[rustc_regions]`,
285 // we dump out various bits of state as warnings. This is useful
286 // for verifying that the compiler is behaving as expected. These
287 // warnings focus on the closure region requirements -- for
288 // viewing the intraprocedural state, the -Zdump-mir output is
291 if let Some(closure_region_requirements) = closure_region_requirements {
295 .span_note_diag(mir.span, "External requirements");
297 regioncx.annotate(tcx, &mut err);
300 "number of external vids: {}",
301 closure_region_requirements.num_external_vids
304 // Dump the region constraints we are imposing *between* those
305 // newly created variables.
306 for_each_region_constraint(closure_region_requirements, &mut |msg| {
311 err.buffer(errors_buffer);
316 .span_note_diag(mir.span, "No external requirements");
317 regioncx.annotate(tcx, &mut err);
319 err.buffer(errors_buffer);
323 fn for_each_region_constraint(
324 closure_region_requirements: &ClosureRegionRequirements<'_>,
325 with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
326 ) -> io::Result<()> {
327 for req in &closure_region_requirements.outlives_requirements {
328 let subject: &dyn Debug = match &req.subject {
329 ClosureOutlivesSubject::Region(subject) => subject,
330 ClosureOutlivesSubject::Ty(ty) => ty,
334 subject, req.outlived_free_region,
340 /// Right now, we piggy back on the `ReVar` to store our NLL inference
341 /// regions. These are indexed with `RegionVid`. This method will
342 /// assert that the region is a `ReVar` and extract its internal index.
343 /// This is reasonable because in our MIR we replace all universal regions
344 /// with inference variables.
345 pub trait ToRegionVid {
346 fn to_region_vid(self) -> RegionVid;
349 impl<'tcx> ToRegionVid for &'tcx RegionKind {
350 fn to_region_vid(self) -> RegionVid {
351 if let ty::ReVar(vid) = self {
354 bug!("region is not an ReVar: {:?}", self)
359 impl ToRegionVid for RegionVid {
360 fn to_region_vid(self) -> RegionVid {
365 crate trait ConstraintDescription {
366 fn description(&self) -> &'static str;