1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use borrow_check::borrow_set::BorrowSet;
12 use borrow_check::location::{LocationIndex, LocationTable};
13 use borrow_check::nll::facts::AllFactsExt;
14 use borrow_check::nll::type_check::{MirTypeckResults, MirTypeckRegionConstraints};
15 use borrow_check::nll::type_check::liveness::liveness_map::{NllLivenessMap, LocalWithRegion};
16 use borrow_check::nll::region_infer::values::RegionValueElements;
17 use dataflow::indexes::BorrowIndex;
18 use dataflow::move_paths::MoveData;
19 use dataflow::FlowAtLocation;
20 use dataflow::MaybeInitializedPlaces;
21 use rustc::hir::def_id::DefId;
22 use rustc::infer::InferCtxt;
23 use rustc::mir::{ClosureOutlivesSubject, ClosureRegionRequirements, Mir};
24 use rustc::ty::{self, RegionKind, RegionVid};
25 use rustc::util::nodemap::FxHashMap;
26 use rustc_errors::Diagnostic;
27 use std::collections::BTreeSet;
31 use std::path::PathBuf;
33 use std::str::FromStr;
34 use transform::MirSource;
35 use util::liveness::{LivenessResults, LiveVarSet};
37 use self::mir_util::PassWhere;
38 use polonius_engine::{Algorithm, Output};
40 use util::pretty::{self, ALIGN};
42 mod constraint_generation;
43 pub mod explain_borrow;
46 crate mod region_infer;
49 mod universal_regions;
53 use self::facts::AllFacts;
54 use self::region_infer::RegionInferenceContext;
55 use self::universal_regions::UniversalRegions;
57 /// Rewrites the regions in the MIR to use NLL variables, also
58 /// scraping out the set of universal regions (e.g., region parameters)
59 /// declared on the function. That set will need to be given to
60 /// `compute_regions`.
61 pub(in borrow_check) fn replace_regions_in_mir<'cx, 'gcx, 'tcx>(
62 infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
64 param_env: ty::ParamEnv<'tcx>,
66 ) -> UniversalRegions<'tcx> {
67 debug!("replace_regions_in_mir(def_id={:?})", def_id);
69 // Compute named region information. This also renumbers the inputs/outputs.
70 let universal_regions = UniversalRegions::new(infcx, def_id, param_env);
72 // Replace all remaining regions with fresh inference variables.
73 renumber::renumber_mir(infcx, mir);
75 let source = MirSource::item(def_id);
76 mir_util::dump_mir(infcx.tcx, None, "renumber", &0, source, mir, |_, _| Ok(()));
81 /// Computes the (non-lexical) regions from the input MIR.
83 /// This may result in errors being reported.
84 pub(in borrow_check) fn compute_regions<'cx, 'gcx, 'tcx>(
85 infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
87 universal_regions: UniversalRegions<'tcx>,
89 location_table: &LocationTable,
90 param_env: ty::ParamEnv<'gcx>,
91 flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'cx, 'gcx, 'tcx>>,
92 move_data: &MoveData<'tcx>,
93 borrow_set: &BorrowSet<'tcx>,
94 errors_buffer: &mut Vec<Diagnostic>,
96 RegionInferenceContext<'tcx>,
97 Option<Rc<Output<RegionVid, BorrowIndex, LocationIndex>>>,
98 Option<ClosureRegionRequirements<'gcx>>,
100 let mut all_facts = if AllFacts::enabled(infcx.tcx) {
101 Some(AllFacts::default())
106 let universal_regions = Rc::new(universal_regions);
108 let elements = &Rc::new(RegionValueElements::new(mir));
110 // Run the MIR type-checker.
111 let MirTypeckResults {
113 universal_region_relations,
116 } = type_check::type_check(
131 if let Some(all_facts) = &mut all_facts {
134 .extend(universal_regions.universal_regions());
137 // Create the region inference context, taking ownership of the
138 // region inference data that was contained in `infcx`, and the
139 // base constraints generated by the type-check.
140 let var_origins = infcx.take_region_var_origins();
141 let MirTypeckRegionConstraints {
142 mut liveness_constraints,
143 outlives_constraints,
147 constraint_generation::generate_constraints(
149 &mut liveness_constraints,
156 let mut regioncx = RegionInferenceContext::new(
159 universal_region_relations,
161 outlives_constraints,
163 liveness_constraints,
167 // Generate various additional constraints.
168 invalidation::generate_invalidates(
177 // Dump facts if requested.
178 let polonius_output = all_facts.and_then(|all_facts| {
179 if infcx.tcx.sess.opts.debugging_opts.nll_facts {
180 let def_path = infcx.tcx.hir.def_path(def_id);
182 PathBuf::from("nll-facts").join(def_path.to_filename_friendly_no_crate());
183 all_facts.write_to_dir(dir_path, location_table).unwrap();
186 if infcx.tcx.sess.opts.debugging_opts.polonius {
187 let algorithm = env::var("POLONIUS_ALGORITHM")
188 .unwrap_or(String::from("DatafrogOpt"));
189 let algorithm = Algorithm::from_str(&algorithm).unwrap();
190 debug!("compute_regions: using polonius algorithm {:?}", algorithm);
191 Some(Rc::new(Output::compute(
201 // Solve the region constraints.
202 let closure_region_requirements = regioncx.solve(infcx, &mir, def_id, errors_buffer);
204 // Dump MIR results into a file, if that is enabled. This let us
205 // write unit-tests, as well as helping with debugging.
210 MirSource::item(def_id),
213 &closure_region_requirements,
216 // We also have a `#[rustc_nll]` annotation that causes us to dump
218 dump_annotation(infcx, &mir, def_id, ®ioncx, &closure_region_requirements, errors_buffer);
220 (regioncx, polonius_output, closure_region_requirements)
223 fn dump_mir_results<'a, 'gcx, 'tcx>(
224 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
225 liveness: &LivenessResults<LocalWithRegion>,
226 liveness_map: &NllLivenessMap,
229 regioncx: &RegionInferenceContext,
230 closure_region_requirements: &Option<ClosureRegionRequirements>,
232 if !mir_util::dump_enabled(infcx.tcx, "nll", source) {
236 let regular_liveness_per_location: FxHashMap<_, _> = mir
240 let mut results = vec![];
243 .simulate_block(&mir, bb, liveness_map, |location, local_set| {
244 results.push((location, local_set.clone()));
250 let drop_liveness_per_location: FxHashMap<_, _> = mir
254 let mut results = vec![];
257 .simulate_block(&mir, bb, liveness_map, |location, local_set| {
258 results.push((location, local_set.clone()));
273 // Before the CFG, dump out the values for each region variable.
274 PassWhere::BeforeCFG => {
275 regioncx.dump_mir(out)?;
277 if let Some(closure_region_requirements) = closure_region_requirements {
279 writeln!(out, "| Free Region Constraints")?;
280 for_each_region_constraint(closure_region_requirements, &mut |msg| {
281 writeln!(out, "| {}", msg)
286 PassWhere::BeforeLocation(location) => {
287 let s = live_variable_set(
288 ®ular_liveness_per_location[&location],
289 &drop_liveness_per_location[&location],
293 "{:ALIGN$} | Live variables on entry to {:?}: {}",
301 // After each basic block, dump out the values
302 // that are live on exit from the basic block.
303 PassWhere::AfterTerminator(bb) => {
304 let s = live_variable_set(&liveness.regular.outs[bb], &liveness.drop.outs[bb]);
305 writeln!(out, " | Live variables on exit from {:?}: {}", bb, s)?;
308 PassWhere::BeforeBlock(_) | PassWhere::AfterLocation(_) | PassWhere::AfterCFG => {}
314 // Also dump the inference graph constraints as a graphviz file.
315 let _: io::Result<()> = do catch {
317 pretty::create_dump_file(infcx.tcx, "regioncx.all.dot", None, "nll", &0, source)?;
318 regioncx.dump_graphviz_raw_constraints(&mut file)?;
321 // Also dump the inference graph constraints as a graphviz file.
322 let _: io::Result<()> = do catch {
324 pretty::create_dump_file(infcx.tcx, "regioncx.scc.dot", None, "nll", &0, source)?;
325 regioncx.dump_graphviz_scc_constraints(&mut file)?;
329 fn dump_annotation<'a, 'gcx, 'tcx>(
330 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
333 regioncx: &RegionInferenceContext,
334 closure_region_requirements: &Option<ClosureRegionRequirements>,
335 errors_buffer: &mut Vec<Diagnostic>,
338 let base_def_id = tcx.closure_base_def_id(mir_def_id);
339 if !tcx.has_attr(base_def_id, "rustc_regions") {
343 // When the enclosing function is tagged with `#[rustc_regions]`,
344 // we dump out various bits of state as warnings. This is useful
345 // for verifying that the compiler is behaving as expected. These
346 // warnings focus on the closure region requirements -- for
347 // viewing the intraprocedural state, the -Zdump-mir output is
350 if let Some(closure_region_requirements) = closure_region_requirements {
354 .span_note_diag(mir.span, "External requirements");
356 regioncx.annotate(&mut err);
359 "number of external vids: {}",
360 closure_region_requirements.num_external_vids
363 // Dump the region constraints we are imposing *between* those
364 // newly created variables.
365 for_each_region_constraint(closure_region_requirements, &mut |msg| {
370 err.buffer(errors_buffer);
375 .span_note_diag(mir.span, "No external requirements");
376 regioncx.annotate(&mut err);
378 err.buffer(errors_buffer);
382 fn for_each_region_constraint(
383 closure_region_requirements: &ClosureRegionRequirements,
384 with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
385 ) -> io::Result<()> {
386 for req in &closure_region_requirements.outlives_requirements {
387 let subject: &dyn Debug = match &req.subject {
388 ClosureOutlivesSubject::Region(subject) => subject,
389 ClosureOutlivesSubject::Ty(ty) => ty,
393 subject, req.outlived_free_region,
399 /// Right now, we piggy back on the `ReVar` to store our NLL inference
400 /// regions. These are indexed with `RegionVid`. This method will
401 /// assert that the region is a `ReVar` and extract its internal index.
402 /// This is reasonable because in our MIR we replace all universal regions
403 /// with inference variables.
404 pub trait ToRegionVid {
405 fn to_region_vid(self) -> RegionVid;
408 impl<'tcx> ToRegionVid for &'tcx RegionKind {
409 fn to_region_vid(self) -> RegionVid {
410 if let ty::ReVar(vid) = self {
413 bug!("region is not an ReVar: {:?}", self)
418 impl ToRegionVid for RegionVid {
419 fn to_region_vid(self) -> RegionVid {
424 fn live_variable_set(
425 regular: &LiveVarSet<LocalWithRegion>,
426 drops: &LiveVarSet<LocalWithRegion>
428 // sort and deduplicate:
429 let all_locals: BTreeSet<_> = regular.iter().chain(drops.iter()).collect();
431 // construct a string with each local, including `(drop)` if it is
432 // only dropped, versus a regular use.
433 let mut string = String::new();
434 for local in all_locals {
435 string.push_str(&format!("{:?}", local));
437 if !regular.contains(&local) {
438 assert!(drops.contains(&local));
439 string.push_str(" (drop)");
442 string.push_str(", ");
445 let len = if string.is_empty() {
451 format!("[{}]", &string[..len])