]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/region_infer/values.rs
2864abde0022c15e2c54e60ce4d80e9bcfd66699
[rust.git] / compiler / rustc_borrowck / src / region_infer / values.rs
1 use rustc_data_structures::fx::FxIndexSet;
2 use rustc_index::bit_set::{HybridBitSet, SparseBitMatrix};
3 use rustc_index::vec::Idx;
4 use rustc_index::vec::IndexVec;
5 use rustc_middle::mir::{BasicBlock, Body, Location};
6 use rustc_middle::ty::{self, RegionVid};
7 use std::fmt::Debug;
8 use std::rc::Rc;
9
10 /// Maps between a `Location` and a `PointIndex` (and vice versa).
11 crate struct RegionValueElements {
12     /// For each basic block, how many points are contained within?
13     statements_before_block: IndexVec<BasicBlock, usize>,
14
15     /// Map backward from each point to the basic block that it
16     /// belongs to.
17     basic_blocks: IndexVec<PointIndex, BasicBlock>,
18
19     num_points: usize,
20 }
21
22 impl RegionValueElements {
23     crate fn new(body: &Body<'_>) -> Self {
24         let mut num_points = 0;
25         let statements_before_block: IndexVec<BasicBlock, usize> = body
26             .basic_blocks()
27             .iter()
28             .map(|block_data| {
29                 let v = num_points;
30                 num_points += block_data.statements.len() + 1;
31                 v
32             })
33             .collect();
34         debug!("RegionValueElements: statements_before_block={:#?}", statements_before_block);
35         debug!("RegionValueElements: num_points={:#?}", num_points);
36
37         let mut basic_blocks = IndexVec::with_capacity(num_points);
38         for (bb, bb_data) in body.basic_blocks().iter_enumerated() {
39             basic_blocks.extend((0..=bb_data.statements.len()).map(|_| bb));
40         }
41
42         Self { statements_before_block, basic_blocks, num_points }
43     }
44
45     /// Total number of point indices
46     crate fn num_points(&self) -> usize {
47         self.num_points
48     }
49
50     /// Converts a `Location` into a `PointIndex`. O(1).
51     crate fn point_from_location(&self, location: Location) -> PointIndex {
52         let Location { block, statement_index } = location;
53         let start_index = self.statements_before_block[block];
54         PointIndex::new(start_index + statement_index)
55     }
56
57     /// Converts a `Location` into a `PointIndex`. O(1).
58     crate fn entry_point(&self, block: BasicBlock) -> PointIndex {
59         let start_index = self.statements_before_block[block];
60         PointIndex::new(start_index)
61     }
62
63     /// Converts a `PointIndex` back to a location. O(1).
64     crate fn to_location(&self, index: PointIndex) -> Location {
65         assert!(index.index() < self.num_points);
66         let block = self.basic_blocks[index];
67         let start_index = self.statements_before_block[block];
68         let statement_index = index.index() - start_index;
69         Location { block, statement_index }
70     }
71
72     /// Sometimes we get point-indices back from bitsets that may be
73     /// out of range (because they round up to the nearest 2^N number
74     /// of bits). Use this function to filter such points out if you
75     /// like.
76     crate fn point_in_range(&self, index: PointIndex) -> bool {
77         index.index() < self.num_points
78     }
79
80     /// Pushes all predecessors of `index` onto `stack`.
81     crate fn push_predecessors(
82         &self,
83         body: &Body<'_>,
84         index: PointIndex,
85         stack: &mut Vec<PointIndex>,
86     ) {
87         let Location { block, statement_index } = self.to_location(index);
88         if statement_index == 0 {
89             // If this is a basic block head, then the predecessors are
90             // the terminators of other basic blocks
91             stack.extend(
92                 body.predecessors()[block]
93                     .iter()
94                     .map(|&pred_bb| body.terminator_loc(pred_bb))
95                     .map(|pred_loc| self.point_from_location(pred_loc)),
96             );
97         } else {
98             // Otherwise, the pred is just the previous statement
99             stack.push(PointIndex::new(index.index() - 1));
100         }
101     }
102 }
103
104 rustc_index::newtype_index! {
105     /// A single integer representing a `Location` in the MIR control-flow
106     /// graph. Constructed efficiently from `RegionValueElements`.
107     pub struct PointIndex { DEBUG_FORMAT = "PointIndex({})" }
108 }
109
110 rustc_index::newtype_index! {
111     /// A single integer representing a `ty::Placeholder`.
112     pub struct PlaceholderIndex { DEBUG_FORMAT = "PlaceholderIndex({})" }
113 }
114
115 /// An individual element in a region value -- the value of a
116 /// particular region variable consists of a set of these elements.
117 #[derive(Debug, Clone)]
118 crate enum RegionElement {
119     /// A point in the control-flow graph.
120     Location(Location),
121
122     /// A universally quantified region from the root universe (e.g.,
123     /// a lifetime parameter).
124     RootUniversalRegion(RegionVid),
125
126     /// A placeholder (e.g., instantiated from a `for<'a> fn(&'a u32)`
127     /// type).
128     PlaceholderRegion(ty::PlaceholderRegion),
129 }
130
131 /// When we initially compute liveness, we use a bit matrix storing
132 /// points for each region-vid.
133 crate struct LivenessValues<N: Idx> {
134     elements: Rc<RegionValueElements>,
135     points: SparseBitMatrix<N, PointIndex>,
136 }
137
138 impl<N: Idx> LivenessValues<N> {
139     /// Creates a new set of "region values" that tracks causal information.
140     /// Each of the regions in num_region_variables will be initialized with an
141     /// empty set of points and no causal information.
142     crate fn new(elements: Rc<RegionValueElements>) -> Self {
143         Self { points: SparseBitMatrix::new(elements.num_points), elements }
144     }
145
146     /// Iterate through each region that has a value in this set.
147     crate fn rows(&self) -> impl Iterator<Item = N> {
148         self.points.rows()
149     }
150
151     /// Adds the given element to the value for the given region. Returns whether
152     /// the element is newly added (i.e., was not already present).
153     crate fn add_element(&mut self, row: N, location: Location) -> bool {
154         debug!("LivenessValues::add(r={:?}, location={:?})", row, location);
155         let index = self.elements.point_from_location(location);
156         self.points.insert(row, index)
157     }
158
159     /// Adds all the elements in the given bit array into the given
160     /// region. Returns whether any of them are newly added.
161     crate fn add_elements(&mut self, row: N, locations: &HybridBitSet<PointIndex>) -> bool {
162         debug!("LivenessValues::add_elements(row={:?}, locations={:?})", row, locations);
163         self.points.union_row(row, locations)
164     }
165
166     /// Adds all the control-flow points to the values for `r`.
167     crate fn add_all_points(&mut self, row: N) {
168         self.points.insert_all_into_row(row);
169     }
170
171     /// Returns `true` if the region `r` contains the given element.
172     crate fn contains(&self, row: N, location: Location) -> bool {
173         let index = self.elements.point_from_location(location);
174         self.points.contains(row, index)
175     }
176
177     /// Returns a "pretty" string value of the region. Meant for debugging.
178     crate fn region_value_str(&self, r: N) -> String {
179         region_value_str(
180             self.points
181                 .row(r)
182                 .into_iter()
183                 .flat_map(|set| set.iter())
184                 .take_while(|&p| self.elements.point_in_range(p))
185                 .map(|p| self.elements.to_location(p))
186                 .map(RegionElement::Location),
187         )
188     }
189 }
190
191 /// Maps from `ty::PlaceholderRegion` values that are used in the rest of
192 /// rustc to the internal `PlaceholderIndex` values that are used in
193 /// NLL.
194 #[derive(Default)]
195 crate struct PlaceholderIndices {
196     indices: FxIndexSet<ty::PlaceholderRegion>,
197 }
198
199 impl PlaceholderIndices {
200     crate fn insert(&mut self, placeholder: ty::PlaceholderRegion) -> PlaceholderIndex {
201         let (index, _) = self.indices.insert_full(placeholder);
202         index.into()
203     }
204
205     crate fn lookup_index(&self, placeholder: ty::PlaceholderRegion) -> PlaceholderIndex {
206         self.indices.get_index_of(&placeholder).unwrap().into()
207     }
208
209     crate fn lookup_placeholder(&self, placeholder: PlaceholderIndex) -> ty::PlaceholderRegion {
210         self.indices[placeholder.index()]
211     }
212
213     crate fn len(&self) -> usize {
214         self.indices.len()
215     }
216 }
217
218 /// Stores the full values for a set of regions (in contrast to
219 /// `LivenessValues`, which only stores those points in the where a
220 /// region is live). The full value for a region may contain points in
221 /// the CFG, but also free regions as well as bound universe
222 /// placeholders.
223 ///
224 /// Example:
225 ///
226 /// ```text
227 /// fn foo(x: &'a u32) -> &'a u32 {
228 ///    let y: &'0 u32 = x; // let's call this `'0`
229 ///    y
230 /// }
231 /// ```
232 ///
233 /// Here, the variable `'0` would contain the free region `'a`,
234 /// because (since it is returned) it must live for at least `'a`. But
235 /// it would also contain various points from within the function.
236 #[derive(Clone)]
237 crate struct RegionValues<N: Idx> {
238     elements: Rc<RegionValueElements>,
239     placeholder_indices: Rc<PlaceholderIndices>,
240     points: SparseBitMatrix<N, PointIndex>,
241     free_regions: SparseBitMatrix<N, RegionVid>,
242
243     /// Placeholders represent bound regions -- so something like `'a`
244     /// in for<'a> fn(&'a u32)`.
245     placeholders: SparseBitMatrix<N, PlaceholderIndex>,
246 }
247
248 impl<N: Idx> RegionValues<N> {
249     /// Creates a new set of "region values" that tracks causal information.
250     /// Each of the regions in num_region_variables will be initialized with an
251     /// empty set of points and no causal information.
252     crate fn new(
253         elements: &Rc<RegionValueElements>,
254         num_universal_regions: usize,
255         placeholder_indices: &Rc<PlaceholderIndices>,
256     ) -> Self {
257         let num_placeholders = placeholder_indices.len();
258         Self {
259             elements: elements.clone(),
260             points: SparseBitMatrix::new(elements.num_points),
261             placeholder_indices: placeholder_indices.clone(),
262             free_regions: SparseBitMatrix::new(num_universal_regions),
263             placeholders: SparseBitMatrix::new(num_placeholders),
264         }
265     }
266
267     /// Adds the given element to the value for the given region. Returns whether
268     /// the element is newly added (i.e., was not already present).
269     crate fn add_element(&mut self, r: N, elem: impl ToElementIndex) -> bool {
270         debug!("add(r={:?}, elem={:?})", r, elem);
271         elem.add_to_row(self, r)
272     }
273
274     /// Adds all the control-flow points to the values for `r`.
275     crate fn add_all_points(&mut self, r: N) {
276         self.points.insert_all_into_row(r);
277     }
278
279     /// Adds all elements in `r_from` to `r_to` (because e.g., `r_to:
280     /// r_from`).
281     crate fn add_region(&mut self, r_to: N, r_from: N) -> bool {
282         self.points.union_rows(r_from, r_to)
283             | self.free_regions.union_rows(r_from, r_to)
284             | self.placeholders.union_rows(r_from, r_to)
285     }
286
287     /// Returns `true` if the region `r` contains the given element.
288     crate fn contains(&self, r: N, elem: impl ToElementIndex) -> bool {
289         elem.contained_in_row(self, r)
290     }
291
292     /// `self[to] |= values[from]`, essentially: that is, take all the
293     /// elements for the region `from` from `values` and add them to
294     /// the region `to` in `self`.
295     crate fn merge_liveness<M: Idx>(&mut self, to: N, from: M, values: &LivenessValues<M>) {
296         if let Some(set) = values.points.row(from) {
297             self.points.union_row(to, set);
298         }
299     }
300
301     /// Returns `true` if `sup_region` contains all the CFG points that
302     /// `sub_region` contains. Ignores universal regions.
303     crate fn contains_points(&self, sup_region: N, sub_region: N) -> bool {
304         if let Some(sub_row) = self.points.row(sub_region) {
305             if let Some(sup_row) = self.points.row(sup_region) {
306                 sup_row.superset(sub_row)
307             } else {
308                 // sup row is empty, so sub row must be empty
309                 sub_row.is_empty()
310             }
311         } else {
312             // sub row is empty, always true
313             true
314         }
315     }
316
317     /// Returns the locations contained within a given region `r`.
318     crate fn locations_outlived_by<'a>(&'a self, r: N) -> impl Iterator<Item = Location> + 'a {
319         self.points.row(r).into_iter().flat_map(move |set| {
320             set.iter()
321                 .take_while(move |&p| self.elements.point_in_range(p))
322                 .map(move |p| self.elements.to_location(p))
323         })
324     }
325
326     /// Returns just the universal regions that are contained in a given region's value.
327     crate fn universal_regions_outlived_by<'a>(
328         &'a self,
329         r: N,
330     ) -> impl Iterator<Item = RegionVid> + 'a {
331         self.free_regions.row(r).into_iter().flat_map(|set| set.iter())
332     }
333
334     /// Returns all the elements contained in a given region's value.
335     crate fn placeholders_contained_in<'a>(
336         &'a self,
337         r: N,
338     ) -> impl Iterator<Item = ty::PlaceholderRegion> + 'a {
339         self.placeholders
340             .row(r)
341             .into_iter()
342             .flat_map(|set| set.iter())
343             .map(move |p| self.placeholder_indices.lookup_placeholder(p))
344     }
345
346     /// Returns all the elements contained in a given region's value.
347     crate fn elements_contained_in<'a>(&'a self, r: N) -> impl Iterator<Item = RegionElement> + 'a {
348         let points_iter = self.locations_outlived_by(r).map(RegionElement::Location);
349
350         let free_regions_iter =
351             self.universal_regions_outlived_by(r).map(RegionElement::RootUniversalRegion);
352
353         let placeholder_universes_iter =
354             self.placeholders_contained_in(r).map(RegionElement::PlaceholderRegion);
355
356         points_iter.chain(free_regions_iter).chain(placeholder_universes_iter)
357     }
358
359     /// Returns a "pretty" string value of the region. Meant for debugging.
360     crate fn region_value_str(&self, r: N) -> String {
361         region_value_str(self.elements_contained_in(r))
362     }
363 }
364
365 crate trait ToElementIndex: Debug + Copy {
366     fn add_to_row<N: Idx>(self, values: &mut RegionValues<N>, row: N) -> bool;
367
368     fn contained_in_row<N: Idx>(self, values: &RegionValues<N>, row: N) -> bool;
369 }
370
371 impl ToElementIndex for Location {
372     fn add_to_row<N: Idx>(self, values: &mut RegionValues<N>, row: N) -> bool {
373         let index = values.elements.point_from_location(self);
374         values.points.insert(row, index)
375     }
376
377     fn contained_in_row<N: Idx>(self, values: &RegionValues<N>, row: N) -> bool {
378         let index = values.elements.point_from_location(self);
379         values.points.contains(row, index)
380     }
381 }
382
383 impl ToElementIndex for RegionVid {
384     fn add_to_row<N: Idx>(self, values: &mut RegionValues<N>, row: N) -> bool {
385         values.free_regions.insert(row, self)
386     }
387
388     fn contained_in_row<N: Idx>(self, values: &RegionValues<N>, row: N) -> bool {
389         values.free_regions.contains(row, self)
390     }
391 }
392
393 impl ToElementIndex for ty::PlaceholderRegion {
394     fn add_to_row<N: Idx>(self, values: &mut RegionValues<N>, row: N) -> bool {
395         let index = values.placeholder_indices.lookup_index(self);
396         values.placeholders.insert(row, index)
397     }
398
399     fn contained_in_row<N: Idx>(self, values: &RegionValues<N>, row: N) -> bool {
400         let index = values.placeholder_indices.lookup_index(self);
401         values.placeholders.contains(row, index)
402     }
403 }
404
405 crate fn location_set_str(
406     elements: &RegionValueElements,
407     points: impl IntoIterator<Item = PointIndex>,
408 ) -> String {
409     region_value_str(
410         points
411             .into_iter()
412             .take_while(|&p| elements.point_in_range(p))
413             .map(|p| elements.to_location(p))
414             .map(RegionElement::Location),
415     )
416 }
417
418 fn region_value_str(elements: impl IntoIterator<Item = RegionElement>) -> String {
419     let mut result = String::new();
420     result.push('{');
421
422     // Set to Some(l1, l2) when we have observed all the locations
423     // from l1..=l2 (inclusive) but not yet printed them. This
424     // gets extended if we then see l3 where l3 is the successor
425     // to l2.
426     let mut open_location: Option<(Location, Location)> = None;
427
428     let mut sep = "";
429     let mut push_sep = |s: &mut String| {
430         s.push_str(sep);
431         sep = ", ";
432     };
433
434     for element in elements {
435         match element {
436             RegionElement::Location(l) => {
437                 if let Some((location1, location2)) = open_location {
438                     if location2.block == l.block
439                         && location2.statement_index == l.statement_index - 1
440                     {
441                         open_location = Some((location1, l));
442                         continue;
443                     }
444
445                     push_sep(&mut result);
446                     push_location_range(&mut result, location1, location2);
447                 }
448
449                 open_location = Some((l, l));
450             }
451
452             RegionElement::RootUniversalRegion(fr) => {
453                 if let Some((location1, location2)) = open_location {
454                     push_sep(&mut result);
455                     push_location_range(&mut result, location1, location2);
456                     open_location = None;
457                 }
458
459                 push_sep(&mut result);
460                 result.push_str(&format!("{:?}", fr));
461             }
462
463             RegionElement::PlaceholderRegion(placeholder) => {
464                 if let Some((location1, location2)) = open_location {
465                     push_sep(&mut result);
466                     push_location_range(&mut result, location1, location2);
467                     open_location = None;
468                 }
469
470                 push_sep(&mut result);
471                 result.push_str(&format!("{:?}", placeholder));
472             }
473         }
474     }
475
476     if let Some((location1, location2)) = open_location {
477         push_sep(&mut result);
478         push_location_range(&mut result, location1, location2);
479     }
480
481     result.push('}');
482
483     return result;
484
485     fn push_location_range(str: &mut String, location1: Location, location2: Location) {
486         if location1 == location2 {
487             str.push_str(&format!("{:?}", location1));
488         } else {
489             assert_eq!(location1.block, location2.block);
490             str.push_str(&format!(
491                 "{:?}[{}..={}]",
492                 location1.block, location1.statement_index, location2.statement_index
493             ));
494         }
495     }
496 }