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;
24 use self::mir_util::PassWhere;
25 use polonius_engine::{Algorithm, Output};
26 use crate::util as mir_util;
27 use crate::util::pretty;
29 mod constraint_generation;
30 pub mod explain_borrow;
33 crate mod region_infer;
36 mod universal_regions;
40 use self::facts::AllFacts;
41 use self::region_infer::RegionInferenceContext;
42 use self::universal_regions::UniversalRegions;
44 /// Rewrites the regions in the MIR to use NLL variables, also
45 /// scraping out the set of universal regions (e.g., region parameters)
46 /// declared on the function. That set will need to be given to
47 /// `compute_regions`.
48 pub(in crate::borrow_check) fn replace_regions_in_mir<'cx, 'gcx, 'tcx>(
49 infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
51 param_env: ty::ParamEnv<'tcx>,
53 ) -> UniversalRegions<'tcx> {
54 debug!("replace_regions_in_mir(def_id={:?})", def_id);
56 // Compute named region information. This also renumbers the inputs/outputs.
57 let universal_regions = UniversalRegions::new(infcx, def_id, param_env);
59 // Replace all remaining regions with fresh inference variables.
60 renumber::renumber_mir(infcx, mir);
62 let source = MirSource::item(def_id);
63 mir_util::dump_mir(infcx.tcx, None, "renumber", &0, source, mir, |_, _| Ok(()));
68 /// Computes the (non-lexical) regions from the input MIR.
70 /// This may result in errors being reported.
71 pub(in crate::borrow_check) fn compute_regions<'cx, 'gcx, 'tcx>(
72 infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
74 universal_regions: UniversalRegions<'tcx>,
77 location_table: &LocationTable,
78 param_env: ty::ParamEnv<'gcx>,
79 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'cx, 'gcx, 'tcx>>,
80 move_data: &MoveData<'tcx>,
81 borrow_set: &BorrowSet<'tcx>,
82 errors_buffer: &mut Vec<Diagnostic>,
84 RegionInferenceContext<'tcx>,
85 Option<Rc<Output<RegionVid, BorrowIndex, LocationIndex>>>,
86 Option<ClosureRegionRequirements<'gcx>>,
88 let mut all_facts = if AllFacts::enabled(infcx.tcx) {
89 Some(AllFacts::default())
94 let universal_regions = Rc::new(universal_regions);
96 let elements = &Rc::new(RegionValueElements::new(mir));
98 // Run the MIR type-checker.
99 let MirTypeckResults {
101 universal_region_relations,
102 } = type_check::type_check(
116 if let Some(all_facts) = &mut all_facts {
119 .extend(universal_regions.universal_regions());
122 // Create the region inference context, taking ownership of the
123 // region inference data that was contained in `infcx`, and the
124 // base constraints generated by the type-check.
125 let var_origins = infcx.take_region_var_origins();
126 let MirTypeckRegionConstraints {
128 placeholder_index_to_region: _,
129 mut liveness_constraints,
130 outlives_constraints,
131 closure_bounds_mapping,
134 let placeholder_indices = Rc::new(placeholder_indices);
136 constraint_generation::generate_constraints(
138 &mut liveness_constraints,
145 let mut regioncx = RegionInferenceContext::new(
149 universal_region_relations,
151 outlives_constraints,
152 closure_bounds_mapping,
154 liveness_constraints,
158 // Generate various additional constraints.
159 invalidation::generate_invalidates(
167 // Dump facts if requested.
168 let polonius_output = all_facts.and_then(|all_facts| {
169 if infcx.tcx.sess.opts.debugging_opts.nll_facts {
170 let def_path = infcx.tcx.hir().def_path(def_id);
172 PathBuf::from("nll-facts").join(def_path.to_filename_friendly_no_crate());
173 all_facts.write_to_dir(dir_path, location_table).unwrap();
176 if infcx.tcx.sess.opts.debugging_opts.polonius {
177 let algorithm = env::var("POLONIUS_ALGORITHM")
178 .unwrap_or_else(|_| String::from("Hybrid"));
179 let algorithm = Algorithm::from_str(&algorithm).unwrap();
180 debug!("compute_regions: using polonius algorithm {:?}", algorithm);
181 Some(Rc::new(Output::compute(
191 // Solve the region constraints.
192 let closure_region_requirements =
193 regioncx.solve(infcx, &mir, upvars, def_id, errors_buffer);
195 // Dump MIR results into a file, if that is enabled. This let us
196 // write unit-tests, as well as helping with debugging.
199 MirSource::item(def_id),
202 &closure_region_requirements,
205 // We also have a `#[rustc_nll]` annotation that causes us to dump
207 dump_annotation(infcx, &mir, def_id, ®ioncx, &closure_region_requirements, errors_buffer);
209 (regioncx, polonius_output, closure_region_requirements)
212 fn dump_mir_results<'a, 'gcx, 'tcx>(
213 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
214 source: MirSource<'tcx>,
216 regioncx: &RegionInferenceContext<'_>,
217 closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
219 if !mir_util::dump_enabled(infcx.tcx, "nll", source) {
232 // Before the CFG, dump out the values for each region variable.
233 PassWhere::BeforeCFG => {
234 regioncx.dump_mir(out)?;
237 if let Some(closure_region_requirements) = closure_region_requirements {
238 writeln!(out, "| Free Region Constraints")?;
239 for_each_region_constraint(closure_region_requirements, &mut |msg| {
240 writeln!(out, "| {}", msg)
246 PassWhere::BeforeLocation(_) => {
249 PassWhere::AfterTerminator(_) => {
252 PassWhere::BeforeBlock(_) | PassWhere::AfterLocation(_) | PassWhere::AfterCFG => {}
258 // Also dump the inference graph constraints as a graphviz file.
259 let _: io::Result<()> = try {
261 pretty::create_dump_file(infcx.tcx, "regioncx.all.dot", None, "nll", &0, source)?;
262 regioncx.dump_graphviz_raw_constraints(&mut file)?;
265 // Also dump the inference graph constraints as a graphviz file.
266 let _: io::Result<()> = try {
268 pretty::create_dump_file(infcx.tcx, "regioncx.scc.dot", None, "nll", &0, source)?;
269 regioncx.dump_graphviz_scc_constraints(&mut file)?;
273 fn dump_annotation<'a, 'gcx, 'tcx>(
274 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
277 regioncx: &RegionInferenceContext<'tcx>,
278 closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
279 errors_buffer: &mut Vec<Diagnostic>,
282 let base_def_id = tcx.closure_base_def_id(mir_def_id);
283 if !tcx.has_attr(base_def_id, "rustc_regions") {
287 // When the enclosing function is tagged with `#[rustc_regions]`,
288 // we dump out various bits of state as warnings. This is useful
289 // for verifying that the compiler is behaving as expected. These
290 // warnings focus on the closure region requirements -- for
291 // viewing the intraprocedural state, the -Zdump-mir output is
294 if let Some(closure_region_requirements) = closure_region_requirements {
298 .span_note_diag(mir.span, "External requirements");
300 regioncx.annotate(tcx, &mut err);
303 "number of external vids: {}",
304 closure_region_requirements.num_external_vids
307 // Dump the region constraints we are imposing *between* those
308 // newly created variables.
309 for_each_region_constraint(closure_region_requirements, &mut |msg| {
314 err.buffer(errors_buffer);
319 .span_note_diag(mir.span, "No external requirements");
320 regioncx.annotate(tcx, &mut err);
322 err.buffer(errors_buffer);
326 fn for_each_region_constraint(
327 closure_region_requirements: &ClosureRegionRequirements<'_>,
328 with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
329 ) -> io::Result<()> {
330 for req in &closure_region_requirements.outlives_requirements {
331 let subject: &dyn Debug = match &req.subject {
332 ClosureOutlivesSubject::Region(subject) => subject,
333 ClosureOutlivesSubject::Ty(ty) => ty,
337 subject, req.outlived_free_region,
343 /// Right now, we piggy back on the `ReVar` to store our NLL inference
344 /// regions. These are indexed with `RegionVid`. This method will
345 /// assert that the region is a `ReVar` and extract its internal index.
346 /// This is reasonable because in our MIR we replace all universal regions
347 /// with inference variables.
348 pub trait ToRegionVid {
349 fn to_region_vid(self) -> RegionVid;
352 impl<'tcx> ToRegionVid for &'tcx RegionKind {
353 fn to_region_vid(self) -> RegionVid {
354 if let ty::ReVar(vid) = self {
357 bug!("region is not an ReVar: {:?}", self)
362 impl ToRegionVid for RegionVid {
363 fn to_region_vid(self) -> RegionVid {
368 crate trait ConstraintDescription {
369 fn description(&self) -> &'static str;