]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/cache.rs
Rollup merge of #64708 - SimonSapin:option-deref, r=Centril
[rust.git] / src / librustc / mir / cache.rs
1 use rustc_index::vec::IndexVec;
2 use rustc_data_structures::sync::{RwLock, MappedReadGuard, ReadGuard};
3 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
4 use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
5 use crate::ich::StableHashingContext;
6 use crate::mir::{Body, BasicBlock};
7
8 #[derive(Clone, Debug)]
9 pub struct Cache {
10     predecessors: RwLock<Option<IndexVec<BasicBlock, Vec<BasicBlock>>>>
11 }
12
13
14 impl rustc_serialize::Encodable for Cache {
15     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
16         Encodable::encode(&(), s)
17     }
18 }
19
20 impl rustc_serialize::Decodable for Cache {
21     fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
22         Decodable::decode(d).map(|_v: ()| Self::new())
23     }
24 }
25
26 impl<'a> HashStable<StableHashingContext<'a>> for Cache {
27     fn hash_stable(&self, _: &mut StableHashingContext<'a>, _: &mut StableHasher) {
28         // Do nothing.
29     }
30 }
31
32 impl Cache {
33     pub fn new() -> Self {
34         Cache {
35             predecessors: RwLock::new(None)
36         }
37     }
38
39     pub fn invalidate(&self) {
40         // FIXME: consider being more fine-grained
41         *self.predecessors.borrow_mut() = None;
42     }
43
44     pub fn predecessors(
45         &self,
46         body: &Body<'_>
47     ) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
48         if self.predecessors.borrow().is_none() {
49             *self.predecessors.borrow_mut() = Some(calculate_predecessors(body));
50         }
51
52         ReadGuard::map(self.predecessors.borrow(), |p| p.as_ref().unwrap())
53     }
54 }
55
56 fn calculate_predecessors(body: &Body<'_>) -> IndexVec<BasicBlock, Vec<BasicBlock>> {
57     let mut result = IndexVec::from_elem(vec![], body.basic_blocks());
58     for (bb, data) in body.basic_blocks().iter_enumerated() {
59         if let Some(ref term) = data.terminator {
60             for &tgt in term.successors() {
61                 result[tgt].push(bb);
62             }
63         }
64     }
65
66     result
67 }
68
69 CloneTypeFoldableAndLiftImpls! {
70     Cache,
71 }