Use OnceCell for predecessor cache

This commit is contained in:
Dylan MacKenzie 2020-05-15 21:56:33 -07:00
parent c282c1c654
commit f17e2c93a6

View file

@ -1,7 +1,7 @@
//! Lazily compute the reverse control-flow graph for the MIR.
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::sync::{Lock, Lrc};
use rustc_data_structures::sync::OnceCell;
use rustc_index::vec::IndexVec;
use rustc_serialize as serialize;
use smallvec::SmallVec;
@ -13,13 +13,13 @@ pub type Predecessors = IndexVec<BasicBlock, SmallVec<[BasicBlock; 4]>>;
#[derive(Clone, Debug)]
pub(super) struct PredecessorCache {
cache: Lock<Option<Lrc<Predecessors>>>,
cache: OnceCell<Predecessors>,
}
impl PredecessorCache {
#[inline]
pub(super) fn new() -> Self {
PredecessorCache { cache: Lock::new(None) }
PredecessorCache { cache: OnceCell::new() }
}
/// Invalidates the predecessor cache.
@ -27,23 +27,19 @@ impl PredecessorCache {
/// 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 don't actually need to take a lock when `invalidate` is called.
/// cache. This means we never need to do synchronization when `invalidate` is called.
#[inline]
pub(super) fn invalidate(&mut self) {
*self.cache.get_mut() = None;
self.cache = OnceCell::new();
}
/// Returns a ref-counted smart pointer containing the predecessor graph for this MIR.
///
/// We use ref-counting instead of a mapped `LockGuard` here to ensure that the lock for
/// `cache` is only held inside this function. As long as no other locks are taken while
/// computing the predecessor graph, deadlock is impossible.
/// Returns the the predecessor graph for this MIR.
#[inline]
pub(super) fn compute(
&self,
basic_blocks: &IndexVec<BasicBlock, BasicBlockData<'_>>,
) -> Lrc<Predecessors> {
Lrc::clone(self.cache.lock().get_or_insert_with(|| {
) -> &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 {
@ -53,8 +49,8 @@ impl PredecessorCache {
}
}
Lrc::new(preds)
}))
preds
})
}
}