Skip to main content

rustc_middle/mir/
basic_blocks.rs

1use std::sync::{Arc, OnceLock};
2
3use rustc_data_structures::graph;
4use rustc_data_structures::graph::dominators::{Dominators, dominators};
5use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher};
6use rustc_index::{IndexSlice, IndexVec};
7use rustc_macros::{StableHash, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
8use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
9use smallvec::SmallVec;
10
11use crate::mir::traversal::Postorder;
12use crate::mir::{BasicBlock, BasicBlockData, START_BLOCK};
13
14#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for BasicBlocks<'tcx> {
    #[inline]
    fn clone(&self) -> BasicBlocks<'tcx> {
        BasicBlocks {
            basic_blocks: ::core::clone::Clone::clone(&self.basic_blocks),
            cache: ::core::clone::Clone::clone(&self.cache),
        }
    }
}Clone, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for BasicBlocks<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    BasicBlocks {
                        basic_blocks: ref __binding_0, cache: ref __binding_1 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for BasicBlocks<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                BasicBlocks {
                    basic_blocks: ::rustc_serialize::Decodable::decode(__decoder),
                    cache: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for BasicBlocks<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "BasicBlocks",
            "basic_blocks", &self.basic_blocks, "cache", &&self.cache)
    }
}Debug, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            BasicBlocks<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    BasicBlocks {
                        basic_blocks: ref __binding_0, cache: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for BasicBlocks<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        BasicBlocks { basic_blocks: __binding_0, cache: __binding_1
                            } => {
                            BasicBlocks {
                                basic_blocks: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                cache: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    BasicBlocks { basic_blocks: __binding_0, cache: __binding_1
                        } => {
                        BasicBlocks {
                            basic_blocks: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            cache: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for BasicBlocks<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    BasicBlocks {
                        basic_blocks: ref __binding_0, cache: ref __binding_1 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
15pub struct BasicBlocks<'tcx> {
16    basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
17    /// Use an `Arc` so we can share the cache when we clone the MIR body, as borrowck does.
18    cache: Arc<Cache>,
19}
20
21// Typically 95%+ of basic blocks have 4 or fewer predecessors.
22type Predecessors = IndexVec<BasicBlock, SmallVec<[BasicBlock; 4]>>;
23
24#[derive(#[automatically_derived]
impl ::core::clone::Clone for Cache {
    #[inline]
    fn clone(&self) -> Cache {
        Cache {
            predecessors: ::core::clone::Clone::clone(&self.predecessors),
            reverse_postorder: ::core::clone::Clone::clone(&self.reverse_postorder),
            dominators: ::core::clone::Clone::clone(&self.dominators),
        }
    }
}Clone, #[automatically_derived]
impl ::core::default::Default for Cache {
    #[inline]
    fn default() -> Cache {
        Cache {
            predecessors: ::core::default::Default::default(),
            reverse_postorder: ::core::default::Default::default(),
            dominators: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl ::core::fmt::Debug for Cache {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "Cache",
            "predecessors", &self.predecessors, "reverse_postorder",
            &self.reverse_postorder, "dominators", &&self.dominators)
    }
}Debug)]
25struct Cache {
26    predecessors: OnceLock<Predecessors>,
27    reverse_postorder: OnceLock<Vec<BasicBlock>>,
28    dominators: OnceLock<Dominators<BasicBlock>>,
29}
30
31impl<'tcx> BasicBlocks<'tcx> {
32    #[inline]
33    pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
34        BasicBlocks { basic_blocks, cache: Arc::new(Cache::default()) }
35    }
36
37    #[inline]
38    pub fn dominators(&self) -> &Dominators<BasicBlock> {
39        self.cache.dominators.get_or_init(|| dominators(self))
40    }
41
42    /// Returns predecessors for each basic block.
43    #[inline]
44    pub fn predecessors(&self) -> &Predecessors {
45        self.cache.predecessors.get_or_init(|| {
46            let mut preds = IndexVec::from_elem(SmallVec::new(), &self.basic_blocks);
47            for (bb, data) in self.basic_blocks.iter_enumerated() {
48                if let Some(term) = &data.terminator {
49                    for succ in term.successors() {
50                        preds[succ].push(bb);
51                    }
52                }
53            }
54            preds
55        })
56    }
57
58    /// Returns basic blocks in a reverse postorder.
59    ///
60    /// See [`traversal::reverse_postorder`]'s docs to learn what is postorder traversal.
61    ///
62    /// [`traversal::reverse_postorder`]: crate::mir::traversal::reverse_postorder
63    #[inline]
64    pub fn reverse_postorder(&self) -> &[BasicBlock] {
65        self.cache.reverse_postorder.get_or_init(|| {
66            let mut rpo: Vec<_> = Postorder::new(&self.basic_blocks, START_BLOCK, None).collect();
67            rpo.reverse();
68            rpo
69        })
70    }
71
72    /// Returns mutable reference to basic blocks. Invalidates CFG cache.
73    #[inline]
74    pub fn as_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
75        self.invalidate_cfg_cache();
76        &mut self.basic_blocks
77    }
78
79    /// Get mutable access to basic blocks without invalidating the CFG cache.
80    ///
81    /// By calling this method instead of e.g. [`BasicBlocks::as_mut`] you promise not to change
82    /// the CFG. This means that
83    ///
84    ///  1) The number of basic blocks remains unchanged
85    ///  2) The set of successors of each terminator remains unchanged.
86    ///  3) For each `TerminatorKind::SwitchInt`, the `targets` remains the same and the terminator
87    ///     kind is not changed.
88    ///
89    /// If any of these conditions cannot be upheld, you should call [`BasicBlocks::invalidate_cfg_cache`].
90    #[inline]
91    pub fn as_mut_preserves_cfg(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
92        &mut self.basic_blocks
93    }
94
95    /// Invalidates cached information about the CFG.
96    ///
97    /// You will only ever need this if you have also called [`BasicBlocks::as_mut_preserves_cfg`].
98    /// All other methods that allow you to mutate the basic blocks also call this method
99    /// themselves, thereby avoiding any risk of accidentally cache invalidation.
100    pub fn invalidate_cfg_cache(&mut self) {
101        if let Some(cache) = Arc::get_mut(&mut self.cache) {
102            // If we only have a single reference to this cache, clear it.
103            *cache = Cache::default();
104        } else {
105            // If we have several references to this cache, overwrite the pointer itself so other
106            // users can continue to use their (valid) cache.
107            self.cache = Arc::new(Cache::default());
108        }
109    }
110}
111
112impl<'tcx> std::ops::Deref for BasicBlocks<'tcx> {
113    type Target = IndexSlice<BasicBlock, BasicBlockData<'tcx>>;
114
115    #[inline]
116    fn deref(&self) -> &IndexSlice<BasicBlock, BasicBlockData<'tcx>> {
117        &self.basic_blocks
118    }
119}
120
121impl<'tcx> graph::DirectedGraph for BasicBlocks<'tcx> {
122    type Node = BasicBlock;
123
124    #[inline]
125    fn num_nodes(&self) -> usize {
126        self.basic_blocks.len()
127    }
128}
129
130impl<'tcx> graph::StartNode for BasicBlocks<'tcx> {
131    #[inline]
132    fn start_node(&self) -> Self::Node {
133        START_BLOCK
134    }
135}
136
137impl<'tcx> graph::Successors for BasicBlocks<'tcx> {
138    #[inline]
139    fn successors(&self, node: Self::Node) -> impl Iterator<Item = Self::Node> {
140        self.basic_blocks[node].terminator().successors()
141    }
142}
143
144impl<'tcx> graph::Predecessors for BasicBlocks<'tcx> {
145    #[inline]
146    fn predecessors(&self, node: Self::Node) -> impl Iterator<Item = Self::Node> {
147        self.predecessors()[node].iter().copied()
148    }
149}
150
151// Done here instead of in `structural_impls.rs` because `Cache` is private, as is `basic_blocks`.
152impl<'tcx> crate::ty::TypeFoldable<crate::ty::TyCtxt<'tcx>> for Cache {
    fn try_fold_with<F: crate::ty::FallibleTypeFolder<crate::ty::TyCtxt<'tcx>>>(self,
        _: &mut F) -> ::std::result::Result<Self, F::Error> {
        Ok(self)
    }
    #[inline]
    fn fold_with<F: crate::ty::TypeFolder<crate::ty::TyCtxt<'tcx>>>(self,
        _: &mut F) -> Self {
        self
    }
}
impl<'tcx> crate::ty::TypeVisitable<crate::ty::TyCtxt<'tcx>> for Cache {
    #[inline]
    fn visit_with<F: crate::ty::TypeVisitor<crate::ty::TyCtxt<'tcx>>>(&self,
        _: &mut F) -> F::Result {
        <F::Result as ::rustc_middle::ty::VisitorResult>::output()
    }
}TrivialTypeTraversalImpls! { Cache }
153
154impl<S: Encoder> Encodable<S> for Cache {
155    #[inline]
156    fn encode(&self, _s: &mut S) {}
157}
158
159impl<D: Decoder> Decodable<D> for Cache {
160    #[inline]
161    fn decode(_: &mut D) -> Self {
162        Default::default()
163    }
164}
165
166impl StableHash for Cache {
167    #[inline]
168    fn stable_hash<Hcx: StableHashCtxt>(&self, _: &mut Hcx, _: &mut StableHasher) {}
169}