|  | 
| 1 | 1 | pub use super::*; | 
| 2 | 2 | 
 | 
| 3 |  | -use crate::dataflow::{BitDenotation, GenKillSet}; | 
|  | 3 | +use crate::dataflow::generic::{AnalysisDomain, GenKill, GenKillAnalysis}; | 
| 4 | 4 | use rustc::mir::visit::Visitor; | 
| 5 | 5 | use rustc::mir::*; | 
|  | 6 | +use rustc::ty::{ParamEnv, TyCtxt}; | 
|  | 7 | +use rustc_span::DUMMY_SP; | 
| 6 | 8 | 
 | 
| 7 |  | -/// This calculates if any part of a MIR local could have previously been borrowed. | 
| 8 |  | -/// This means that once a local has been borrowed, its bit will be set | 
| 9 |  | -/// from that point and onwards, until we see a StorageDead statement for the local, | 
| 10 |  | -/// at which points there is no memory associated with the local, so it cannot be borrowed. | 
| 11 |  | -/// This is used to compute which locals are live during a yield expression for | 
| 12 |  | -/// immovable generators. | 
| 13 |  | -#[derive(Copy, Clone)] | 
| 14 |  | -pub struct HaveBeenBorrowedLocals<'a, 'tcx> { | 
| 15 |  | -    body: &'a Body<'tcx>, | 
|  | 9 | +pub type MaybeMutBorrowedLocals<'mir, 'tcx> = MaybeBorrowedLocals<MutBorrow<'mir, 'tcx>>; | 
|  | 10 | + | 
|  | 11 | +/// A dataflow analysis that tracks whether a pointer or reference could possibly exist that points | 
|  | 12 | +/// to a given local. | 
|  | 13 | +/// | 
|  | 14 | +/// The `K` parameter determines what kind of borrows are tracked. By default, | 
|  | 15 | +/// `MaybeBorrowedLocals` looks for *any* borrow of a local. If you are only interested in borrows | 
|  | 16 | +/// that might allow mutation, use the `MaybeMutBorrowedLocals` type alias instead. | 
|  | 17 | +/// | 
|  | 18 | +/// At present, this is used as a very limited form of alias analysis. For example, | 
|  | 19 | +/// `MaybeBorrowedLocals` is used to compute which locals are live during a yield expression for | 
|  | 20 | +/// immovable generators. `MaybeMutBorrowedLocals` is used during const checking to prove that a | 
|  | 21 | +/// local has not been mutated via indirect assignment (e.g., `*p = 42`), the side-effects of a | 
|  | 22 | +/// function call or inline assembly. | 
|  | 23 | +pub struct MaybeBorrowedLocals<K = AnyBorrow> { | 
|  | 24 | +    kind: K, | 
|  | 25 | +    ignore_borrow_on_drop: bool, | 
|  | 26 | +} | 
|  | 27 | + | 
|  | 28 | +impl MaybeBorrowedLocals { | 
|  | 29 | +    /// A dataflow analysis that records whether a pointer or reference exists that may alias the | 
|  | 30 | +    /// given local. | 
|  | 31 | +    pub fn all_borrows() -> Self { | 
|  | 32 | +        MaybeBorrowedLocals { kind: AnyBorrow, ignore_borrow_on_drop: false } | 
|  | 33 | +    } | 
|  | 34 | +} | 
|  | 35 | + | 
|  | 36 | +impl MaybeMutBorrowedLocals<'mir, 'tcx> { | 
|  | 37 | +    /// A dataflow analysis that records whether a pointer or reference exists that may *mutably* | 
|  | 38 | +    /// alias the given local. | 
|  | 39 | +    /// | 
|  | 40 | +    /// This includes `&mut` and pointers derived from an `&mut`, as well as shared borrows of | 
|  | 41 | +    /// types with interior mutability. | 
|  | 42 | +    pub fn mut_borrows_only( | 
|  | 43 | +        tcx: TyCtxt<'tcx>, | 
|  | 44 | +        body: &'mir mir::Body<'tcx>, | 
|  | 45 | +        param_env: ParamEnv<'tcx>, | 
|  | 46 | +    ) -> Self { | 
|  | 47 | +        MaybeBorrowedLocals { | 
|  | 48 | +            kind: MutBorrow { body, tcx, param_env }, | 
|  | 49 | +            ignore_borrow_on_drop: false, | 
|  | 50 | +        } | 
|  | 51 | +    } | 
| 16 | 52 | } | 
| 17 | 53 | 
 | 
| 18 |  | -impl<'a, 'tcx> HaveBeenBorrowedLocals<'a, 'tcx> { | 
| 19 |  | -    pub fn new(body: &'a Body<'tcx>) -> Self { | 
| 20 |  | -        HaveBeenBorrowedLocals { body } | 
|  | 54 | +impl<K> MaybeBorrowedLocals<K> { | 
|  | 55 | +    /// During dataflow analysis, ignore the borrow that may occur when a place is dropped. | 
|  | 56 | +    /// | 
|  | 57 | +    /// Drop terminators may call custom drop glue (`Drop::drop`), which takes `&mut self` as a | 
|  | 58 | +    /// parameter. In the general case, a drop impl could launder that reference into the | 
|  | 59 | +    /// surrounding environment through a raw pointer, thus creating a valid `*mut` pointing to the | 
|  | 60 | +    /// dropped local. We are not yet willing to declare this particular case UB, so we must treat | 
|  | 61 | +    /// all dropped locals as mutably borrowed for now. See discussion on [#61069]. | 
|  | 62 | +    /// | 
|  | 63 | +    /// In some contexts, we know that this borrow will never occur. For example, during | 
|  | 64 | +    /// const-eval, custom drop glue cannot be run. Code that calls this should document the | 
|  | 65 | +    /// assumptions that justify ignoring `Drop` terminators in this way. | 
|  | 66 | +    /// | 
|  | 67 | +    /// [#61069]: https://github.com/rust-lang/rust/pull/61069 | 
|  | 68 | +    pub fn unsound_ignore_borrow_on_drop(self) -> Self { | 
|  | 69 | +        MaybeBorrowedLocals { ignore_borrow_on_drop: true, ..self } | 
| 21 | 70 |     } | 
| 22 | 71 | 
 | 
| 23 |  | -    pub fn body(&self) -> &Body<'tcx> { | 
| 24 |  | -        self.body | 
|  | 72 | +    fn transfer_function<'a, T>(&'a self, trans: &'a mut T) -> TransferFunction<'a, T, K> { | 
|  | 73 | +        TransferFunction { | 
|  | 74 | +            kind: &self.kind, | 
|  | 75 | +            trans, | 
|  | 76 | +            ignore_borrow_on_drop: self.ignore_borrow_on_drop, | 
|  | 77 | +        } | 
| 25 | 78 |     } | 
| 26 | 79 | } | 
| 27 | 80 | 
 | 
| 28 |  | -impl<'a, 'tcx> BitDenotation<'tcx> for HaveBeenBorrowedLocals<'a, 'tcx> { | 
|  | 81 | +impl<K> AnalysisDomain<'tcx> for MaybeBorrowedLocals<K> | 
|  | 82 | +where | 
|  | 83 | +    K: BorrowAnalysisKind<'tcx>, | 
|  | 84 | +{ | 
| 29 | 85 |     type Idx = Local; | 
| 30 |  | -    fn name() -> &'static str { | 
| 31 |  | -        "has_been_borrowed_locals" | 
|  | 86 | + | 
|  | 87 | +    const NAME: &'static str = K::ANALYSIS_NAME; | 
|  | 88 | + | 
|  | 89 | +    fn bits_per_block(&self, body: &mir::Body<'tcx>) -> usize { | 
|  | 90 | +        body.local_decls().len() | 
|  | 91 | +    } | 
|  | 92 | + | 
|  | 93 | +    fn initialize_start_block(&self, _: &mir::Body<'tcx>, _: &mut BitSet<Self::Idx>) { | 
|  | 94 | +        // No locals are aliased on function entry | 
|  | 95 | +    } | 
|  | 96 | +} | 
|  | 97 | + | 
|  | 98 | +impl<K> GenKillAnalysis<'tcx> for MaybeBorrowedLocals<K> | 
|  | 99 | +where | 
|  | 100 | +    K: BorrowAnalysisKind<'tcx>, | 
|  | 101 | +{ | 
|  | 102 | +    fn statement_effect( | 
|  | 103 | +        &self, | 
|  | 104 | +        trans: &mut impl GenKill<Self::Idx>, | 
|  | 105 | +        statement: &mir::Statement<'tcx>, | 
|  | 106 | +        location: Location, | 
|  | 107 | +    ) { | 
|  | 108 | +        self.transfer_function(trans).visit_statement(statement, location); | 
| 32 | 109 |     } | 
| 33 |  | -    fn bits_per_block(&self) -> usize { | 
| 34 |  | -        self.body.local_decls.len() | 
|  | 110 | + | 
|  | 111 | +    fn terminator_effect( | 
|  | 112 | +        &self, | 
|  | 113 | +        trans: &mut impl GenKill<Self::Idx>, | 
|  | 114 | +        terminator: &mir::Terminator<'tcx>, | 
|  | 115 | +        location: Location, | 
|  | 116 | +    ) { | 
|  | 117 | +        self.transfer_function(trans).visit_terminator(terminator, location); | 
| 35 | 118 |     } | 
| 36 | 119 | 
 | 
| 37 |  | -    fn start_block_effect(&self, _on_entry: &mut BitSet<Local>) { | 
| 38 |  | -        // Nothing is borrowed on function entry | 
|  | 120 | +    fn call_return_effect( | 
|  | 121 | +        &self, | 
|  | 122 | +        _trans: &mut impl GenKill<Self::Idx>, | 
|  | 123 | +        _block: mir::BasicBlock, | 
|  | 124 | +        _func: &mir::Operand<'tcx>, | 
|  | 125 | +        _args: &[mir::Operand<'tcx>], | 
|  | 126 | +        _dest_place: &mir::Place<'tcx>, | 
|  | 127 | +    ) { | 
| 39 | 128 |     } | 
|  | 129 | +} | 
|  | 130 | + | 
|  | 131 | +impl<K> BottomValue for MaybeBorrowedLocals<K> { | 
|  | 132 | +    // bottom = unborrowed | 
|  | 133 | +    const BOTTOM_VALUE: bool = false; | 
|  | 134 | +} | 
| 40 | 135 | 
 | 
| 41 |  | -    fn statement_effect(&self, trans: &mut GenKillSet<Local>, loc: Location) { | 
| 42 |  | -        let stmt = &self.body[loc.block].statements[loc.statement_index]; | 
|  | 136 | +/// A `Visitor` that defines the transfer function for `MaybeBorrowedLocals`. | 
|  | 137 | +struct TransferFunction<'a, T, K> { | 
|  | 138 | +    trans: &'a mut T, | 
|  | 139 | +    kind: &'a K, | 
|  | 140 | +    ignore_borrow_on_drop: bool, | 
|  | 141 | +} | 
| 43 | 142 | 
 | 
| 44 |  | -        BorrowedLocalsVisitor { trans }.visit_statement(stmt, loc); | 
|  | 143 | +impl<T, K> Visitor<'tcx> for TransferFunction<'a, T, K> | 
|  | 144 | +where | 
|  | 145 | +    T: GenKill<Local>, | 
|  | 146 | +    K: BorrowAnalysisKind<'tcx>, | 
|  | 147 | +{ | 
|  | 148 | +    fn visit_statement(&mut self, stmt: &Statement<'tcx>, location: Location) { | 
|  | 149 | +        self.super_statement(stmt, location); | 
| 45 | 150 | 
 | 
| 46 |  | -        // StorageDead invalidates all borrows and raw pointers to a local | 
| 47 |  | -        match stmt.kind { | 
| 48 |  | -            StatementKind::StorageDead(l) => trans.kill(l), | 
| 49 |  | -            _ => (), | 
|  | 151 | +        // When we reach a `StorageDead` statement, we can assume that any pointers to this memory | 
|  | 152 | +        // are now invalid. | 
|  | 153 | +        if let StatementKind::StorageDead(local) = stmt.kind { | 
|  | 154 | +            self.trans.kill(local); | 
| 50 | 155 |         } | 
| 51 | 156 |     } | 
| 52 | 157 | 
 | 
| 53 |  | -    fn terminator_effect(&self, trans: &mut GenKillSet<Local>, loc: Location) { | 
| 54 |  | -        let terminator = self.body[loc.block].terminator(); | 
| 55 |  | -        BorrowedLocalsVisitor { trans }.visit_terminator(terminator, loc); | 
| 56 |  | -        match &terminator.kind { | 
| 57 |  | -            // Drop terminators borrows the location | 
| 58 |  | -            TerminatorKind::Drop { location, .. } | 
| 59 |  | -            | TerminatorKind::DropAndReplace { location, .. } => { | 
| 60 |  | -                if let Some(local) = find_local(location) { | 
| 61 |  | -                    trans.gen(local); | 
|  | 158 | +    fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: Location) { | 
|  | 159 | +        self.super_rvalue(rvalue, location); | 
|  | 160 | + | 
|  | 161 | +        match rvalue { | 
|  | 162 | +            mir::Rvalue::AddressOf(mt, borrowed_place) => { | 
|  | 163 | +                if !borrowed_place.is_indirect() && self.kind.in_address_of(*mt, borrowed_place) { | 
|  | 164 | +                    self.trans.gen(borrowed_place.local); | 
| 62 | 165 |                 } | 
| 63 | 166 |             } | 
| 64 |  | -            _ => (), | 
|  | 167 | + | 
|  | 168 | +            mir::Rvalue::Ref(_, kind, borrowed_place) => { | 
|  | 169 | +                if !borrowed_place.is_indirect() && self.kind.in_ref(*kind, borrowed_place) { | 
|  | 170 | +                    self.trans.gen(borrowed_place.local); | 
|  | 171 | +                } | 
|  | 172 | +            } | 
|  | 173 | + | 
|  | 174 | +            mir::Rvalue::Cast(..) | 
|  | 175 | +            | mir::Rvalue::Use(..) | 
|  | 176 | +            | mir::Rvalue::Repeat(..) | 
|  | 177 | +            | mir::Rvalue::Len(..) | 
|  | 178 | +            | mir::Rvalue::BinaryOp(..) | 
|  | 179 | +            | mir::Rvalue::CheckedBinaryOp(..) | 
|  | 180 | +            | mir::Rvalue::NullaryOp(..) | 
|  | 181 | +            | mir::Rvalue::UnaryOp(..) | 
|  | 182 | +            | mir::Rvalue::Discriminant(..) | 
|  | 183 | +            | mir::Rvalue::Aggregate(..) => {} | 
| 65 | 184 |         } | 
| 66 | 185 |     } | 
| 67 | 186 | 
 | 
| 68 |  | -    fn propagate_call_return( | 
| 69 |  | -        &self, | 
| 70 |  | -        _in_out: &mut BitSet<Local>, | 
| 71 |  | -        _call_bb: mir::BasicBlock, | 
| 72 |  | -        _dest_bb: mir::BasicBlock, | 
| 73 |  | -        _dest_place: &mir::Place<'tcx>, | 
| 74 |  | -    ) { | 
| 75 |  | -        // Nothing to do when a call returns successfully | 
|  | 187 | +    fn visit_terminator(&mut self, terminator: &mir::Terminator<'tcx>, location: Location) { | 
|  | 188 | +        self.super_terminator(terminator, location); | 
|  | 189 | + | 
|  | 190 | +        match terminator.kind { | 
|  | 191 | +            mir::TerminatorKind::Drop { location: dropped_place, .. } | 
|  | 192 | +            | mir::TerminatorKind::DropAndReplace { location: dropped_place, .. } => { | 
|  | 193 | +                // See documentation for `unsound_ignore_borrow_on_drop` for an explanation. | 
|  | 194 | +                if !self.ignore_borrow_on_drop { | 
|  | 195 | +                    self.trans.gen(dropped_place.local); | 
|  | 196 | +                } | 
|  | 197 | +            } | 
|  | 198 | + | 
|  | 199 | +            TerminatorKind::Abort | 
|  | 200 | +            | TerminatorKind::Assert { .. } | 
|  | 201 | +            | TerminatorKind::Call { .. } | 
|  | 202 | +            | TerminatorKind::FalseEdges { .. } | 
|  | 203 | +            | TerminatorKind::FalseUnwind { .. } | 
|  | 204 | +            | TerminatorKind::GeneratorDrop | 
|  | 205 | +            | TerminatorKind::Goto { .. } | 
|  | 206 | +            | TerminatorKind::Resume | 
|  | 207 | +            | TerminatorKind::Return | 
|  | 208 | +            | TerminatorKind::SwitchInt { .. } | 
|  | 209 | +            | TerminatorKind::Unreachable | 
|  | 210 | +            | TerminatorKind::Yield { .. } => {} | 
|  | 211 | +        } | 
| 76 | 212 |     } | 
| 77 | 213 | } | 
| 78 | 214 | 
 | 
| 79 |  | -impl<'a, 'tcx> BottomValue for HaveBeenBorrowedLocals<'a, 'tcx> { | 
| 80 |  | -    // bottom = unborrowed | 
| 81 |  | -    const BOTTOM_VALUE: bool = false; | 
|  | 215 | +pub struct AnyBorrow; | 
|  | 216 | + | 
|  | 217 | +pub struct MutBorrow<'mir, 'tcx> { | 
|  | 218 | +    tcx: TyCtxt<'tcx>, | 
|  | 219 | +    body: &'mir Body<'tcx>, | 
|  | 220 | +    param_env: ParamEnv<'tcx>, | 
|  | 221 | +} | 
|  | 222 | + | 
|  | 223 | +impl MutBorrow<'mir, 'tcx> { | 
|  | 224 | +    /// `&` and `&raw` only allow mutation if the borrowed place is `!Freeze`. | 
|  | 225 | +    /// | 
|  | 226 | +    /// This assumes that it is UB to take the address of a struct field whose type is | 
|  | 227 | +    /// `Freeze`, then use pointer arithmetic to derive a pointer to a *different* field of | 
|  | 228 | +    /// that same struct whose type is `!Freeze`. If we decide that this is not UB, we will | 
|  | 229 | +    /// have to check the type of the borrowed **local** instead of the borrowed **place** | 
|  | 230 | +    /// below. See [rust-lang/unsafe-code-guidelines#134]. | 
|  | 231 | +    /// | 
|  | 232 | +    /// [rust-lang/unsafe-code-guidelines#134]: https://github.com/rust-lang/unsafe-code-guidelines/issues/134 | 
|  | 233 | +    fn shared_borrow_allows_mutation(&self, place: &Place<'tcx>) -> bool { | 
|  | 234 | +        !place.ty(self.body, self.tcx).ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) | 
|  | 235 | +    } | 
| 82 | 236 | } | 
| 83 | 237 | 
 | 
| 84 |  | -struct BorrowedLocalsVisitor<'gk> { | 
| 85 |  | -    trans: &'gk mut GenKillSet<Local>, | 
|  | 238 | +pub trait BorrowAnalysisKind<'tcx> { | 
|  | 239 | +    const ANALYSIS_NAME: &'static str; | 
|  | 240 | + | 
|  | 241 | +    fn in_address_of(&self, mt: Mutability, place: &Place<'tcx>) -> bool; | 
|  | 242 | +    fn in_ref(&self, kind: mir::BorrowKind, place: &Place<'tcx>) -> bool; | 
| 86 | 243 | } | 
| 87 | 244 | 
 | 
| 88 |  | -fn find_local(place: &Place<'_>) -> Option<Local> { | 
| 89 |  | -    if !place.is_indirect() { Some(place.local) } else { None } | 
|  | 245 | +impl BorrowAnalysisKind<'tcx> for AnyBorrow { | 
|  | 246 | +    const ANALYSIS_NAME: &'static str = "maybe_borrowed_locals"; | 
|  | 247 | + | 
|  | 248 | +    fn in_ref(&self, _: mir::BorrowKind, _: &Place<'_>) -> bool { | 
|  | 249 | +        true | 
|  | 250 | +    } | 
|  | 251 | +    fn in_address_of(&self, _: Mutability, _: &Place<'_>) -> bool { | 
|  | 252 | +        true | 
|  | 253 | +    } | 
| 90 | 254 | } | 
| 91 | 255 | 
 | 
| 92 |  | -impl<'tcx> Visitor<'tcx> for BorrowedLocalsVisitor<'_> { | 
| 93 |  | -    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { | 
| 94 |  | -        if let Rvalue::Ref(_, _, ref place) = *rvalue { | 
| 95 |  | -            if let Some(local) = find_local(place) { | 
| 96 |  | -                self.trans.gen(local); | 
|  | 256 | +impl BorrowAnalysisKind<'tcx> for MutBorrow<'mir, 'tcx> { | 
|  | 257 | +    const ANALYSIS_NAME: &'static str = "maybe_mut_borrowed_locals"; | 
|  | 258 | + | 
|  | 259 | +    fn in_ref(&self, kind: mir::BorrowKind, place: &Place<'tcx>) -> bool { | 
|  | 260 | +        match kind { | 
|  | 261 | +            mir::BorrowKind::Mut { .. } => true, | 
|  | 262 | +            mir::BorrowKind::Shared | mir::BorrowKind::Shallow | mir::BorrowKind::Unique => { | 
|  | 263 | +                self.shared_borrow_allows_mutation(place) | 
| 97 | 264 |             } | 
| 98 | 265 |         } | 
|  | 266 | +    } | 
| 99 | 267 | 
 | 
| 100 |  | -        self.super_rvalue(rvalue, location) | 
|  | 268 | +    fn in_address_of(&self, mt: Mutability, place: &Place<'tcx>) -> bool { | 
|  | 269 | +        match mt { | 
|  | 270 | +            Mutability::Mut => true, | 
|  | 271 | +            Mutability::Not => self.shared_borrow_allows_mutation(place), | 
|  | 272 | +        } | 
| 101 | 273 |     } | 
| 102 | 274 | } | 
0 commit comments