1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Module defining the `dfs` method on `RegionInferenceContext`, along with
//! its associated helper traits.

use borrow_check::nll::universal_regions::UniversalRegions;
use borrow_check::nll::region_infer::RegionInferenceContext;
use borrow_check::nll::region_infer::values::{RegionElementIndex, RegionValueElements,
                                              RegionValues};
use syntax::codemap::Span;
use rustc::mir::{Location, Mir};
use rustc::ty::RegionVid;
use rustc_data_structures::bitvec::BitVector;
use rustc_data_structures::indexed_vec::Idx;

pub(super) struct DfsStorage {
    stack: Vec<Location>,
    visited: BitVector,
}

impl<'tcx> RegionInferenceContext<'tcx> {
    /// Creates dfs storage for use by dfs; this should be shared
    /// across as many calls to dfs as possible to amortize allocation
    /// costs.
    pub(super) fn new_dfs_storage(&self) -> DfsStorage {
        let num_elements = self.elements.num_elements();
        DfsStorage {
            stack: vec![],
            visited: BitVector::new(num_elements),
        }
    }

    /// Function used to satisfy or test a `R1: R2 @ P`
    /// constraint. The core idea is that it performs a DFS starting
    /// from `P`. The precise actions *during* that DFS depend on the
    /// `op` supplied, so see (e.g.) `CopyFromSourceToTarget` for more
    /// details.
    ///
    /// Returns:
    ///
    /// - `Ok(true)` if the walk was completed and something changed
    ///   along the way;
    /// - `Ok(false)` if the walk was completed with no changes;
    /// - `Err(early)` if the walk was existed early by `op`. `earlyelem` is the
    ///   value that `op` returned.
    #[inline(never)] // ensure dfs is identifiable in profiles
    pub(super) fn dfs<C>(
        &self,
        mir: &Mir<'tcx>,
        dfs: &mut DfsStorage,
        mut op: C,
    ) -> Result<bool, C::Early>
    where
        C: DfsOp,
    {
        let mut changed = false;

        dfs.visited.clear();
        dfs.stack.push(op.start_point());
        while let Some(p) = dfs.stack.pop() {
            let point_index = self.elements.index(p);

            if !op.source_region_contains(point_index) {
                debug!("            not in from-region");
                continue;
            }

            if !dfs.visited.insert(point_index.index()) {
                debug!("            already visited");
                continue;
            }

            let new = op.add_to_target_region(point_index)?;
            changed |= new;

            let block_data = &mir[p.block];

            let start_stack_len = dfs.stack.len();

            if p.statement_index < block_data.statements.len() {
                dfs.stack.push(Location {
                    statement_index: p.statement_index + 1,
                    ..p
                });
            } else {
                dfs.stack.extend(
                    block_data
                        .terminator()
                        .successors()
                        .iter()
                        .map(|&basic_block| Location {
                            statement_index: 0,
                            block: basic_block,
                        }),
                );
            }

            if dfs.stack.len() == start_stack_len {
                // If we reach the END point in the graph, then copy
                // over any skolemized end points in the `from_region`
                // and make sure they are included in the `to_region`.
                changed |= op.add_universal_regions_outlived_by_source_to_target()?;
            }
        }

        Ok(changed)
    }
}

/// Customizes the operation of the `dfs` function. This function is
/// used during inference to satisfy a `R1: R2 @ P` constraint.
pub(super) trait DfsOp {
    /// If this op stops the walk early, what type does it propagate?
    type Early;

    /// Returns the point from which to start the DFS.
    fn start_point(&self) -> Location;

    /// Returns true if the source region contains the given point.
    fn source_region_contains(&mut self, point_index: RegionElementIndex) -> bool;

    /// Adds the given point to the target region, returning true if
    /// something has changed. Returns `Err` if we should abort the
    /// walk early.
    fn add_to_target_region(
        &mut self,
        point_index: RegionElementIndex,
    ) -> Result<bool, Self::Early>;

    /// Adds all universal regions in the source region to the target region, returning
    /// true if something has changed.
    fn add_universal_regions_outlived_by_source_to_target(&mut self) -> Result<bool, Self::Early>;
}

