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};
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>,
15 /// Map backward from each point to the basic block that it
17 basic_blocks: IndexVec<PointIndex, BasicBlock>,
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
30 num_points += block_data.statements.len() + 1;
34 debug!("RegionValueElements: statements_before_block={:#?}", statements_before_block);
35 debug!("RegionValueElements: num_points={:#?}", num_points);
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));
42 Self { statements_before_block, basic_blocks, num_points }
45 /// Total number of point indices
46 crate fn num_points(&self) -> usize {
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)
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)
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 }
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
76 crate fn point_in_range(&self, index: PointIndex) -> bool {
77 index.index() < self.num_points
80 /// Pushes all predecessors of `index` onto `stack`.
81 crate fn push_predecessors(
85 stack: &mut Vec<PointIndex>,
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
92 body.predecessors()[block]
94 .map(|&pred_bb| body.terminator_loc(pred_bb))
95 .map(|pred_loc| self.point_from_location(pred_loc)),
98 // Otherwise, the pred is just the previous statement
99 stack.push(PointIndex::new(index.index() - 1));
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({})" }
110 rustc_index::newtype_index! {
111 /// A single integer representing a `ty::Placeholder`.
112 pub struct PlaceholderIndex { DEBUG_FORMAT = "PlaceholderIndex({})" }
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.
122 /// A universally quantified region from the root universe (e.g.,
123 /// a lifetime parameter).
124 RootUniversalRegion(RegionVid),
126 /// A placeholder (e.g., instantiated from a `for<'a> fn(&'a u32)`
128 PlaceholderRegion(ty::PlaceholderRegion),
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>,
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 }
146 /// Iterate through each region that has a value in this set.
147 crate fn rows(&self) -> impl Iterator<Item = N> {
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)
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)
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);
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)
177 /// Returns a "pretty" string value of the region. Meant for debugging.
178 crate fn region_value_str(&self, r: N) -> String {
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),
191 /// Maps from `ty::PlaceholderRegion` values that are used in the rest of
192 /// rustc to the internal `PlaceholderIndex` values that are used in
195 crate struct PlaceholderIndices {
196 indices: FxIndexSet<ty::PlaceholderRegion>,
199 impl PlaceholderIndices {
200 crate fn insert(&mut self, placeholder: ty::PlaceholderRegion) -> PlaceholderIndex {
201 let (index, _) = self.indices.insert_full(placeholder);
205 crate fn lookup_index(&self, placeholder: ty::PlaceholderRegion) -> PlaceholderIndex {
206 self.indices.get_index_of(&placeholder).unwrap().into()
209 crate fn lookup_placeholder(&self, placeholder: PlaceholderIndex) -> ty::PlaceholderRegion {
210 self.indices[placeholder.index()]
213 crate fn len(&self) -> usize {
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
227 /// fn foo(x: &'a u32) -> &'a u32 {
228 /// let y: &'0 u32 = x; // let's call this `'0`
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.
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>,
243 /// Placeholders represent bound regions -- so something like `'a`
244 /// in for<'a> fn(&'a u32)`.
245 placeholders: SparseBitMatrix<N, PlaceholderIndex>,
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.
253 elements: &Rc<RegionValueElements>,
254 num_universal_regions: usize,
255 placeholder_indices: &Rc<PlaceholderIndices>,
257 let num_placeholders = placeholder_indices.len();
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),
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)
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);
279 /// Adds all elements in `r_from` to `r_to` (because e.g., `r_to:
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)
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)
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);
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)
308 // sup row is empty, so sub row must be empty
312 // sub row is empty, always true
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| {
321 .take_while(move |&p| self.elements.point_in_range(p))
322 .map(move |p| self.elements.to_location(p))
326 /// Returns just the universal regions that are contained in a given region's value.
327 crate fn universal_regions_outlived_by<'a>(
330 ) -> impl Iterator<Item = RegionVid> + 'a {
331 self.free_regions.row(r).into_iter().flat_map(|set| set.iter())
334 /// Returns all the elements contained in a given region's value.
335 crate fn placeholders_contained_in<'a>(
338 ) -> impl Iterator<Item = ty::PlaceholderRegion> + 'a {
342 .flat_map(|set| set.iter())
343 .map(move |p| self.placeholder_indices.lookup_placeholder(p))
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);
350 let free_regions_iter =
351 self.universal_regions_outlived_by(r).map(RegionElement::RootUniversalRegion);
353 let placeholder_universes_iter =
354 self.placeholders_contained_in(r).map(RegionElement::PlaceholderRegion);
356 points_iter.chain(free_regions_iter).chain(placeholder_universes_iter)
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))
365 crate trait ToElementIndex: Debug + Copy {
366 fn add_to_row<N: Idx>(self, values: &mut RegionValues<N>, row: N) -> bool;
368 fn contained_in_row<N: Idx>(self, values: &RegionValues<N>, row: N) -> bool;
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)
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)
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)
388 fn contained_in_row<N: Idx>(self, values: &RegionValues<N>, row: N) -> bool {
389 values.free_regions.contains(row, self)
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)
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)
405 crate fn location_set_str(
406 elements: &RegionValueElements,
407 points: impl IntoIterator<Item = PointIndex>,
412 .take_while(|&p| elements.point_in_range(p))
413 .map(|p| elements.to_location(p))
414 .map(RegionElement::Location),
418 fn region_value_str(elements: impl IntoIterator<Item = RegionElement>) -> String {
419 let mut result = String::new();
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
426 let mut open_location: Option<(Location, Location)> = None;
429 let mut push_sep = |s: &mut String| {
434 for element in elements {
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
441 open_location = Some((location1, l));
445 push_sep(&mut result);
446 push_location_range(&mut result, location1, location2);
449 open_location = Some((l, l));
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;
459 push_sep(&mut result);
460 result.push_str(&format!("{:?}", fr));
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;
470 push_sep(&mut result);
471 result.push_str(&format!("{:?}", placeholder));
476 if let Some((location1, location2)) = open_location {
477 push_sep(&mut result);
478 push_location_range(&mut result, location1, location2);
485 fn push_location_range(str: &mut String, location1: Location, location2: Location) {
486 if location1 == location2 {
487 str.push_str(&format!("{:?}", location1));
489 assert_eq!(location1.block, location2.block);
490 str.push_str(&format!(
492 location1.block, location1.statement_index, location2.statement_index