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 crate::borrow_check::Upvar;
12 use rustc::hir::def_id::DefId;
13 use rustc::infer::InferCtxt;
14 use rustc::mir::{ClosureOutlivesSubject, ClosureRegionRequirements, Mir};
15 use rustc::ty::{self, RegionKind, RegionVid};
16 use rustc_errors::Diagnostic;
20 use std::path::PathBuf;
22 use std::str::FromStr;
23 use syntax::symbol::sym;
25 use self::mir_util::PassWhere;
26 use polonius_engine::{Algorithm, Output};
27 use crate::util as mir_util;
28 use crate::util::pretty;
30 mod constraint_generation;
31 pub mod explain_borrow;
34 crate mod region_infer;
37 mod universal_regions;
41 use self::facts::AllFacts;
42 use self::region_infer::RegionInferenceContext;
43 use self::universal_regions::UniversalRegions;
45 /// Rewrites the regions in the MIR to use NLL variables, also
46 /// scraping out the set of universal regions (e.g., region parameters)
47 /// declared on the function. That set will need to be given to
48 /// `compute_regions`.
49 pub(in crate::borrow_check) fn replace_regions_in_mir<'cx, 'gcx, 'tcx>(
50 infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
52 param_env: ty::ParamEnv<'tcx>,
54 ) -> UniversalRegions<'tcx> {
55 debug!("replace_regions_in_mir(def_id={:?})", def_id);
57 // Compute named region information. This also renumbers the inputs/outputs.
58 let universal_regions = UniversalRegions::new(infcx, def_id, param_env);
60 // Replace all remaining regions with fresh inference variables.
61 renumber::renumber_mir(infcx, mir);
63 let source = MirSource::item(def_id);
64 mir_util::dump_mir(infcx.tcx, None, "renumber", &0, source, mir, |_, _| Ok(()));
69 /// Computes the (non-lexical) regions from the input MIR.
71 /// This may result in errors being reported.
72 pub(in crate::borrow_check) fn compute_regions<'cx, 'gcx, 'tcx>(
73 infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
75 universal_regions: UniversalRegions<'tcx>,
78 location_table: &LocationTable,
79 param_env: ty::ParamEnv<'gcx>,
80 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'cx, 'gcx, 'tcx>>,
81 move_data: &MoveData<'tcx>,
82 borrow_set: &BorrowSet<'tcx>,
83 errors_buffer: &mut Vec<Diagnostic>,
85 RegionInferenceContext<'tcx>,
86 Option<Rc<Output<RegionVid, BorrowIndex, LocationIndex>>>,
87 Option<ClosureRegionRequirements<'gcx>>,
89 let mut all_facts = if AllFacts::enabled(infcx.tcx) {
90 Some(AllFacts::default())
95 let universal_regions = Rc::new(universal_regions);
97 let elements = &Rc::new(RegionValueElements::new(mir));
99 // Run the MIR type-checker.
100 let MirTypeckResults {
102 universal_region_relations,
103 } = type_check::type_check(
117 if let Some(all_facts) = &mut all_facts {
120 .extend(universal_regions.universal_regions());
123 // Create the region inference context, taking ownership of the
124 // region inference data that was contained in `infcx`, and the
125 // base constraints generated by the type-check.
126 let var_origins = infcx.take_region_var_origins();
127 let MirTypeckRegionConstraints {
129 placeholder_index_to_region: _,
130 mut liveness_constraints,
131 outlives_constraints,
132 closure_bounds_mapping,
135 let placeholder_indices = Rc::new(placeholder_indices);
137 constraint_generation::generate_constraints(
139 &mut liveness_constraints,
146 let mut regioncx = RegionInferenceContext::new(
150 universal_region_relations,
152 outlives_constraints,
153 closure_bounds_mapping,
155 liveness_constraints,
159 // Generate various additional constraints.
160 invalidation::generate_invalidates(
168 // Dump facts if requested.
169 let polonius_output = all_facts.and_then(|all_facts| {
170 if infcx.tcx.sess.opts.debugging_opts.nll_facts {
171 let def_path = infcx.tcx.hir().def_path(def_id);
173 PathBuf::from("nll-facts").join(def_path.to_filename_friendly_no_crate());
174 all_facts.write_to_dir(dir_path, location_table).unwrap();
177 if infcx.tcx.sess.opts.debugging_opts.polonius {
178 let algorithm = env::var("POLONIUS_ALGORITHM")
179 .unwrap_or_else(|_| String::from("Hybrid"));
180 let algorithm = Algorithm::from_str(&algorithm).unwrap();
181 debug!("compute_regions: using polonius algorithm {:?}", algorithm);
182 Some(Rc::new(Output::compute(
192 // Solve the region constraints.
193 let closure_region_requirements =
194 regioncx.solve(infcx, &mir, upvars, def_id, errors_buffer);
196 // Dump MIR results into a file, if that is enabled. This let us
197 // write unit-tests, as well as helping with debugging.
200 MirSource::item(def_id),
203 &closure_region_requirements,
206 // We also have a `#[rustc_nll]` annotation that causes us to dump
208 dump_annotation(infcx, &mir, def_id, ®ioncx, &closure_region_requirements, errors_buffer);
210 (regioncx, polonius_output, closure_region_requirements)
213 fn dump_mir_results<'a, 'gcx, 'tcx>(
214 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
215 source: MirSource<'tcx>,
217 regioncx: &RegionInferenceContext<'_>,
218 closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
220 if !mir_util::dump_enabled(infcx.tcx, "nll", source) {
233 // Before the CFG, dump out the values for each region variable.
234 PassWhere::BeforeCFG => {
235 regioncx.dump_mir(out)?;
238 if let Some(closure_region_requirements) = closure_region_requirements {
239 writeln!(out, "| Free Region Constraints")?;
240 for_each_region_constraint(closure_region_requirements, &mut |msg| {
241 writeln!(out, "| {}", msg)
247 PassWhere::BeforeLocation(_) => {
250 PassWhere::AfterTerminator(_) => {
253 PassWhere::BeforeBlock(_) | PassWhere::AfterLocation(_) | PassWhere::AfterCFG => {}
259 // Also dump the inference graph constraints as a graphviz file.
260 let _: io::Result<()> = try {
262 pretty::create_dump_file(infcx.tcx, "regioncx.all.dot", None, "nll", &0, source)?;
263 regioncx.dump_graphviz_raw_constraints(&mut file)?;
266 // Also dump the inference graph constraints as a graphviz file.
267 let _: io::Result<()> = try {
269 pretty::create_dump_file(infcx.tcx, "regioncx.scc.dot", None, "nll", &0, source)?;
270 regioncx.dump_graphviz_scc_constraints(&mut file)?;
274 fn dump_annotation<'a, 'gcx, 'tcx>(
275 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
278 regioncx: &RegionInferenceContext<'tcx>,
279 closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
280 errors_buffer: &mut Vec<Diagnostic>,
283 let base_def_id = tcx.closure_base_def_id(mir_def_id);
284 if !tcx.has_attr(base_def_id, sym::rustc_regions) {
288 // When the enclosing function is tagged with `#[rustc_regions]`,
289 // we dump out various bits of state as warnings. This is useful
290 // for verifying that the compiler is behaving as expected. These
291 // warnings focus on the closure region requirements -- for
292 // viewing the intraprocedural state, the -Zdump-mir output is
295 if let Some(closure_region_requirements) = closure_region_requirements {
299 .span_note_diag(mir.span, "External requirements");
301 regioncx.annotate(tcx, &mut err);
304 "number of external vids: {}",
305 closure_region_requirements.num_external_vids
308 // Dump the region constraints we are imposing *between* those
309 // newly created variables.
310 for_each_region_constraint(closure_region_requirements, &mut |msg| {
315 err.buffer(errors_buffer);
320 .span_note_diag(mir.span, "No external requirements");
321 regioncx.annotate(tcx, &mut err);
323 err.buffer(errors_buffer);
327 fn for_each_region_constraint(
328 closure_region_requirements: &ClosureRegionRequirements<'_>,
329 with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
330 ) -> io::Result<()> {
331 for req in &closure_region_requirements.outlives_requirements {
332 let subject: &dyn Debug = match &req.subject {
333 ClosureOutlivesSubject::Region(subject) => subject,
334 ClosureOutlivesSubject::Ty(ty) => ty,
338 subject, req.outlived_free_region,
344 /// Right now, we piggy back on the `ReVar` to store our NLL inference
345 /// regions. These are indexed with `RegionVid`. This method will
346 /// assert that the region is a `ReVar` and extract its internal index.
347 /// This is reasonable because in our MIR we replace all universal regions
348 /// with inference variables.
349 pub trait ToRegionVid {
350 fn to_region_vid(self) -> RegionVid;
353 impl<'tcx> ToRegionVid for &'tcx RegionKind {
354 fn to_region_vid(self) -> RegionVid {
355 if let ty::ReVar(vid) = self {
358 bug!("region is not an ReVar: {:?}", self)
363 impl ToRegionVid for RegionVid {
364 fn to_region_vid(self) -> RegionVid {
369 crate trait ConstraintDescription {
370 fn description(&self) -> &'static str;