/// Used during inference to enforce a `R1: R2 @ P` constraint.  For
/// each point Q we reach along the DFS, we check if Q is in R2 (the
/// "source region"). If not, we stop the walk. Otherwise, we add Q to
/// R1 (the "target region") and continue to Q's successors. If we
/// reach the end of the graph, then we add any universal regions from
/// R2 into R1.
pub(super) struct CopyFromSourceToTarget<'v> {
    pub source_region: RegionVid,
    pub target_region: RegionVid,
    pub inferred_values: &'v mut RegionValues,
    pub constraint_point: Location,
    pub constraint_span: Span,
}

impl<'v> DfsOp for CopyFromSourceToTarget<'v> {
    /// We never stop the walk early.
    type Early = !;

    fn start_point(&self) -> Location {
        self.constraint_point
    }

    fn source_region_contains(&mut self, point_index: RegionElementIndex) -> bool {
        self.inferred_values
            .contains(self.source_region, point_index)
    }

    fn add_to_target_region(&mut self, point_index: RegionElementIndex) -> Result<bool, !> {
        Ok(self.inferred_values.add_due_to_outlives(
            self.source_region,
            self.target_region,
            point_index,
            self.constraint_point,
            self.constraint_span,
        ))
    }

    fn add_universal_regions_outlived_by_source_to_target(&mut self) -> Result<bool, !> {
        Ok(self.inferred_values.add_universal_regions_outlived_by(
            self.source_region,
            self.target_region,
            self.constraint_point,
            self.constraint_span,
        ))
    }
}

/// Used after inference to *test* a `R1: R2 @ P` constraint.  For
/// each point Q we reach along the DFS, we check if Q in R2 is also
/// contained in R1. If not, we abort the walk early with an `Err`
/// condition. Similarly, if we reach the end of the graph and find
/// that R1 contains some universal region that R2 does not contain,
/// we abort the walk early.
pub(super) struct TestTargetOutlivesSource<'v, 'tcx: 'v> {
    pub source_region: RegionVid,
    pub target_region: RegionVid,
    pub elements: &'v RegionValueElements,
    pub universal_regions: &'v UniversalRegions<'tcx>,
    pub inferred_values: &'v RegionValues,
    pub constraint_point: Location,
}

impl<'v, 'tcx> DfsOp for TestTargetOutlivesSource<'v, 'tcx> {
    /// The element that was not found within R2.
    type Early = RegionElementIndex;

    fn start_point(&self) -> Location {
        self.constraint_point
    }

    fn source_region_contains(&mut self, point_index: RegionElementIndex) -> bool {
        self.inferred_values
            .contains(self.source_region, point_index)
    }

    fn add_to_target_region(
        &mut self,
        point_index: RegionElementIndex,
    ) -> Result<bool, RegionElementIndex> {
        if !self.inferred_values
            .contains(self.target_region, point_index)
        {
            return Err(point_index);
        }

        Ok(false)
    }

    fn add_universal_regions_outlived_by_source_to_target(
        &mut self,
    ) -> Result<bool, RegionElementIndex> {
        // For all `ur_in_source` in `source_region`.
        for ur_in_source in self.inferred_values
            .universal_regions_outlived_by(self.source_region)
        {
            // Check that `target_region` outlives `ur_in_source`.

            // If `ur_in_source` is a member of `target_region`, OK.
            //
            // (This is implied by the loop below, actually, just an
            // irresistible micro-opt. Mm. Premature optimization. So
            // tasty.)
            if self.inferred_values
                .contains(self.target_region, ur_in_source)
            {
                continue;
            }

            // If there is some other element X such that `target_region: X` and
            // `X: ur_in_source`, OK.
            if self.inferred_values
                .universal_regions_outlived_by(self.target_region)
                .any(|ur_in_target| self.universal_regions.outlives(ur_in_target, ur_in_source))
            {
                continue;
            }

            // Otherwise, not known to be true.
            return Err(self.elements.index(ur_in_source));
        }

        Ok(false)
    }
}