rust/compiler/rustc_middle/src/mir/predecessors.rs

81 lines
2.5 KiB
Rust
Raw Normal View History

//! Lazily compute the reverse control-flow graph for the MIR.
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
2020-05-16 04:56:33 +00:00
use rustc_data_structures::sync::OnceCell;
use rustc_index::vec::IndexVec;
use rustc_serialize as serialize;
use smallvec::SmallVec;
use crate::mir::{BasicBlock, BasicBlockData};
// Typically 95%+ of basic blocks have 4 or fewer predecessors.
pub type Predecessors = IndexVec<BasicBlock, SmallVec<[BasicBlock; 4]>>;
#[derive(Clone, Debug)]
pub(super) struct PredecessorCache {
2020-05-16 04:56:33 +00:00
cache: OnceCell<Predecessors>,
}
impl PredecessorCache {
2020-04-12 17:48:56 +00:00
#[inline]
pub(super) fn new() -> Self {
2020-05-16 04:56:33 +00:00
PredecessorCache { cache: OnceCell::new() }
}
/// Invalidates the predecessor cache.
2020-04-12 17:48:56 +00:00
#[inline]
pub(super) fn invalidate(&mut self) {
2020-05-16 18:26:21 +00:00
// Invalidating the predecessor cache requires mutating the MIR, which in turn requires a
// unique reference (`&mut`) to the `mir::Body`. Because of this, we can assume that all
// callers of `invalidate` have a unique reference to the MIR and thus to the predecessor
// cache. This means we never need to do synchronization when `invalidate` is called, we can
// simply reinitialize the `OnceCell`.
2020-05-16 04:56:33 +00:00
self.cache = OnceCell::new();
}
2020-05-16 04:56:33 +00:00
/// Returns the the predecessor graph for this MIR.
2020-04-12 17:48:56 +00:00
#[inline]
pub(super) fn compute(
&self,
basic_blocks: &IndexVec<BasicBlock, BasicBlockData<'_>>,
2020-05-16 04:56:33 +00:00
) -> &Predecessors {
self.cache.get_or_init(|| {
let mut preds = IndexVec::from_elem(SmallVec::new(), basic_blocks);
for (bb, data) in basic_blocks.iter_enumerated() {
if let Some(term) = &data.terminator {
for &succ in term.successors() {
preds[succ].push(bb);
}
}
}
2020-05-16 04:56:33 +00:00
preds
})
}
}
impl<S: serialize::Encoder> serialize::Encodable<S> for PredecessorCache {
2020-04-12 17:48:56 +00:00
#[inline]
fn encode(&self, s: &mut S) -> Result<(), S::Error> {
serialize::Encodable::encode(&(), s)
}
}
impl<D: serialize::Decoder> serialize::Decodable<D> for PredecessorCache {
2020-04-12 17:48:56 +00:00
#[inline]
fn decode(d: &mut D) -> Result<Self, D::Error> {
serialize::Decodable::decode(d).map(|_v: ()| Self::new())
}
}
impl<CTX> HashStable<CTX> for PredecessorCache {
2020-04-12 17:48:56 +00:00
#[inline]
fn hash_stable(&self, _: &mut CTX, _: &mut StableHasher) {
// do nothing
}
}
CloneTypeFoldableAndLiftImpls! {
PredecessorCache,
}