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::LocationTable;
13 use borrow_check::nll::ToRegionVid;
14 use borrow_check::nll::facts::AllFacts;
15 use borrow_check::nll::region_infer::RegionInferenceContext;
16 use borrow_check::nll::type_check::AtLocation;
18 use rustc::infer::InferCtxt;
19 use rustc::mir::visit::TyContext;
20 use rustc::mir::visit::Visitor;
21 use rustc::mir::Place::Projection;
22 use rustc::mir::{BasicBlock, BasicBlockData, Location, Mir, Place, Rvalue};
23 use rustc::mir::{Local, PlaceProjection, ProjectionElem, Statement, Terminator};
24 use rustc::ty::fold::TypeFoldable;
25 use rustc::ty::subst::Substs;
26 use rustc::ty::{self, CanonicalTy, ClosureSubsts, GeneratorSubsts};
29 pub(super) fn generate_constraints<'cx, 'gcx, 'tcx>(
30 infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
31 regioncx: &mut RegionInferenceContext<'tcx>,
32 all_facts: &mut Option<AllFacts>,
33 location_table: &LocationTable,
35 borrow_set: &BorrowSet<'tcx>,
36 liveness_set_from_typeck: &[(ty::Region<'tcx>, Location)],
38 let mut cg = ConstraintGeneration {
47 cg.add_region_liveness_constraints_from_type_check(liveness_set_from_typeck);
49 for (bb, data) in mir.basic_blocks().iter_enumerated() {
50 cg.visit_basic_block_data(bb, data);
54 /// 'cg = the duration of the constraint generation process itself.
55 struct ConstraintGeneration<'cg, 'cx: 'cg, 'gcx: 'tcx, 'tcx: 'cx> {
56 infcx: &'cg InferCtxt<'cx, 'gcx, 'tcx>,
57 all_facts: &'cg mut Option<AllFacts>,
58 location_table: &'cg LocationTable,
59 regioncx: &'cg mut RegionInferenceContext<'tcx>,
61 borrow_set: &'cg BorrowSet<'tcx>,
64 impl<'cg, 'cx, 'gcx, 'tcx> Visitor<'tcx> for ConstraintGeneration<'cg, 'cx, 'gcx, 'tcx> {
65 fn visit_basic_block_data(&mut self, bb: BasicBlock, data: &BasicBlockData<'tcx>) {
66 self.super_basic_block_data(bb, data);
69 /// We sometimes have `substs` within an rvalue, or within a
70 /// call. Make them live at the location where they appear.
71 fn visit_substs(&mut self, substs: &&'tcx Substs<'tcx>, location: Location) {
72 self.add_regular_live_constraint(*substs, location);
73 self.super_substs(substs);
76 /// We sometimes have `region` within an rvalue, or within a
77 /// call. Make them live at the location where they appear.
78 fn visit_region(&mut self, region: &ty::Region<'tcx>, location: Location) {
79 self.add_regular_live_constraint(*region, location);
80 self.super_region(region);
83 /// We sometimes have `ty` within an rvalue, or within a
84 /// call. Make them live at the location where they appear.
85 fn visit_ty(&mut self, ty: &ty::Ty<'tcx>, ty_context: TyContext) {
87 TyContext::ReturnTy(source_info)
88 | TyContext::YieldTy(source_info)
89 | TyContext::LocalDecl { source_info, .. } => {
92 "should not be visiting outside of the CFG: {:?}",
96 TyContext::Location(location) => {
97 self.add_regular_live_constraint(*ty, location);
104 /// We sometimes have `generator_substs` within an rvalue, or within a
105 /// call. Make them live at the location where they appear.
106 fn visit_generator_substs(&mut self, substs: &GeneratorSubsts<'tcx>, location: Location) {
107 self.add_regular_live_constraint(*substs, location);
108 self.super_generator_substs(substs);
111 /// We sometimes have `closure_substs` within an rvalue, or within a
112 /// call. Make them live at the location where they appear.
113 fn visit_closure_substs(&mut self, substs: &ClosureSubsts<'tcx>, location: Location) {
114 self.add_regular_live_constraint(*substs, location);
115 self.super_closure_substs(substs);
121 statement: &Statement<'tcx>,
124 if let Some(all_facts) = self.all_facts {
125 all_facts.cfg_edge.push((
126 self.location_table.start_index(location),
127 self.location_table.mid_index(location),
130 all_facts.cfg_edge.push((
131 self.location_table.mid_index(location),
133 .start_index(location.successor_within_block()),
137 self.super_statement(block, statement, location);
144 rvalue: &Rvalue<'tcx>,
147 // When we see `X = ...`, then kill borrows of
148 // `(*X).foo` and so forth.
149 if let Some(all_facts) = self.all_facts {
150 if let Place::Local(temp) = place {
151 if let Some(borrow_indices) = self.borrow_set.local_map.get(temp) {
152 for &borrow_index in borrow_indices {
153 let location_index = self.location_table.mid_index(location);
154 all_facts.killed.push((borrow_index, location_index));
160 self.super_assign(block, place, rvalue, location);
166 terminator: &Terminator<'tcx>,
169 if let Some(all_facts) = self.all_facts {
170 all_facts.cfg_edge.push((
171 self.location_table.start_index(location),
172 self.location_table.mid_index(location),
175 for successor_block in terminator.successors() {
176 all_facts.cfg_edge.push((
177 self.location_table.mid_index(location),
179 .start_index(successor_block.start_location()),
184 self.super_terminator(block, terminator, location);
187 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
188 debug!("visit_rvalue(rvalue={:?}, location={:?})", rvalue, location);
191 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
192 // In some cases, e.g. when borrowing from an unsafe
193 // place, we don't bother to create a loan, since
194 // there are no conditions to validate.
195 if let Some(all_facts) = self.all_facts {
196 if let Some(borrow_index) = self.borrow_set.location_map.get(&location) {
197 let region_vid = region.to_region_vid();
198 all_facts.borrow_region.push((
201 self.location_table.mid_index(location),
206 // Look for an rvalue like:
210 // where L is the path that is borrowed. In that case, we have
211 // to add the reborrow constraints (which don't fall out
212 // naturally from the type-checker).
213 self.add_reborrow_constraint(location, region, borrowed_place);
219 self.super_rvalue(rvalue, location);
222 fn visit_user_assert_ty(
224 _c_ty: &CanonicalTy<'tcx>,
231 impl<'cx, 'cg, 'gcx, 'tcx> ConstraintGeneration<'cx, 'cg, 'gcx, 'tcx> {
232 /// The MIR type checker generates region liveness constraints
233 /// that we also have to respect.
234 fn add_region_liveness_constraints_from_type_check(
236 liveness_set: &[(ty::Region<'tcx>, Location)],
239 "add_region_liveness_constraints_from_type_check(liveness_set={} items)",
243 let ConstraintGeneration {
250 for (region, location) in liveness_set {
251 debug!("generate: {:#?} is live at {:#?}", region, location);
252 let region_vid = regioncx.to_region_vid(region);
253 regioncx.add_live_point(region_vid, *location);
256 if let Some(all_facts) = all_facts {
259 .extend(liveness_set.into_iter().flat_map(|(region, location)| {
260 let r = regioncx.to_region_vid(region);
261 let p1 = location_table.start_index(*location);
262 let p2 = location_table.mid_index(*location);
263 iter::once((r, p1)).chain(iter::once((r, p2)))
268 /// Some variable with type `live_ty` is "regular live" at
269 /// `location` -- i.e., it may be used later. This means that all
270 /// regions appearing in the type `live_ty` must be live at
272 fn add_regular_live_constraint<T>(&mut self, live_ty: T, location: Location)
274 T: TypeFoldable<'tcx>,
277 "add_regular_live_constraint(live_ty={:?}, location={:?})",
283 .for_each_free_region(&live_ty, |live_region| {
284 let vid = live_region.to_region_vid();
285 self.regioncx.add_live_point(vid, location);
289 // Add the reborrow constraint at `location` so that `borrowed_place`
290 // is valid for `borrow_region`.
291 fn add_reborrow_constraint(
294 borrow_region: ty::Region<'tcx>,
295 borrowed_place: &Place<'tcx>,
297 let mut borrowed_place = borrowed_place;
300 "add_reborrow_constraint({:?}, {:?}, {:?})",
301 location, borrow_region, borrowed_place
303 while let Projection(box PlaceProjection { base, elem }) = borrowed_place {
304 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
307 ProjectionElem::Deref => {
308 let tcx = self.infcx.tcx;
309 let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
311 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
313 ty::TyRef(ref_region, _, mutbl) => {
314 self.regioncx.add_outlives(
316 ref_region.to_region_vid(),
317 borrow_region.to_region_vid(),
320 if let Some(all_facts) = self.all_facts {
321 all_facts.outlives.push((
322 ref_region.to_region_vid(),
323 borrow_region.to_region_vid(),
324 self.location_table.mid_index(location),
329 hir::Mutability::MutImmutable => {
330 // Immutable reference. We don't need the base
331 // to be valid for the entire lifetime of
335 hir::Mutability::MutMutable => {
336 // Mutable reference. We *do* need the base
337 // to be valid, because after the base becomes
338 // invalid, someone else can use our mutable deref.
340 // This is in order to make the following function
343 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
348 // As otherwise you could clone `&mut T` using the
349 // following function:
351 // fn bad(x: &mut T) -> (&mut T, &mut T) {
352 // let my_clone = unsafe_deref(&'a x);
360 ty::TyRawPtr(..) => {
361 // deref of raw pointer, guaranteed to be valid
364 ty::TyAdt(def, _) if def.is_box() => {
365 // deref of `Box`, need the base to be valid - propagate
367 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
370 ProjectionElem::Field(..)
371 | ProjectionElem::Downcast(..)
372 | ProjectionElem::Index(..)
373 | ProjectionElem::ConstantIndex { .. }
374 | ProjectionElem::Subslice { .. } => {
375 // other field access
379 // The "propagate" case. We need to check that our base is valid
380 // for the borrow's lifetime.
381 borrowed_place = base;